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/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 using llvm::RoundingMode; 54 55 /// Determine whether the use of this declaration is valid, without 56 /// emitting diagnostics. 57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 58 // See if this is an auto-typed variable whose initializer we are parsing. 59 if (ParsingInitForAutoVars.count(D)) 60 return false; 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) 65 return false; 66 67 // If the function has a deduced return type, and we can't deduce it, 68 // then we can't use it either. 69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 71 return false; 72 73 // See if this is an aligned allocation/deallocation function that is 74 // unavailable. 75 if (TreatUnavailableAsInvalid && 76 isUnavailableAlignedAllocationFunction(*FD)) 77 return false; 78 } 79 80 // See if this function is unavailable. 81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 83 return false; 84 85 return true; 86 } 87 88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 89 // Warn if this is used but marked unused. 90 if (const auto *A = D->getAttr<UnusedAttr>()) { 91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 92 // should diagnose them. 93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 96 if (DC && !DC->hasAttr<UnusedAttr>()) 97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 98 } 99 } 100 } 101 102 /// Emit a note explaining that this function is deleted. 103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 104 assert(Decl && Decl->isDeleted()); 105 106 if (Decl->isDefaulted()) { 107 // If the method was explicitly defaulted, point at that declaration. 108 if (!Decl->isImplicit()) 109 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 110 111 // Try to diagnose why this special member function was implicitly 112 // deleted. This might fail, if that reason no longer applies. 113 DiagnoseDeletedDefaultedFunction(Decl); 114 return; 115 } 116 117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 118 if (Ctor && Ctor->isInheritingConstructor()) 119 return NoteDeletedInheritingConstructor(Ctor); 120 121 Diag(Decl->getLocation(), diag::note_availability_specified_here) 122 << Decl << 1; 123 } 124 125 /// Determine whether a FunctionDecl was ever declared with an 126 /// explicit storage class. 127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 128 for (auto I : D->redecls()) { 129 if (I->getStorageClass() != SC_None) 130 return true; 131 } 132 return false; 133 } 134 135 /// Check whether we're in an extern inline function and referring to a 136 /// variable or function with internal linkage (C11 6.7.4p3). 137 /// 138 /// This is only a warning because we used to silently accept this code, but 139 /// in many cases it will not behave correctly. This is not enabled in C++ mode 140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 141 /// and so while there may still be user mistakes, most of the time we can't 142 /// prove that there are errors. 143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 144 const NamedDecl *D, 145 SourceLocation Loc) { 146 // This is disabled under C++; there are too many ways for this to fire in 147 // contexts where the warning is a false positive, or where it is technically 148 // correct but benign. 149 if (S.getLangOpts().CPlusPlus) 150 return; 151 152 // Check if this is an inlined function or method. 153 FunctionDecl *Current = S.getCurFunctionDecl(); 154 if (!Current) 155 return; 156 if (!Current->isInlined()) 157 return; 158 if (!Current->isExternallyVisible()) 159 return; 160 161 // Check if the decl has internal linkage. 162 if (D->getFormalLinkage() != InternalLinkage) 163 return; 164 165 // Downgrade from ExtWarn to Extension if 166 // (1) the supposedly external inline function is in the main file, 167 // and probably won't be included anywhere else. 168 // (2) the thing we're referencing is a pure function. 169 // (3) the thing we're referencing is another inline function. 170 // This last can give us false negatives, but it's better than warning on 171 // wrappers for simple C library functions. 172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 174 if (!DowngradeWarning && UsedFn) 175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 176 177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 178 : diag::ext_internal_in_extern_inline) 179 << /*IsVar=*/!UsedFn << D; 180 181 S.MaybeSuggestAddingStaticToDecl(Current); 182 183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 184 << D; 185 } 186 187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 188 const FunctionDecl *First = Cur->getFirstDecl(); 189 190 // Suggest "static" on the function, if possible. 191 if (!hasAnyExplicitStorageClass(First)) { 192 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 193 Diag(DeclBegin, diag::note_convert_inline_to_static) 194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 195 } 196 } 197 198 /// Determine whether the use of this declaration is valid, and 199 /// emit any corresponding diagnostics. 200 /// 201 /// This routine diagnoses various problems with referencing 202 /// declarations that can occur when using a declaration. For example, 203 /// it might warn if a deprecated or unavailable declaration is being 204 /// used, or produce an error (and return true) if a C++0x deleted 205 /// function is being used. 206 /// 207 /// \returns true if there was an error (this declaration cannot be 208 /// referenced), false otherwise. 209 /// 210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 211 const ObjCInterfaceDecl *UnknownObjCClass, 212 bool ObjCPropertyAccess, 213 bool AvoidPartialAvailabilityChecks, 214 ObjCInterfaceDecl *ClassReceiver) { 215 SourceLocation Loc = Locs.front(); 216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 217 // If there were any diagnostics suppressed by template argument deduction, 218 // emit them now. 219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 220 if (Pos != SuppressedDiagnostics.end()) { 221 for (const PartialDiagnosticAt &Suppressed : Pos->second) 222 Diag(Suppressed.first, Suppressed.second); 223 224 // Clear out the list of suppressed diagnostics, so that we don't emit 225 // them again for this specialization. However, we don't obsolete this 226 // entry from the table, because we want to avoid ever emitting these 227 // diagnostics again. 228 Pos->second.clear(); 229 } 230 231 // C++ [basic.start.main]p3: 232 // The function 'main' shall not be used within a program. 233 if (cast<FunctionDecl>(D)->isMain()) 234 Diag(Loc, diag::ext_main_used); 235 236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 237 } 238 239 // See if this is an auto-typed variable whose initializer we are parsing. 240 if (ParsingInitForAutoVars.count(D)) { 241 if (isa<BindingDecl>(D)) { 242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 243 << D->getDeclName(); 244 } else { 245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 246 << D->getDeclName() << cast<VarDecl>(D)->getType(); 247 } 248 return true; 249 } 250 251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 252 // See if this is a deleted function. 253 if (FD->isDeleted()) { 254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 255 if (Ctor && Ctor->isInheritingConstructor()) 256 Diag(Loc, diag::err_deleted_inherited_ctor_use) 257 << Ctor->getParent() 258 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 259 else 260 Diag(Loc, diag::err_deleted_function_use); 261 NoteDeletedFunction(FD); 262 return true; 263 } 264 265 // [expr.prim.id]p4 266 // A program that refers explicitly or implicitly to a function with a 267 // trailing requires-clause whose constraint-expression is not satisfied, 268 // other than to declare it, is ill-formed. [...] 269 // 270 // See if this is a function with constraints that need to be satisfied. 271 // Check this before deducing the return type, as it might instantiate the 272 // definition. 273 if (FD->getTrailingRequiresClause()) { 274 ConstraintSatisfaction Satisfaction; 275 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 276 // A diagnostic will have already been generated (non-constant 277 // constraint expression, for example) 278 return true; 279 if (!Satisfaction.IsSatisfied) { 280 Diag(Loc, 281 diag::err_reference_to_function_with_unsatisfied_constraints) 282 << D; 283 DiagnoseUnsatisfiedConstraint(Satisfaction); 284 return true; 285 } 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 295 return true; 296 297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 298 return true; 299 } 300 301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 302 // Lambdas are only default-constructible or assignable in C++2a onwards. 303 if (MD->getParent()->isLambda() && 304 ((isa<CXXConstructorDecl>(MD) && 305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 308 << !isa<CXXConstructorDecl>(MD); 309 } 310 } 311 312 auto getReferencedObjCProp = [](const NamedDecl *D) -> 313 const ObjCPropertyDecl * { 314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 315 return MD->findPropertyDecl(); 316 return nullptr; 317 }; 318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 320 return true; 321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 322 return true; 323 } 324 325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 326 // Only the variables omp_in and omp_out are allowed in the combiner. 327 // Only the variables omp_priv and omp_orig are allowed in the 328 // initializer-clause. 329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 331 isa<VarDecl>(D)) { 332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 333 << getCurFunction()->HasOMPDeclareReductionCombiner; 334 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 335 return true; 336 } 337 338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 339 // List-items in map clauses on this construct may only refer to the declared 340 // variable var and entities that could be referenced by a procedure defined 341 // at the same location 342 if (LangOpts.OpenMP && isa<VarDecl>(D) && 343 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 344 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 345 << getOpenMPDeclareMapperVarName(); 346 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 347 return true; 348 } 349 350 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 351 AvoidPartialAvailabilityChecks, ClassReceiver); 352 353 DiagnoseUnusedOfDecl(*this, D, Loc); 354 355 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 356 357 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 358 if (const auto *VD = dyn_cast<ValueDecl>(D)) 359 checkDeviceDecl(VD, Loc); 360 361 if (!Context.getTargetInfo().isTLSSupported()) 362 if (const auto *VD = dyn_cast<VarDecl>(D)) 363 if (VD->getTLSKind() != VarDecl::TLS_None) 364 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 365 } 366 367 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 368 !isUnevaluatedContext()) { 369 // C++ [expr.prim.req.nested] p3 370 // A local parameter shall only appear as an unevaluated operand 371 // (Clause 8) within the constraint-expression. 372 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 373 << D; 374 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 375 return true; 376 } 377 378 return false; 379 } 380 381 /// DiagnoseSentinelCalls - This routine checks whether a call or 382 /// message-send is to a declaration with the sentinel attribute, and 383 /// if so, it checks that the requirements of the sentinel are 384 /// satisfied. 385 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 386 ArrayRef<Expr *> Args) { 387 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 388 if (!attr) 389 return; 390 391 // The number of formal parameters of the declaration. 392 unsigned numFormalParams; 393 394 // The kind of declaration. This is also an index into a %select in 395 // the diagnostic. 396 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 397 398 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 399 numFormalParams = MD->param_size(); 400 calleeType = CT_Method; 401 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 402 numFormalParams = FD->param_size(); 403 calleeType = CT_Function; 404 } else if (isa<VarDecl>(D)) { 405 QualType type = cast<ValueDecl>(D)->getType(); 406 const FunctionType *fn = nullptr; 407 if (const PointerType *ptr = type->getAs<PointerType>()) { 408 fn = ptr->getPointeeType()->getAs<FunctionType>(); 409 if (!fn) return; 410 calleeType = CT_Function; 411 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 412 fn = ptr->getPointeeType()->castAs<FunctionType>(); 413 calleeType = CT_Block; 414 } else { 415 return; 416 } 417 418 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 419 numFormalParams = proto->getNumParams(); 420 } else { 421 numFormalParams = 0; 422 } 423 } else { 424 return; 425 } 426 427 // "nullPos" is the number of formal parameters at the end which 428 // effectively count as part of the variadic arguments. This is 429 // useful if you would prefer to not have *any* formal parameters, 430 // but the language forces you to have at least one. 431 unsigned nullPos = attr->getNullPos(); 432 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 433 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 434 435 // The number of arguments which should follow the sentinel. 436 unsigned numArgsAfterSentinel = attr->getSentinel(); 437 438 // If there aren't enough arguments for all the formal parameters, 439 // the sentinel, and the args after the sentinel, complain. 440 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 441 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 442 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 443 return; 444 } 445 446 // Otherwise, find the sentinel expression. 447 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 448 if (!sentinelExpr) return; 449 if (sentinelExpr->isValueDependent()) return; 450 if (Context.isSentinelNullExpr(sentinelExpr)) return; 451 452 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 453 // or 'NULL' if those are actually defined in the context. Only use 454 // 'nil' for ObjC methods, where it's much more likely that the 455 // variadic arguments form a list of object pointers. 456 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 457 std::string NullValue; 458 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 459 NullValue = "nil"; 460 else if (getLangOpts().CPlusPlus11) 461 NullValue = "nullptr"; 462 else if (PP.isMacroDefined("NULL")) 463 NullValue = "NULL"; 464 else 465 NullValue = "(void*) 0"; 466 467 if (MissingNilLoc.isInvalid()) 468 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 469 else 470 Diag(MissingNilLoc, diag::warn_missing_sentinel) 471 << int(calleeType) 472 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 473 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 474 } 475 476 SourceRange Sema::getExprRange(Expr *E) const { 477 return E ? E->getSourceRange() : SourceRange(); 478 } 479 480 //===----------------------------------------------------------------------===// 481 // Standard Promotions and Conversions 482 //===----------------------------------------------------------------------===// 483 484 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 485 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 486 // Handle any placeholder expressions which made it here. 487 if (E->getType()->isPlaceholderType()) { 488 ExprResult result = CheckPlaceholderExpr(E); 489 if (result.isInvalid()) return ExprError(); 490 E = result.get(); 491 } 492 493 QualType Ty = E->getType(); 494 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 495 496 if (Ty->isFunctionType()) { 497 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 498 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 499 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 500 return ExprError(); 501 502 E = ImpCastExprToType(E, Context.getPointerType(Ty), 503 CK_FunctionToPointerDecay).get(); 504 } else if (Ty->isArrayType()) { 505 // In C90 mode, arrays only promote to pointers if the array expression is 506 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 507 // type 'array of type' is converted to an expression that has type 'pointer 508 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 509 // that has type 'array of type' ...". The relevant change is "an lvalue" 510 // (C90) to "an expression" (C99). 511 // 512 // C++ 4.2p1: 513 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 514 // T" can be converted to an rvalue of type "pointer to T". 515 // 516 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 517 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 518 CK_ArrayToPointerDecay).get(); 519 } 520 return E; 521 } 522 523 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 524 // Check to see if we are dereferencing a null pointer. If so, 525 // and if not volatile-qualified, this is undefined behavior that the 526 // optimizer will delete, so warn about it. People sometimes try to use this 527 // to get a deterministic trap and are surprised by clang's behavior. This 528 // only handles the pattern "*null", which is a very syntactic check. 529 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 530 if (UO && UO->getOpcode() == UO_Deref && 531 UO->getSubExpr()->getType()->isPointerType()) { 532 const LangAS AS = 533 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 534 if ((!isTargetAddressSpace(AS) || 535 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 536 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 537 S.Context, Expr::NPC_ValueDependentIsNotNull) && 538 !UO->getType().isVolatileQualified()) { 539 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 540 S.PDiag(diag::warn_indirection_through_null) 541 << UO->getSubExpr()->getSourceRange()); 542 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 543 S.PDiag(diag::note_indirection_through_null)); 544 } 545 } 546 } 547 548 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 549 SourceLocation AssignLoc, 550 const Expr* RHS) { 551 const ObjCIvarDecl *IV = OIRE->getDecl(); 552 if (!IV) 553 return; 554 555 DeclarationName MemberName = IV->getDeclName(); 556 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 557 if (!Member || !Member->isStr("isa")) 558 return; 559 560 const Expr *Base = OIRE->getBase(); 561 QualType BaseType = Base->getType(); 562 if (OIRE->isArrow()) 563 BaseType = BaseType->getPointeeType(); 564 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 565 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 566 ObjCInterfaceDecl *ClassDeclared = nullptr; 567 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 568 if (!ClassDeclared->getSuperClass() 569 && (*ClassDeclared->ivar_begin()) == IV) { 570 if (RHS) { 571 NamedDecl *ObjectSetClass = 572 S.LookupSingleName(S.TUScope, 573 &S.Context.Idents.get("object_setClass"), 574 SourceLocation(), S.LookupOrdinaryName); 575 if (ObjectSetClass) { 576 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 577 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 578 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 579 "object_setClass(") 580 << FixItHint::CreateReplacement( 581 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 582 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 583 } 584 else 585 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 586 } else { 587 NamedDecl *ObjectGetClass = 588 S.LookupSingleName(S.TUScope, 589 &S.Context.Idents.get("object_getClass"), 590 SourceLocation(), S.LookupOrdinaryName); 591 if (ObjectGetClass) 592 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 593 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 594 "object_getClass(") 595 << FixItHint::CreateReplacement( 596 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 597 else 598 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 599 } 600 S.Diag(IV->getLocation(), diag::note_ivar_decl); 601 } 602 } 603 } 604 605 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 606 // Handle any placeholder expressions which made it here. 607 if (E->getType()->isPlaceholderType()) { 608 ExprResult result = CheckPlaceholderExpr(E); 609 if (result.isInvalid()) return ExprError(); 610 E = result.get(); 611 } 612 613 // C++ [conv.lval]p1: 614 // A glvalue of a non-function, non-array type T can be 615 // converted to a prvalue. 616 if (!E->isGLValue()) return E; 617 618 QualType T = E->getType(); 619 assert(!T.isNull() && "r-value conversion on typeless expression?"); 620 621 // lvalue-to-rvalue conversion cannot be applied to function or array types. 622 if (T->isFunctionType() || T->isArrayType()) 623 return E; 624 625 // We don't want to throw lvalue-to-rvalue casts on top of 626 // expressions of certain types in C++. 627 if (getLangOpts().CPlusPlus && 628 (E->getType() == Context.OverloadTy || 629 T->isDependentType() || 630 T->isRecordType())) 631 return E; 632 633 // The C standard is actually really unclear on this point, and 634 // DR106 tells us what the result should be but not why. It's 635 // generally best to say that void types just doesn't undergo 636 // lvalue-to-rvalue at all. Note that expressions of unqualified 637 // 'void' type are never l-values, but qualified void can be. 638 if (T->isVoidType()) 639 return E; 640 641 // OpenCL usually rejects direct accesses to values of 'half' type. 642 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 643 T->isHalfType()) { 644 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 645 << 0 << T; 646 return ExprError(); 647 } 648 649 CheckForNullPointerDereference(*this, E); 650 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 651 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 652 &Context.Idents.get("object_getClass"), 653 SourceLocation(), LookupOrdinaryName); 654 if (ObjectGetClass) 655 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 656 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 657 << FixItHint::CreateReplacement( 658 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 659 else 660 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 661 } 662 else if (const ObjCIvarRefExpr *OIRE = 663 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 664 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 665 666 // C++ [conv.lval]p1: 667 // [...] If T is a non-class type, the type of the prvalue is the 668 // cv-unqualified version of T. Otherwise, the type of the 669 // rvalue is T. 670 // 671 // C99 6.3.2.1p2: 672 // If the lvalue has qualified type, the value has the unqualified 673 // version of the type of the lvalue; otherwise, the value has the 674 // type of the lvalue. 675 if (T.hasQualifiers()) 676 T = T.getUnqualifiedType(); 677 678 // Under the MS ABI, lock down the inheritance model now. 679 if (T->isMemberPointerType() && 680 Context.getTargetInfo().getCXXABI().isMicrosoft()) 681 (void)isCompleteType(E->getExprLoc(), T); 682 683 ExprResult Res = CheckLValueToRValueConversionOperand(E); 684 if (Res.isInvalid()) 685 return Res; 686 E = Res.get(); 687 688 // Loading a __weak object implicitly retains the value, so we need a cleanup to 689 // balance that. 690 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 691 Cleanup.setExprNeedsCleanups(true); 692 693 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 694 Cleanup.setExprNeedsCleanups(true); 695 696 // C++ [conv.lval]p3: 697 // If T is cv std::nullptr_t, the result is a null pointer constant. 698 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 699 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 700 FPOptionsOverride()); 701 702 // C11 6.3.2.1p2: 703 // ... if the lvalue has atomic type, the value has the non-atomic version 704 // of the type of the lvalue ... 705 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 706 T = Atomic->getValueType().getUnqualifiedType(); 707 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 708 nullptr, VK_RValue, FPOptionsOverride()); 709 } 710 711 return Res; 712 } 713 714 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 715 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 716 if (Res.isInvalid()) 717 return ExprError(); 718 Res = DefaultLvalueConversion(Res.get()); 719 if (Res.isInvalid()) 720 return ExprError(); 721 return Res; 722 } 723 724 /// CallExprUnaryConversions - a special case of an unary conversion 725 /// performed on a function designator of a call expression. 726 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 727 QualType Ty = E->getType(); 728 ExprResult Res = E; 729 // Only do implicit cast for a function type, but not for a pointer 730 // to function type. 731 if (Ty->isFunctionType()) { 732 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 733 CK_FunctionToPointerDecay); 734 if (Res.isInvalid()) 735 return ExprError(); 736 } 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res.get(); 741 } 742 743 /// UsualUnaryConversions - Performs various conversions that are common to most 744 /// operators (C99 6.3). The conversions of array and function types are 745 /// sometimes suppressed. For example, the array->pointer conversion doesn't 746 /// apply if the array is an argument to the sizeof or address (&) operators. 747 /// In these instances, this routine should *not* be called. 748 ExprResult Sema::UsualUnaryConversions(Expr *E) { 749 // First, convert to an r-value. 750 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 751 if (Res.isInvalid()) 752 return ExprError(); 753 E = Res.get(); 754 755 QualType Ty = E->getType(); 756 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 757 758 // Half FP have to be promoted to float unless it is natively supported 759 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 760 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 761 762 // Try to perform integral promotions if the object has a theoretically 763 // promotable type. 764 if (Ty->isIntegralOrUnscopedEnumerationType()) { 765 // C99 6.3.1.1p2: 766 // 767 // The following may be used in an expression wherever an int or 768 // unsigned int may be used: 769 // - an object or expression with an integer type whose integer 770 // conversion rank is less than or equal to the rank of int 771 // and unsigned int. 772 // - A bit-field of type _Bool, int, signed int, or unsigned int. 773 // 774 // If an int can represent all values of the original type, the 775 // value is converted to an int; otherwise, it is converted to an 776 // unsigned int. These are called the integer promotions. All 777 // other types are unchanged by the integer promotions. 778 779 QualType PTy = Context.isPromotableBitField(E); 780 if (!PTy.isNull()) { 781 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 782 return E; 783 } 784 if (Ty->isPromotableIntegerType()) { 785 QualType PT = Context.getPromotedIntegerType(Ty); 786 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 787 return E; 788 } 789 } 790 return E; 791 } 792 793 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 794 /// do not have a prototype. Arguments that have type float or __fp16 795 /// are promoted to double. All other argument types are converted by 796 /// UsualUnaryConversions(). 797 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 798 QualType Ty = E->getType(); 799 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 800 801 ExprResult Res = UsualUnaryConversions(E); 802 if (Res.isInvalid()) 803 return ExprError(); 804 E = Res.get(); 805 806 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 807 // promote to double. 808 // Note that default argument promotion applies only to float (and 809 // half/fp16); it does not apply to _Float16. 810 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 811 if (BTy && (BTy->getKind() == BuiltinType::Half || 812 BTy->getKind() == BuiltinType::Float)) { 813 if (getLangOpts().OpenCL && 814 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 815 if (BTy->getKind() == BuiltinType::Half) { 816 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 817 } 818 } else { 819 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 820 } 821 } 822 823 // C++ performs lvalue-to-rvalue conversion as a default argument 824 // promotion, even on class types, but note: 825 // C++11 [conv.lval]p2: 826 // When an lvalue-to-rvalue conversion occurs in an unevaluated 827 // operand or a subexpression thereof the value contained in the 828 // referenced object is not accessed. Otherwise, if the glvalue 829 // has a class type, the conversion copy-initializes a temporary 830 // of type T from the glvalue and the result of the conversion 831 // is a prvalue for the temporary. 832 // FIXME: add some way to gate this entire thing for correctness in 833 // potentially potentially evaluated contexts. 834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 835 ExprResult Temp = PerformCopyInitialization( 836 InitializedEntity::InitializeTemporary(E->getType()), 837 E->getExprLoc(), E); 838 if (Temp.isInvalid()) 839 return ExprError(); 840 E = Temp.get(); 841 } 842 843 return E; 844 } 845 846 /// Determine the degree of POD-ness for an expression. 847 /// Incomplete types are considered POD, since this check can be performed 848 /// when we're in an unevaluated context. 849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 850 if (Ty->isIncompleteType()) { 851 // C++11 [expr.call]p7: 852 // After these conversions, if the argument does not have arithmetic, 853 // enumeration, pointer, pointer to member, or class type, the program 854 // is ill-formed. 855 // 856 // Since we've already performed array-to-pointer and function-to-pointer 857 // decay, the only such type in C++ is cv void. This also handles 858 // initializer lists as variadic arguments. 859 if (Ty->isVoidType()) 860 return VAK_Invalid; 861 862 if (Ty->isObjCObjectType()) 863 return VAK_Invalid; 864 return VAK_Valid; 865 } 866 867 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 868 return VAK_Invalid; 869 870 if (Ty.isCXX98PODType(Context)) 871 return VAK_Valid; 872 873 // C++11 [expr.call]p7: 874 // Passing a potentially-evaluated argument of class type (Clause 9) 875 // having a non-trivial copy constructor, a non-trivial move constructor, 876 // or a non-trivial destructor, with no corresponding parameter, 877 // is conditionally-supported with implementation-defined semantics. 878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 880 if (!Record->hasNonTrivialCopyConstructor() && 881 !Record->hasNonTrivialMoveConstructor() && 882 !Record->hasNonTrivialDestructor()) 883 return VAK_ValidInCXX11; 884 885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 886 return VAK_Valid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 891 if (getLangOpts().MSVCCompat) 892 return VAK_MSVCUndefined; 893 894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 895 // permitted to reject them. We should consider doing so. 896 return VAK_Undefined; 897 } 898 899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 900 // Don't allow one to pass an Objective-C interface to a vararg. 901 const QualType &Ty = E->getType(); 902 VarArgKind VAK = isValidVarArgType(Ty); 903 904 // Complain about passing non-POD types through varargs. 905 switch (VAK) { 906 case VAK_ValidInCXX11: 907 DiagRuntimeBehavior( 908 E->getBeginLoc(), nullptr, 909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 910 LLVM_FALLTHROUGH; 911 case VAK_Valid: 912 if (Ty->isRecordType()) { 913 // This is unlikely to be what the user intended. If the class has a 914 // 'c_str' member function, the user probably meant to call that. 915 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 916 PDiag(diag::warn_pass_class_arg_to_vararg) 917 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 918 } 919 break; 920 921 case VAK_Undefined: 922 case VAK_MSVCUndefined: 923 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 924 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 925 << getLangOpts().CPlusPlus11 << Ty << CT); 926 break; 927 928 case VAK_Invalid: 929 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 930 Diag(E->getBeginLoc(), 931 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 932 << Ty << CT; 933 else if (Ty->isObjCObjectType()) 934 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 935 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 936 << Ty << CT); 937 else 938 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 939 << isa<InitListExpr>(E) << Ty << CT; 940 break; 941 } 942 } 943 944 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 945 /// will create a trap if the resulting type is not a POD type. 946 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 947 FunctionDecl *FDecl) { 948 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 949 // Strip the unbridged-cast placeholder expression off, if applicable. 950 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 951 (CT == VariadicMethod || 952 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 953 E = stripARCUnbridgedCast(E); 954 955 // Otherwise, do normal placeholder checking. 956 } else { 957 ExprResult ExprRes = CheckPlaceholderExpr(E); 958 if (ExprRes.isInvalid()) 959 return ExprError(); 960 E = ExprRes.get(); 961 } 962 } 963 964 ExprResult ExprRes = DefaultArgumentPromotion(E); 965 if (ExprRes.isInvalid()) 966 return ExprError(); 967 968 // Copy blocks to the heap. 969 if (ExprRes.get()->getType()->isBlockPointerType()) 970 maybeExtendBlockObject(ExprRes); 971 972 E = ExprRes.get(); 973 974 // Diagnostics regarding non-POD argument types are 975 // emitted along with format string checking in Sema::CheckFunctionCall(). 976 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 977 // Turn this into a trap. 978 CXXScopeSpec SS; 979 SourceLocation TemplateKWLoc; 980 UnqualifiedId Name; 981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 982 E->getBeginLoc()); 983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 984 /*HasTrailingLParen=*/true, 985 /*IsAddressOfOperand=*/false); 986 if (TrapFn.isInvalid()) 987 return ExprError(); 988 989 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 990 None, E->getEndLoc()); 991 if (Call.isInvalid()) 992 return ExprError(); 993 994 ExprResult Comma = 995 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 996 if (Comma.isInvalid()) 997 return ExprError(); 998 return Comma.get(); 999 } 1000 1001 if (!getLangOpts().CPlusPlus && 1002 RequireCompleteType(E->getExprLoc(), E->getType(), 1003 diag::err_call_incomplete_argument)) 1004 return ExprError(); 1005 1006 return E; 1007 } 1008 1009 /// Converts an integer to complex float type. Helper function of 1010 /// UsualArithmeticConversions() 1011 /// 1012 /// \return false if the integer expression is an integer type and is 1013 /// successfully converted to the complex type. 1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1015 ExprResult &ComplexExpr, 1016 QualType IntTy, 1017 QualType ComplexTy, 1018 bool SkipCast) { 1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1020 if (SkipCast) return false; 1021 if (IntTy->isIntegerType()) { 1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1025 CK_FloatingRealToComplex); 1026 } else { 1027 assert(IntTy->isComplexIntegerType()); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1029 CK_IntegralComplexToFloatingComplex); 1030 } 1031 return false; 1032 } 1033 1034 /// Handle arithmetic conversion with complex types. Helper function of 1035 /// UsualArithmeticConversions() 1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1037 ExprResult &RHS, QualType LHSType, 1038 QualType RHSType, 1039 bool IsCompAssign) { 1040 // if we have an integer operand, the result is the complex type. 1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1042 /*skipCast*/false)) 1043 return LHSType; 1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1045 /*skipCast*/IsCompAssign)) 1046 return RHSType; 1047 1048 // This handles complex/complex, complex/float, or float/complex. 1049 // When both operands are complex, the shorter operand is converted to the 1050 // type of the longer, and that is the type of the result. This corresponds 1051 // to what is done when combining two real floating-point operands. 1052 // The fun begins when size promotion occur across type domains. 1053 // From H&S 6.3.4: When one operand is complex and the other is a real 1054 // floating-point type, the less precise type is converted, within it's 1055 // real or complex domain, to the precision of the other type. For example, 1056 // when combining a "long double" with a "double _Complex", the 1057 // "double _Complex" is promoted to "long double _Complex". 1058 1059 // Compute the rank of the two types, regardless of whether they are complex. 1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1061 1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1064 QualType LHSElementType = 1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1066 QualType RHSElementType = 1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1068 1069 QualType ResultType = S.Context.getComplexType(LHSElementType); 1070 if (Order < 0) { 1071 // Promote the precision of the LHS if not an assignment. 1072 ResultType = S.Context.getComplexType(RHSElementType); 1073 if (!IsCompAssign) { 1074 if (LHSComplexType) 1075 LHS = 1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1077 else 1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1079 } 1080 } else if (Order > 0) { 1081 // Promote the precision of the RHS. 1082 if (RHSComplexType) 1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1084 else 1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1086 } 1087 return ResultType; 1088 } 1089 1090 /// Handle arithmetic conversion from integer to float. Helper function 1091 /// of UsualArithmeticConversions() 1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1093 ExprResult &IntExpr, 1094 QualType FloatTy, QualType IntTy, 1095 bool ConvertFloat, bool ConvertInt) { 1096 if (IntTy->isIntegerType()) { 1097 if (ConvertInt) 1098 // Convert intExpr to the lhs floating point type. 1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1100 CK_IntegralToFloating); 1101 return FloatTy; 1102 } 1103 1104 // Convert both sides to the appropriate complex float. 1105 assert(IntTy->isComplexIntegerType()); 1106 QualType result = S.Context.getComplexType(FloatTy); 1107 1108 // _Complex int -> _Complex float 1109 if (ConvertInt) 1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1111 CK_IntegralComplexToFloatingComplex); 1112 1113 // float -> _Complex float 1114 if (ConvertFloat) 1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1116 CK_FloatingRealToComplex); 1117 1118 return result; 1119 } 1120 1121 /// Handle arithmethic conversion with floating point types. Helper 1122 /// function of UsualArithmeticConversions() 1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1124 ExprResult &RHS, QualType LHSType, 1125 QualType RHSType, bool IsCompAssign) { 1126 bool LHSFloat = LHSType->isRealFloatingType(); 1127 bool RHSFloat = RHSType->isRealFloatingType(); 1128 1129 // N1169 4.1.4: If one of the operands has a floating type and the other 1130 // operand has a fixed-point type, the fixed-point operand 1131 // is converted to the floating type [...] 1132 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1133 if (LHSFloat) 1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1135 else if (!IsCompAssign) 1136 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1137 return LHSFloat ? LHSType : RHSType; 1138 } 1139 1140 // If we have two real floating types, convert the smaller operand 1141 // to the bigger result. 1142 if (LHSFloat && RHSFloat) { 1143 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1144 if (order > 0) { 1145 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1146 return LHSType; 1147 } 1148 1149 assert(order < 0 && "illegal float comparison"); 1150 if (!IsCompAssign) 1151 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1152 return RHSType; 1153 } 1154 1155 if (LHSFloat) { 1156 // Half FP has to be promoted to float unless it is natively supported 1157 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1158 LHSType = S.Context.FloatTy; 1159 1160 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1161 /*ConvertFloat=*/!IsCompAssign, 1162 /*ConvertInt=*/ true); 1163 } 1164 assert(RHSFloat); 1165 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1166 /*ConvertFloat=*/ true, 1167 /*ConvertInt=*/!IsCompAssign); 1168 } 1169 1170 /// Diagnose attempts to convert between __float128 and long double if 1171 /// there is no support for such conversion. Helper function of 1172 /// UsualArithmeticConversions(). 1173 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1174 QualType RHSType) { 1175 /* No issue converting if at least one of the types is not a floating point 1176 type or the two types have the same rank. 1177 */ 1178 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1179 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1180 return false; 1181 1182 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1183 "The remaining types must be floating point types."); 1184 1185 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1186 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1187 1188 QualType LHSElemType = LHSComplex ? 1189 LHSComplex->getElementType() : LHSType; 1190 QualType RHSElemType = RHSComplex ? 1191 RHSComplex->getElementType() : RHSType; 1192 1193 // No issue if the two types have the same representation 1194 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1195 &S.Context.getFloatTypeSemantics(RHSElemType)) 1196 return false; 1197 1198 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1199 RHSElemType == S.Context.LongDoubleTy); 1200 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1201 RHSElemType == S.Context.Float128Ty); 1202 1203 // We've handled the situation where __float128 and long double have the same 1204 // representation. We allow all conversions for all possible long double types 1205 // except PPC's double double. 1206 return Float128AndLongDouble && 1207 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1208 &llvm::APFloat::PPCDoubleDouble()); 1209 } 1210 1211 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1212 1213 namespace { 1214 /// These helper callbacks are placed in an anonymous namespace to 1215 /// permit their use as function template parameters. 1216 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1217 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1218 } 1219 1220 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1221 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1222 CK_IntegralComplexCast); 1223 } 1224 } 1225 1226 /// Handle integer arithmetic conversions. Helper function of 1227 /// UsualArithmeticConversions() 1228 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1229 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1230 ExprResult &RHS, QualType LHSType, 1231 QualType RHSType, bool IsCompAssign) { 1232 // The rules for this case are in C99 6.3.1.8 1233 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1234 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1235 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1236 if (LHSSigned == RHSSigned) { 1237 // Same signedness; use the higher-ranked type 1238 if (order >= 0) { 1239 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1240 return LHSType; 1241 } else if (!IsCompAssign) 1242 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1243 return RHSType; 1244 } else if (order != (LHSSigned ? 1 : -1)) { 1245 // The unsigned type has greater than or equal rank to the 1246 // signed type, so use the unsigned type 1247 if (RHSSigned) { 1248 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1249 return LHSType; 1250 } else if (!IsCompAssign) 1251 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1252 return RHSType; 1253 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1254 // The two types are different widths; if we are here, that 1255 // means the signed type is larger than the unsigned type, so 1256 // use the signed type. 1257 if (LHSSigned) { 1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1259 return LHSType; 1260 } else if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1262 return RHSType; 1263 } else { 1264 // The signed type is higher-ranked than the unsigned type, 1265 // but isn't actually any bigger (like unsigned int and long 1266 // on most 32-bit systems). Use the unsigned type corresponding 1267 // to the signed type. 1268 QualType result = 1269 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1270 RHS = (*doRHSCast)(S, RHS.get(), result); 1271 if (!IsCompAssign) 1272 LHS = (*doLHSCast)(S, LHS.get(), result); 1273 return result; 1274 } 1275 } 1276 1277 /// Handle conversions with GCC complex int extension. Helper function 1278 /// of UsualArithmeticConversions() 1279 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1280 ExprResult &RHS, QualType LHSType, 1281 QualType RHSType, 1282 bool IsCompAssign) { 1283 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1284 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1285 1286 if (LHSComplexInt && RHSComplexInt) { 1287 QualType LHSEltType = LHSComplexInt->getElementType(); 1288 QualType RHSEltType = RHSComplexInt->getElementType(); 1289 QualType ScalarType = 1290 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1291 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1292 1293 return S.Context.getComplexType(ScalarType); 1294 } 1295 1296 if (LHSComplexInt) { 1297 QualType LHSEltType = LHSComplexInt->getElementType(); 1298 QualType ScalarType = 1299 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1300 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1301 QualType ComplexType = S.Context.getComplexType(ScalarType); 1302 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1303 CK_IntegralRealToComplex); 1304 1305 return ComplexType; 1306 } 1307 1308 assert(RHSComplexInt); 1309 1310 QualType RHSEltType = RHSComplexInt->getElementType(); 1311 QualType ScalarType = 1312 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1313 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1314 QualType ComplexType = S.Context.getComplexType(ScalarType); 1315 1316 if (!IsCompAssign) 1317 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1318 CK_IntegralRealToComplex); 1319 return ComplexType; 1320 } 1321 1322 /// Return the rank of a given fixed point or integer type. The value itself 1323 /// doesn't matter, but the values must be increasing with proper increasing 1324 /// rank as described in N1169 4.1.1. 1325 static unsigned GetFixedPointRank(QualType Ty) { 1326 const auto *BTy = Ty->getAs<BuiltinType>(); 1327 assert(BTy && "Expected a builtin type."); 1328 1329 switch (BTy->getKind()) { 1330 case BuiltinType::ShortFract: 1331 case BuiltinType::UShortFract: 1332 case BuiltinType::SatShortFract: 1333 case BuiltinType::SatUShortFract: 1334 return 1; 1335 case BuiltinType::Fract: 1336 case BuiltinType::UFract: 1337 case BuiltinType::SatFract: 1338 case BuiltinType::SatUFract: 1339 return 2; 1340 case BuiltinType::LongFract: 1341 case BuiltinType::ULongFract: 1342 case BuiltinType::SatLongFract: 1343 case BuiltinType::SatULongFract: 1344 return 3; 1345 case BuiltinType::ShortAccum: 1346 case BuiltinType::UShortAccum: 1347 case BuiltinType::SatShortAccum: 1348 case BuiltinType::SatUShortAccum: 1349 return 4; 1350 case BuiltinType::Accum: 1351 case BuiltinType::UAccum: 1352 case BuiltinType::SatAccum: 1353 case BuiltinType::SatUAccum: 1354 return 5; 1355 case BuiltinType::LongAccum: 1356 case BuiltinType::ULongAccum: 1357 case BuiltinType::SatLongAccum: 1358 case BuiltinType::SatULongAccum: 1359 return 6; 1360 default: 1361 if (BTy->isInteger()) 1362 return 0; 1363 llvm_unreachable("Unexpected fixed point or integer type"); 1364 } 1365 } 1366 1367 /// handleFixedPointConversion - Fixed point operations between fixed 1368 /// point types and integers or other fixed point types do not fall under 1369 /// usual arithmetic conversion since these conversions could result in loss 1370 /// of precsision (N1169 4.1.4). These operations should be calculated with 1371 /// the full precision of their result type (N1169 4.1.6.2.1). 1372 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1373 QualType RHSTy) { 1374 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1375 "Expected at least one of the operands to be a fixed point type"); 1376 assert((LHSTy->isFixedPointOrIntegerType() || 1377 RHSTy->isFixedPointOrIntegerType()) && 1378 "Special fixed point arithmetic operation conversions are only " 1379 "applied to ints or other fixed point types"); 1380 1381 // If one operand has signed fixed-point type and the other operand has 1382 // unsigned fixed-point type, then the unsigned fixed-point operand is 1383 // converted to its corresponding signed fixed-point type and the resulting 1384 // type is the type of the converted operand. 1385 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1386 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1387 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1388 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1389 1390 // The result type is the type with the highest rank, whereby a fixed-point 1391 // conversion rank is always greater than an integer conversion rank; if the 1392 // type of either of the operands is a saturating fixedpoint type, the result 1393 // type shall be the saturating fixed-point type corresponding to the type 1394 // with the highest rank; the resulting value is converted (taking into 1395 // account rounding and overflow) to the precision of the resulting type. 1396 // Same ranks between signed and unsigned types are resolved earlier, so both 1397 // types are either signed or both unsigned at this point. 1398 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1399 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1400 1401 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1402 1403 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1404 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1405 1406 return ResultTy; 1407 } 1408 1409 /// Check that the usual arithmetic conversions can be performed on this pair of 1410 /// expressions that might be of enumeration type. 1411 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1412 SourceLocation Loc, 1413 Sema::ArithConvKind ACK) { 1414 // C++2a [expr.arith.conv]p1: 1415 // If one operand is of enumeration type and the other operand is of a 1416 // different enumeration type or a floating-point type, this behavior is 1417 // deprecated ([depr.arith.conv.enum]). 1418 // 1419 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1420 // Eventually we will presumably reject these cases (in C++23 onwards?). 1421 QualType L = LHS->getType(), R = RHS->getType(); 1422 bool LEnum = L->isUnscopedEnumerationType(), 1423 REnum = R->isUnscopedEnumerationType(); 1424 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1425 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1426 (REnum && L->isFloatingType())) { 1427 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1428 ? diag::warn_arith_conv_enum_float_cxx20 1429 : diag::warn_arith_conv_enum_float) 1430 << LHS->getSourceRange() << RHS->getSourceRange() 1431 << (int)ACK << LEnum << L << R; 1432 } else if (!IsCompAssign && LEnum && REnum && 1433 !S.Context.hasSameUnqualifiedType(L, R)) { 1434 unsigned DiagID; 1435 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1436 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1437 // If either enumeration type is unnamed, it's less likely that the 1438 // user cares about this, but this situation is still deprecated in 1439 // C++2a. Use a different warning group. 1440 DiagID = S.getLangOpts().CPlusPlus20 1441 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1442 : diag::warn_arith_conv_mixed_anon_enum_types; 1443 } else if (ACK == Sema::ACK_Conditional) { 1444 // Conditional expressions are separated out because they have 1445 // historically had a different warning flag. 1446 DiagID = S.getLangOpts().CPlusPlus20 1447 ? diag::warn_conditional_mixed_enum_types_cxx20 1448 : diag::warn_conditional_mixed_enum_types; 1449 } else if (ACK == Sema::ACK_Comparison) { 1450 // Comparison expressions are separated out because they have 1451 // historically had a different warning flag. 1452 DiagID = S.getLangOpts().CPlusPlus20 1453 ? diag::warn_comparison_mixed_enum_types_cxx20 1454 : diag::warn_comparison_mixed_enum_types; 1455 } else { 1456 DiagID = S.getLangOpts().CPlusPlus20 1457 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1458 : diag::warn_arith_conv_mixed_enum_types; 1459 } 1460 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1461 << (int)ACK << L << R; 1462 } 1463 } 1464 1465 /// UsualArithmeticConversions - Performs various conversions that are common to 1466 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1467 /// routine returns the first non-arithmetic type found. The client is 1468 /// responsible for emitting appropriate error diagnostics. 1469 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1470 SourceLocation Loc, 1471 ArithConvKind ACK) { 1472 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1473 1474 if (ACK != ACK_CompAssign) { 1475 LHS = UsualUnaryConversions(LHS.get()); 1476 if (LHS.isInvalid()) 1477 return QualType(); 1478 } 1479 1480 RHS = UsualUnaryConversions(RHS.get()); 1481 if (RHS.isInvalid()) 1482 return QualType(); 1483 1484 // For conversion purposes, we ignore any qualifiers. 1485 // For example, "const float" and "float" are equivalent. 1486 QualType LHSType = 1487 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1488 QualType RHSType = 1489 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1490 1491 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1492 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1493 LHSType = AtomicLHS->getValueType(); 1494 1495 // If both types are identical, no conversion is needed. 1496 if (LHSType == RHSType) 1497 return LHSType; 1498 1499 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1500 // The caller can deal with this (e.g. pointer + int). 1501 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1502 return QualType(); 1503 1504 // Apply unary and bitfield promotions to the LHS's type. 1505 QualType LHSUnpromotedType = LHSType; 1506 if (LHSType->isPromotableIntegerType()) 1507 LHSType = Context.getPromotedIntegerType(LHSType); 1508 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1509 if (!LHSBitfieldPromoteTy.isNull()) 1510 LHSType = LHSBitfieldPromoteTy; 1511 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1512 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1513 1514 // If both types are identical, no conversion is needed. 1515 if (LHSType == RHSType) 1516 return LHSType; 1517 1518 // ExtInt types aren't subject to conversions between them or normal integers, 1519 // so this fails. 1520 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1521 return QualType(); 1522 1523 // At this point, we have two different arithmetic types. 1524 1525 // Diagnose attempts to convert between __float128 and long double where 1526 // such conversions currently can't be handled. 1527 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1528 return QualType(); 1529 1530 // Handle complex types first (C99 6.3.1.8p1). 1531 if (LHSType->isComplexType() || RHSType->isComplexType()) 1532 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1533 ACK == ACK_CompAssign); 1534 1535 // Now handle "real" floating types (i.e. float, double, long double). 1536 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1537 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1538 ACK == ACK_CompAssign); 1539 1540 // Handle GCC complex int extension. 1541 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1542 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1543 ACK == ACK_CompAssign); 1544 1545 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1546 return handleFixedPointConversion(*this, LHSType, RHSType); 1547 1548 // Finally, we have two differing integer types. 1549 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1550 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1551 } 1552 1553 //===----------------------------------------------------------------------===// 1554 // Semantic Analysis for various Expression Types 1555 //===----------------------------------------------------------------------===// 1556 1557 1558 ExprResult 1559 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1560 SourceLocation DefaultLoc, 1561 SourceLocation RParenLoc, 1562 Expr *ControllingExpr, 1563 ArrayRef<ParsedType> ArgTypes, 1564 ArrayRef<Expr *> ArgExprs) { 1565 unsigned NumAssocs = ArgTypes.size(); 1566 assert(NumAssocs == ArgExprs.size()); 1567 1568 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1569 for (unsigned i = 0; i < NumAssocs; ++i) { 1570 if (ArgTypes[i]) 1571 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1572 else 1573 Types[i] = nullptr; 1574 } 1575 1576 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1577 ControllingExpr, 1578 llvm::makeArrayRef(Types, NumAssocs), 1579 ArgExprs); 1580 delete [] Types; 1581 return ER; 1582 } 1583 1584 ExprResult 1585 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1586 SourceLocation DefaultLoc, 1587 SourceLocation RParenLoc, 1588 Expr *ControllingExpr, 1589 ArrayRef<TypeSourceInfo *> Types, 1590 ArrayRef<Expr *> Exprs) { 1591 unsigned NumAssocs = Types.size(); 1592 assert(NumAssocs == Exprs.size()); 1593 1594 // Decay and strip qualifiers for the controlling expression type, and handle 1595 // placeholder type replacement. See committee discussion from WG14 DR423. 1596 { 1597 EnterExpressionEvaluationContext Unevaluated( 1598 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1599 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1600 if (R.isInvalid()) 1601 return ExprError(); 1602 ControllingExpr = R.get(); 1603 } 1604 1605 // The controlling expression is an unevaluated operand, so side effects are 1606 // likely unintended. 1607 if (!inTemplateInstantiation() && 1608 ControllingExpr->HasSideEffects(Context, false)) 1609 Diag(ControllingExpr->getExprLoc(), 1610 diag::warn_side_effects_unevaluated_context); 1611 1612 bool TypeErrorFound = false, 1613 IsResultDependent = ControllingExpr->isTypeDependent(), 1614 ContainsUnexpandedParameterPack 1615 = ControllingExpr->containsUnexpandedParameterPack(); 1616 1617 for (unsigned i = 0; i < NumAssocs; ++i) { 1618 if (Exprs[i]->containsUnexpandedParameterPack()) 1619 ContainsUnexpandedParameterPack = true; 1620 1621 if (Types[i]) { 1622 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1623 ContainsUnexpandedParameterPack = true; 1624 1625 if (Types[i]->getType()->isDependentType()) { 1626 IsResultDependent = true; 1627 } else { 1628 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1629 // complete object type other than a variably modified type." 1630 unsigned D = 0; 1631 if (Types[i]->getType()->isIncompleteType()) 1632 D = diag::err_assoc_type_incomplete; 1633 else if (!Types[i]->getType()->isObjectType()) 1634 D = diag::err_assoc_type_nonobject; 1635 else if (Types[i]->getType()->isVariablyModifiedType()) 1636 D = diag::err_assoc_type_variably_modified; 1637 1638 if (D != 0) { 1639 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1640 << Types[i]->getTypeLoc().getSourceRange() 1641 << Types[i]->getType(); 1642 TypeErrorFound = true; 1643 } 1644 1645 // C11 6.5.1.1p2 "No two generic associations in the same generic 1646 // selection shall specify compatible types." 1647 for (unsigned j = i+1; j < NumAssocs; ++j) 1648 if (Types[j] && !Types[j]->getType()->isDependentType() && 1649 Context.typesAreCompatible(Types[i]->getType(), 1650 Types[j]->getType())) { 1651 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1652 diag::err_assoc_compatible_types) 1653 << Types[j]->getTypeLoc().getSourceRange() 1654 << Types[j]->getType() 1655 << Types[i]->getType(); 1656 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1657 diag::note_compat_assoc) 1658 << Types[i]->getTypeLoc().getSourceRange() 1659 << Types[i]->getType(); 1660 TypeErrorFound = true; 1661 } 1662 } 1663 } 1664 } 1665 if (TypeErrorFound) 1666 return ExprError(); 1667 1668 // If we determined that the generic selection is result-dependent, don't 1669 // try to compute the result expression. 1670 if (IsResultDependent) 1671 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1672 Exprs, DefaultLoc, RParenLoc, 1673 ContainsUnexpandedParameterPack); 1674 1675 SmallVector<unsigned, 1> CompatIndices; 1676 unsigned DefaultIndex = -1U; 1677 for (unsigned i = 0; i < NumAssocs; ++i) { 1678 if (!Types[i]) 1679 DefaultIndex = i; 1680 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1681 Types[i]->getType())) 1682 CompatIndices.push_back(i); 1683 } 1684 1685 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1686 // type compatible with at most one of the types named in its generic 1687 // association list." 1688 if (CompatIndices.size() > 1) { 1689 // We strip parens here because the controlling expression is typically 1690 // parenthesized in macro definitions. 1691 ControllingExpr = ControllingExpr->IgnoreParens(); 1692 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1693 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1694 << (unsigned)CompatIndices.size(); 1695 for (unsigned I : CompatIndices) { 1696 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1697 diag::note_compat_assoc) 1698 << Types[I]->getTypeLoc().getSourceRange() 1699 << Types[I]->getType(); 1700 } 1701 return ExprError(); 1702 } 1703 1704 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1705 // its controlling expression shall have type compatible with exactly one of 1706 // the types named in its generic association list." 1707 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1708 // We strip parens here because the controlling expression is typically 1709 // parenthesized in macro definitions. 1710 ControllingExpr = ControllingExpr->IgnoreParens(); 1711 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1712 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1713 return ExprError(); 1714 } 1715 1716 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1717 // type name that is compatible with the type of the controlling expression, 1718 // then the result expression of the generic selection is the expression 1719 // in that generic association. Otherwise, the result expression of the 1720 // generic selection is the expression in the default generic association." 1721 unsigned ResultIndex = 1722 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1723 1724 return GenericSelectionExpr::Create( 1725 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1726 ContainsUnexpandedParameterPack, ResultIndex); 1727 } 1728 1729 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1730 /// location of the token and the offset of the ud-suffix within it. 1731 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1732 unsigned Offset) { 1733 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1734 S.getLangOpts()); 1735 } 1736 1737 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1738 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1739 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1740 IdentifierInfo *UDSuffix, 1741 SourceLocation UDSuffixLoc, 1742 ArrayRef<Expr*> Args, 1743 SourceLocation LitEndLoc) { 1744 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1745 1746 QualType ArgTy[2]; 1747 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1748 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1749 if (ArgTy[ArgIdx]->isArrayType()) 1750 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1751 } 1752 1753 DeclarationName OpName = 1754 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1755 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1756 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1757 1758 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1759 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1760 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1761 /*AllowStringTemplatePack*/ false, 1762 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1763 return ExprError(); 1764 1765 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1766 } 1767 1768 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1769 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1770 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1771 /// multiple tokens. However, the common case is that StringToks points to one 1772 /// string. 1773 /// 1774 ExprResult 1775 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1776 assert(!StringToks.empty() && "Must have at least one string!"); 1777 1778 StringLiteralParser Literal(StringToks, PP); 1779 if (Literal.hadError) 1780 return ExprError(); 1781 1782 SmallVector<SourceLocation, 4> StringTokLocs; 1783 for (const Token &Tok : StringToks) 1784 StringTokLocs.push_back(Tok.getLocation()); 1785 1786 QualType CharTy = Context.CharTy; 1787 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1788 if (Literal.isWide()) { 1789 CharTy = Context.getWideCharType(); 1790 Kind = StringLiteral::Wide; 1791 } else if (Literal.isUTF8()) { 1792 if (getLangOpts().Char8) 1793 CharTy = Context.Char8Ty; 1794 Kind = StringLiteral::UTF8; 1795 } else if (Literal.isUTF16()) { 1796 CharTy = Context.Char16Ty; 1797 Kind = StringLiteral::UTF16; 1798 } else if (Literal.isUTF32()) { 1799 CharTy = Context.Char32Ty; 1800 Kind = StringLiteral::UTF32; 1801 } else if (Literal.isPascal()) { 1802 CharTy = Context.UnsignedCharTy; 1803 } 1804 1805 // Warn on initializing an array of char from a u8 string literal; this 1806 // becomes ill-formed in C++2a. 1807 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1808 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1809 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1810 1811 // Create removals for all 'u8' prefixes in the string literal(s). This 1812 // ensures C++2a compatibility (but may change the program behavior when 1813 // built by non-Clang compilers for which the execution character set is 1814 // not always UTF-8). 1815 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1816 SourceLocation RemovalDiagLoc; 1817 for (const Token &Tok : StringToks) { 1818 if (Tok.getKind() == tok::utf8_string_literal) { 1819 if (RemovalDiagLoc.isInvalid()) 1820 RemovalDiagLoc = Tok.getLocation(); 1821 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1822 Tok.getLocation(), 1823 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1824 getSourceManager(), getLangOpts()))); 1825 } 1826 } 1827 Diag(RemovalDiagLoc, RemovalDiag); 1828 } 1829 1830 QualType StrTy = 1831 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1832 1833 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1834 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1835 Kind, Literal.Pascal, StrTy, 1836 &StringTokLocs[0], 1837 StringTokLocs.size()); 1838 if (Literal.getUDSuffix().empty()) 1839 return Lit; 1840 1841 // We're building a user-defined literal. 1842 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1843 SourceLocation UDSuffixLoc = 1844 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1845 Literal.getUDSuffixOffset()); 1846 1847 // Make sure we're allowed user-defined literals here. 1848 if (!UDLScope) 1849 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1850 1851 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1852 // operator "" X (str, len) 1853 QualType SizeType = Context.getSizeType(); 1854 1855 DeclarationName OpName = 1856 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1857 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1858 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1859 1860 QualType ArgTy[] = { 1861 Context.getArrayDecayedType(StrTy), SizeType 1862 }; 1863 1864 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1865 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1866 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1867 /*AllowStringTemplatePack*/ true, 1868 /*DiagnoseMissing*/ true, Lit)) { 1869 1870 case LOLR_Cooked: { 1871 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1872 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1873 StringTokLocs[0]); 1874 Expr *Args[] = { Lit, LenArg }; 1875 1876 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1877 } 1878 1879 case LOLR_Template: { 1880 TemplateArgumentListInfo ExplicitArgs; 1881 TemplateArgument Arg(Lit); 1882 TemplateArgumentLocInfo ArgInfo(Lit); 1883 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1884 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1885 &ExplicitArgs); 1886 } 1887 1888 case LOLR_StringTemplatePack: { 1889 TemplateArgumentListInfo ExplicitArgs; 1890 1891 unsigned CharBits = Context.getIntWidth(CharTy); 1892 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1893 llvm::APSInt Value(CharBits, CharIsUnsigned); 1894 1895 TemplateArgument TypeArg(CharTy); 1896 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1897 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1898 1899 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1900 Value = Lit->getCodeUnit(I); 1901 TemplateArgument Arg(Context, Value, CharTy); 1902 TemplateArgumentLocInfo ArgInfo; 1903 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1904 } 1905 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1906 &ExplicitArgs); 1907 } 1908 case LOLR_Raw: 1909 case LOLR_ErrorNoDiagnostic: 1910 llvm_unreachable("unexpected literal operator lookup result"); 1911 case LOLR_Error: 1912 return ExprError(); 1913 } 1914 llvm_unreachable("unexpected literal operator lookup result"); 1915 } 1916 1917 DeclRefExpr * 1918 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1919 SourceLocation Loc, 1920 const CXXScopeSpec *SS) { 1921 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1922 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1923 } 1924 1925 DeclRefExpr * 1926 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1927 const DeclarationNameInfo &NameInfo, 1928 const CXXScopeSpec *SS, NamedDecl *FoundD, 1929 SourceLocation TemplateKWLoc, 1930 const TemplateArgumentListInfo *TemplateArgs) { 1931 NestedNameSpecifierLoc NNS = 1932 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1933 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1934 TemplateArgs); 1935 } 1936 1937 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1938 // A declaration named in an unevaluated operand never constitutes an odr-use. 1939 if (isUnevaluatedContext()) 1940 return NOUR_Unevaluated; 1941 1942 // C++2a [basic.def.odr]p4: 1943 // A variable x whose name appears as a potentially-evaluated expression e 1944 // is odr-used by e unless [...] x is a reference that is usable in 1945 // constant expressions. 1946 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1947 if (VD->getType()->isReferenceType() && 1948 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1949 VD->isUsableInConstantExpressions(Context)) 1950 return NOUR_Constant; 1951 } 1952 1953 // All remaining non-variable cases constitute an odr-use. For variables, we 1954 // need to wait and see how the expression is used. 1955 return NOUR_None; 1956 } 1957 1958 /// BuildDeclRefExpr - Build an expression that references a 1959 /// declaration that does not require a closure capture. 1960 DeclRefExpr * 1961 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1962 const DeclarationNameInfo &NameInfo, 1963 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1964 SourceLocation TemplateKWLoc, 1965 const TemplateArgumentListInfo *TemplateArgs) { 1966 bool RefersToCapturedVariable = 1967 isa<VarDecl>(D) && 1968 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1969 1970 DeclRefExpr *E = DeclRefExpr::Create( 1971 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1972 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1973 MarkDeclRefReferenced(E); 1974 1975 // C++ [except.spec]p17: 1976 // An exception-specification is considered to be needed when: 1977 // - in an expression, the function is the unique lookup result or 1978 // the selected member of a set of overloaded functions. 1979 // 1980 // We delay doing this until after we've built the function reference and 1981 // marked it as used so that: 1982 // a) if the function is defaulted, we get errors from defining it before / 1983 // instead of errors from computing its exception specification, and 1984 // b) if the function is a defaulted comparison, we can use the body we 1985 // build when defining it as input to the exception specification 1986 // computation rather than computing a new body. 1987 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1988 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1989 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1990 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1991 } 1992 } 1993 1994 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1995 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1996 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1997 getCurFunction()->recordUseOfWeak(E); 1998 1999 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2000 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2001 FD = IFD->getAnonField(); 2002 if (FD) { 2003 UnusedPrivateFields.remove(FD); 2004 // Just in case we're building an illegal pointer-to-member. 2005 if (FD->isBitField()) 2006 E->setObjectKind(OK_BitField); 2007 } 2008 2009 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2010 // designates a bit-field. 2011 if (auto *BD = dyn_cast<BindingDecl>(D)) 2012 if (auto *BE = BD->getBinding()) 2013 E->setObjectKind(BE->getObjectKind()); 2014 2015 return E; 2016 } 2017 2018 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2019 /// possibly a list of template arguments. 2020 /// 2021 /// If this produces template arguments, it is permitted to call 2022 /// DecomposeTemplateName. 2023 /// 2024 /// This actually loses a lot of source location information for 2025 /// non-standard name kinds; we should consider preserving that in 2026 /// some way. 2027 void 2028 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2029 TemplateArgumentListInfo &Buffer, 2030 DeclarationNameInfo &NameInfo, 2031 const TemplateArgumentListInfo *&TemplateArgs) { 2032 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2033 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2034 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2035 2036 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2037 Id.TemplateId->NumArgs); 2038 translateTemplateArguments(TemplateArgsPtr, Buffer); 2039 2040 TemplateName TName = Id.TemplateId->Template.get(); 2041 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2042 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2043 TemplateArgs = &Buffer; 2044 } else { 2045 NameInfo = GetNameFromUnqualifiedId(Id); 2046 TemplateArgs = nullptr; 2047 } 2048 } 2049 2050 static void emitEmptyLookupTypoDiagnostic( 2051 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2052 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2053 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2054 DeclContext *Ctx = 2055 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2056 if (!TC) { 2057 // Emit a special diagnostic for failed member lookups. 2058 // FIXME: computing the declaration context might fail here (?) 2059 if (Ctx) 2060 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2061 << SS.getRange(); 2062 else 2063 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2064 return; 2065 } 2066 2067 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2068 bool DroppedSpecifier = 2069 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2070 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2071 ? diag::note_implicit_param_decl 2072 : diag::note_previous_decl; 2073 if (!Ctx) 2074 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2075 SemaRef.PDiag(NoteID)); 2076 else 2077 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2078 << Typo << Ctx << DroppedSpecifier 2079 << SS.getRange(), 2080 SemaRef.PDiag(NoteID)); 2081 } 2082 2083 /// Diagnose an empty lookup. 2084 /// 2085 /// \return false if new lookup candidates were found 2086 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2087 CorrectionCandidateCallback &CCC, 2088 TemplateArgumentListInfo *ExplicitTemplateArgs, 2089 ArrayRef<Expr *> Args, TypoExpr **Out) { 2090 DeclarationName Name = R.getLookupName(); 2091 2092 unsigned diagnostic = diag::err_undeclared_var_use; 2093 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2094 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2095 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2096 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2097 diagnostic = diag::err_undeclared_use; 2098 diagnostic_suggest = diag::err_undeclared_use_suggest; 2099 } 2100 2101 // If the original lookup was an unqualified lookup, fake an 2102 // unqualified lookup. This is useful when (for example) the 2103 // original lookup would not have found something because it was a 2104 // dependent name. 2105 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2106 while (DC) { 2107 if (isa<CXXRecordDecl>(DC)) { 2108 LookupQualifiedName(R, DC); 2109 2110 if (!R.empty()) { 2111 // Don't give errors about ambiguities in this lookup. 2112 R.suppressDiagnostics(); 2113 2114 // During a default argument instantiation the CurContext points 2115 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2116 // function parameter list, hence add an explicit check. 2117 bool isDefaultArgument = 2118 !CodeSynthesisContexts.empty() && 2119 CodeSynthesisContexts.back().Kind == 2120 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2121 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2122 bool isInstance = CurMethod && 2123 CurMethod->isInstance() && 2124 DC == CurMethod->getParent() && !isDefaultArgument; 2125 2126 // Give a code modification hint to insert 'this->'. 2127 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2128 // Actually quite difficult! 2129 if (getLangOpts().MSVCCompat) 2130 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2131 if (isInstance) { 2132 Diag(R.getNameLoc(), diagnostic) << Name 2133 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2134 CheckCXXThisCapture(R.getNameLoc()); 2135 } else { 2136 Diag(R.getNameLoc(), diagnostic) << Name; 2137 } 2138 2139 // Do we really want to note all of these? 2140 for (NamedDecl *D : R) 2141 Diag(D->getLocation(), diag::note_dependent_var_use); 2142 2143 // Return true if we are inside a default argument instantiation 2144 // and the found name refers to an instance member function, otherwise 2145 // the function calling DiagnoseEmptyLookup will try to create an 2146 // implicit member call and this is wrong for default argument. 2147 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2148 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2149 return true; 2150 } 2151 2152 // Tell the callee to try to recover. 2153 return false; 2154 } 2155 2156 R.clear(); 2157 } 2158 2159 DC = DC->getLookupParent(); 2160 } 2161 2162 // We didn't find anything, so try to correct for a typo. 2163 TypoCorrection Corrected; 2164 if (S && Out) { 2165 SourceLocation TypoLoc = R.getNameLoc(); 2166 assert(!ExplicitTemplateArgs && 2167 "Diagnosing an empty lookup with explicit template args!"); 2168 *Out = CorrectTypoDelayed( 2169 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2170 [=](const TypoCorrection &TC) { 2171 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2172 diagnostic, diagnostic_suggest); 2173 }, 2174 nullptr, CTK_ErrorRecovery); 2175 if (*Out) 2176 return true; 2177 } else if (S && 2178 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2179 S, &SS, CCC, CTK_ErrorRecovery))) { 2180 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2181 bool DroppedSpecifier = 2182 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2183 R.setLookupName(Corrected.getCorrection()); 2184 2185 bool AcceptableWithRecovery = false; 2186 bool AcceptableWithoutRecovery = false; 2187 NamedDecl *ND = Corrected.getFoundDecl(); 2188 if (ND) { 2189 if (Corrected.isOverloaded()) { 2190 OverloadCandidateSet OCS(R.getNameLoc(), 2191 OverloadCandidateSet::CSK_Normal); 2192 OverloadCandidateSet::iterator Best; 2193 for (NamedDecl *CD : Corrected) { 2194 if (FunctionTemplateDecl *FTD = 2195 dyn_cast<FunctionTemplateDecl>(CD)) 2196 AddTemplateOverloadCandidate( 2197 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2198 Args, OCS); 2199 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2200 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2201 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2202 Args, OCS); 2203 } 2204 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2205 case OR_Success: 2206 ND = Best->FoundDecl; 2207 Corrected.setCorrectionDecl(ND); 2208 break; 2209 default: 2210 // FIXME: Arbitrarily pick the first declaration for the note. 2211 Corrected.setCorrectionDecl(ND); 2212 break; 2213 } 2214 } 2215 R.addDecl(ND); 2216 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2217 CXXRecordDecl *Record = nullptr; 2218 if (Corrected.getCorrectionSpecifier()) { 2219 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2220 Record = Ty->getAsCXXRecordDecl(); 2221 } 2222 if (!Record) 2223 Record = cast<CXXRecordDecl>( 2224 ND->getDeclContext()->getRedeclContext()); 2225 R.setNamingClass(Record); 2226 } 2227 2228 auto *UnderlyingND = ND->getUnderlyingDecl(); 2229 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2230 isa<FunctionTemplateDecl>(UnderlyingND); 2231 // FIXME: If we ended up with a typo for a type name or 2232 // Objective-C class name, we're in trouble because the parser 2233 // is in the wrong place to recover. Suggest the typo 2234 // correction, but don't make it a fix-it since we're not going 2235 // to recover well anyway. 2236 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2237 getAsTypeTemplateDecl(UnderlyingND) || 2238 isa<ObjCInterfaceDecl>(UnderlyingND); 2239 } else { 2240 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2241 // because we aren't able to recover. 2242 AcceptableWithoutRecovery = true; 2243 } 2244 2245 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2246 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2247 ? diag::note_implicit_param_decl 2248 : diag::note_previous_decl; 2249 if (SS.isEmpty()) 2250 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2251 PDiag(NoteID), AcceptableWithRecovery); 2252 else 2253 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2254 << Name << computeDeclContext(SS, false) 2255 << DroppedSpecifier << SS.getRange(), 2256 PDiag(NoteID), AcceptableWithRecovery); 2257 2258 // Tell the callee whether to try to recover. 2259 return !AcceptableWithRecovery; 2260 } 2261 } 2262 R.clear(); 2263 2264 // Emit a special diagnostic for failed member lookups. 2265 // FIXME: computing the declaration context might fail here (?) 2266 if (!SS.isEmpty()) { 2267 Diag(R.getNameLoc(), diag::err_no_member) 2268 << Name << computeDeclContext(SS, false) 2269 << SS.getRange(); 2270 return true; 2271 } 2272 2273 // Give up, we can't recover. 2274 Diag(R.getNameLoc(), diagnostic) << Name; 2275 return true; 2276 } 2277 2278 /// In Microsoft mode, if we are inside a template class whose parent class has 2279 /// dependent base classes, and we can't resolve an unqualified identifier, then 2280 /// assume the identifier is a member of a dependent base class. We can only 2281 /// recover successfully in static methods, instance methods, and other contexts 2282 /// where 'this' is available. This doesn't precisely match MSVC's 2283 /// instantiation model, but it's close enough. 2284 static Expr * 2285 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2286 DeclarationNameInfo &NameInfo, 2287 SourceLocation TemplateKWLoc, 2288 const TemplateArgumentListInfo *TemplateArgs) { 2289 // Only try to recover from lookup into dependent bases in static methods or 2290 // contexts where 'this' is available. 2291 QualType ThisType = S.getCurrentThisType(); 2292 const CXXRecordDecl *RD = nullptr; 2293 if (!ThisType.isNull()) 2294 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2295 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2296 RD = MD->getParent(); 2297 if (!RD || !RD->hasAnyDependentBases()) 2298 return nullptr; 2299 2300 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2301 // is available, suggest inserting 'this->' as a fixit. 2302 SourceLocation Loc = NameInfo.getLoc(); 2303 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2304 DB << NameInfo.getName() << RD; 2305 2306 if (!ThisType.isNull()) { 2307 DB << FixItHint::CreateInsertion(Loc, "this->"); 2308 return CXXDependentScopeMemberExpr::Create( 2309 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2310 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2311 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2312 } 2313 2314 // Synthesize a fake NNS that points to the derived class. This will 2315 // perform name lookup during template instantiation. 2316 CXXScopeSpec SS; 2317 auto *NNS = 2318 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2319 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2320 return DependentScopeDeclRefExpr::Create( 2321 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2322 TemplateArgs); 2323 } 2324 2325 ExprResult 2326 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2327 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2328 bool HasTrailingLParen, bool IsAddressOfOperand, 2329 CorrectionCandidateCallback *CCC, 2330 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2331 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2332 "cannot be direct & operand and have a trailing lparen"); 2333 if (SS.isInvalid()) 2334 return ExprError(); 2335 2336 TemplateArgumentListInfo TemplateArgsBuffer; 2337 2338 // Decompose the UnqualifiedId into the following data. 2339 DeclarationNameInfo NameInfo; 2340 const TemplateArgumentListInfo *TemplateArgs; 2341 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2342 2343 DeclarationName Name = NameInfo.getName(); 2344 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2345 SourceLocation NameLoc = NameInfo.getLoc(); 2346 2347 if (II && II->isEditorPlaceholder()) { 2348 // FIXME: When typed placeholders are supported we can create a typed 2349 // placeholder expression node. 2350 return ExprError(); 2351 } 2352 2353 // C++ [temp.dep.expr]p3: 2354 // An id-expression is type-dependent if it contains: 2355 // -- an identifier that was declared with a dependent type, 2356 // (note: handled after lookup) 2357 // -- a template-id that is dependent, 2358 // (note: handled in BuildTemplateIdExpr) 2359 // -- a conversion-function-id that specifies a dependent type, 2360 // -- a nested-name-specifier that contains a class-name that 2361 // names a dependent type. 2362 // Determine whether this is a member of an unknown specialization; 2363 // we need to handle these differently. 2364 bool DependentID = false; 2365 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2366 Name.getCXXNameType()->isDependentType()) { 2367 DependentID = true; 2368 } else if (SS.isSet()) { 2369 if (DeclContext *DC = computeDeclContext(SS, false)) { 2370 if (RequireCompleteDeclContext(SS, DC)) 2371 return ExprError(); 2372 } else { 2373 DependentID = true; 2374 } 2375 } 2376 2377 if (DependentID) 2378 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2379 IsAddressOfOperand, TemplateArgs); 2380 2381 // Perform the required lookup. 2382 LookupResult R(*this, NameInfo, 2383 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2384 ? LookupObjCImplicitSelfParam 2385 : LookupOrdinaryName); 2386 if (TemplateKWLoc.isValid() || TemplateArgs) { 2387 // Lookup the template name again to correctly establish the context in 2388 // which it was found. This is really unfortunate as we already did the 2389 // lookup to determine that it was a template name in the first place. If 2390 // this becomes a performance hit, we can work harder to preserve those 2391 // results until we get here but it's likely not worth it. 2392 bool MemberOfUnknownSpecialization; 2393 AssumedTemplateKind AssumedTemplate; 2394 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2395 MemberOfUnknownSpecialization, TemplateKWLoc, 2396 &AssumedTemplate)) 2397 return ExprError(); 2398 2399 if (MemberOfUnknownSpecialization || 2400 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2401 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2402 IsAddressOfOperand, TemplateArgs); 2403 } else { 2404 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2405 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2406 2407 // If the result might be in a dependent base class, this is a dependent 2408 // id-expression. 2409 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2410 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2411 IsAddressOfOperand, TemplateArgs); 2412 2413 // If this reference is in an Objective-C method, then we need to do 2414 // some special Objective-C lookup, too. 2415 if (IvarLookupFollowUp) { 2416 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2417 if (E.isInvalid()) 2418 return ExprError(); 2419 2420 if (Expr *Ex = E.getAs<Expr>()) 2421 return Ex; 2422 } 2423 } 2424 2425 if (R.isAmbiguous()) 2426 return ExprError(); 2427 2428 // This could be an implicitly declared function reference (legal in C90, 2429 // extension in C99, forbidden in C++). 2430 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2431 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2432 if (D) R.addDecl(D); 2433 } 2434 2435 // Determine whether this name might be a candidate for 2436 // argument-dependent lookup. 2437 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2438 2439 if (R.empty() && !ADL) { 2440 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2441 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2442 TemplateKWLoc, TemplateArgs)) 2443 return E; 2444 } 2445 2446 // Don't diagnose an empty lookup for inline assembly. 2447 if (IsInlineAsmIdentifier) 2448 return ExprError(); 2449 2450 // If this name wasn't predeclared and if this is not a function 2451 // call, diagnose the problem. 2452 TypoExpr *TE = nullptr; 2453 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2454 : nullptr); 2455 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2456 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2457 "Typo correction callback misconfigured"); 2458 if (CCC) { 2459 // Make sure the callback knows what the typo being diagnosed is. 2460 CCC->setTypoName(II); 2461 if (SS.isValid()) 2462 CCC->setTypoNNS(SS.getScopeRep()); 2463 } 2464 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2465 // a template name, but we happen to have always already looked up the name 2466 // before we get here if it must be a template name. 2467 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2468 None, &TE)) { 2469 if (TE && KeywordReplacement) { 2470 auto &State = getTypoExprState(TE); 2471 auto BestTC = State.Consumer->getNextCorrection(); 2472 if (BestTC.isKeyword()) { 2473 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2474 if (State.DiagHandler) 2475 State.DiagHandler(BestTC); 2476 KeywordReplacement->startToken(); 2477 KeywordReplacement->setKind(II->getTokenID()); 2478 KeywordReplacement->setIdentifierInfo(II); 2479 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2480 // Clean up the state associated with the TypoExpr, since it has 2481 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2482 clearDelayedTypo(TE); 2483 // Signal that a correction to a keyword was performed by returning a 2484 // valid-but-null ExprResult. 2485 return (Expr*)nullptr; 2486 } 2487 State.Consumer->resetCorrectionStream(); 2488 } 2489 return TE ? TE : ExprError(); 2490 } 2491 2492 assert(!R.empty() && 2493 "DiagnoseEmptyLookup returned false but added no results"); 2494 2495 // If we found an Objective-C instance variable, let 2496 // LookupInObjCMethod build the appropriate expression to 2497 // reference the ivar. 2498 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2499 R.clear(); 2500 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2501 // In a hopelessly buggy code, Objective-C instance variable 2502 // lookup fails and no expression will be built to reference it. 2503 if (!E.isInvalid() && !E.get()) 2504 return ExprError(); 2505 return E; 2506 } 2507 } 2508 2509 // This is guaranteed from this point on. 2510 assert(!R.empty() || ADL); 2511 2512 // Check whether this might be a C++ implicit instance member access. 2513 // C++ [class.mfct.non-static]p3: 2514 // When an id-expression that is not part of a class member access 2515 // syntax and not used to form a pointer to member is used in the 2516 // body of a non-static member function of class X, if name lookup 2517 // resolves the name in the id-expression to a non-static non-type 2518 // member of some class C, the id-expression is transformed into a 2519 // class member access expression using (*this) as the 2520 // postfix-expression to the left of the . operator. 2521 // 2522 // But we don't actually need to do this for '&' operands if R 2523 // resolved to a function or overloaded function set, because the 2524 // expression is ill-formed if it actually works out to be a 2525 // non-static member function: 2526 // 2527 // C++ [expr.ref]p4: 2528 // Otherwise, if E1.E2 refers to a non-static member function. . . 2529 // [t]he expression can be used only as the left-hand operand of a 2530 // member function call. 2531 // 2532 // There are other safeguards against such uses, but it's important 2533 // to get this right here so that we don't end up making a 2534 // spuriously dependent expression if we're inside a dependent 2535 // instance method. 2536 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2537 bool MightBeImplicitMember; 2538 if (!IsAddressOfOperand) 2539 MightBeImplicitMember = true; 2540 else if (!SS.isEmpty()) 2541 MightBeImplicitMember = false; 2542 else if (R.isOverloadedResult()) 2543 MightBeImplicitMember = false; 2544 else if (R.isUnresolvableResult()) 2545 MightBeImplicitMember = true; 2546 else 2547 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2548 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2549 isa<MSPropertyDecl>(R.getFoundDecl()); 2550 2551 if (MightBeImplicitMember) 2552 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2553 R, TemplateArgs, S); 2554 } 2555 2556 if (TemplateArgs || TemplateKWLoc.isValid()) { 2557 2558 // In C++1y, if this is a variable template id, then check it 2559 // in BuildTemplateIdExpr(). 2560 // The single lookup result must be a variable template declaration. 2561 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2562 Id.TemplateId->Kind == TNK_Var_template) { 2563 assert(R.getAsSingle<VarTemplateDecl>() && 2564 "There should only be one declaration found."); 2565 } 2566 2567 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2568 } 2569 2570 return BuildDeclarationNameExpr(SS, R, ADL); 2571 } 2572 2573 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2574 /// declaration name, generally during template instantiation. 2575 /// There's a large number of things which don't need to be done along 2576 /// this path. 2577 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2578 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2579 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2580 DeclContext *DC = computeDeclContext(SS, false); 2581 if (!DC) 2582 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2583 NameInfo, /*TemplateArgs=*/nullptr); 2584 2585 if (RequireCompleteDeclContext(SS, DC)) 2586 return ExprError(); 2587 2588 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2589 LookupQualifiedName(R, DC); 2590 2591 if (R.isAmbiguous()) 2592 return ExprError(); 2593 2594 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2595 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2596 NameInfo, /*TemplateArgs=*/nullptr); 2597 2598 if (R.empty()) { 2599 // Don't diagnose problems with invalid record decl, the secondary no_member 2600 // diagnostic during template instantiation is likely bogus, e.g. if a class 2601 // is invalid because it's derived from an invalid base class, then missing 2602 // members were likely supposed to be inherited. 2603 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2604 if (CD->isInvalidDecl()) 2605 return ExprError(); 2606 Diag(NameInfo.getLoc(), diag::err_no_member) 2607 << NameInfo.getName() << DC << SS.getRange(); 2608 return ExprError(); 2609 } 2610 2611 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2612 // Diagnose a missing typename if this resolved unambiguously to a type in 2613 // a dependent context. If we can recover with a type, downgrade this to 2614 // a warning in Microsoft compatibility mode. 2615 unsigned DiagID = diag::err_typename_missing; 2616 if (RecoveryTSI && getLangOpts().MSVCCompat) 2617 DiagID = diag::ext_typename_missing; 2618 SourceLocation Loc = SS.getBeginLoc(); 2619 auto D = Diag(Loc, DiagID); 2620 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2621 << SourceRange(Loc, NameInfo.getEndLoc()); 2622 2623 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2624 // context. 2625 if (!RecoveryTSI) 2626 return ExprError(); 2627 2628 // Only issue the fixit if we're prepared to recover. 2629 D << FixItHint::CreateInsertion(Loc, "typename "); 2630 2631 // Recover by pretending this was an elaborated type. 2632 QualType Ty = Context.getTypeDeclType(TD); 2633 TypeLocBuilder TLB; 2634 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2635 2636 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2637 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2638 QTL.setElaboratedKeywordLoc(SourceLocation()); 2639 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2640 2641 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2642 2643 return ExprEmpty(); 2644 } 2645 2646 // Defend against this resolving to an implicit member access. We usually 2647 // won't get here if this might be a legitimate a class member (we end up in 2648 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2649 // a pointer-to-member or in an unevaluated context in C++11. 2650 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2651 return BuildPossibleImplicitMemberExpr(SS, 2652 /*TemplateKWLoc=*/SourceLocation(), 2653 R, /*TemplateArgs=*/nullptr, S); 2654 2655 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2656 } 2657 2658 /// The parser has read a name in, and Sema has detected that we're currently 2659 /// inside an ObjC method. Perform some additional checks and determine if we 2660 /// should form a reference to an ivar. 2661 /// 2662 /// Ideally, most of this would be done by lookup, but there's 2663 /// actually quite a lot of extra work involved. 2664 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2665 IdentifierInfo *II) { 2666 SourceLocation Loc = Lookup.getNameLoc(); 2667 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2668 2669 // Check for error condition which is already reported. 2670 if (!CurMethod) 2671 return DeclResult(true); 2672 2673 // There are two cases to handle here. 1) scoped lookup could have failed, 2674 // in which case we should look for an ivar. 2) scoped lookup could have 2675 // found a decl, but that decl is outside the current instance method (i.e. 2676 // a global variable). In these two cases, we do a lookup for an ivar with 2677 // this name, if the lookup sucedes, we replace it our current decl. 2678 2679 // If we're in a class method, we don't normally want to look for 2680 // ivars. But if we don't find anything else, and there's an 2681 // ivar, that's an error. 2682 bool IsClassMethod = CurMethod->isClassMethod(); 2683 2684 bool LookForIvars; 2685 if (Lookup.empty()) 2686 LookForIvars = true; 2687 else if (IsClassMethod) 2688 LookForIvars = false; 2689 else 2690 LookForIvars = (Lookup.isSingleResult() && 2691 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2692 ObjCInterfaceDecl *IFace = nullptr; 2693 if (LookForIvars) { 2694 IFace = CurMethod->getClassInterface(); 2695 ObjCInterfaceDecl *ClassDeclared; 2696 ObjCIvarDecl *IV = nullptr; 2697 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2698 // Diagnose using an ivar in a class method. 2699 if (IsClassMethod) { 2700 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2701 return DeclResult(true); 2702 } 2703 2704 // Diagnose the use of an ivar outside of the declaring class. 2705 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2706 !declaresSameEntity(ClassDeclared, IFace) && 2707 !getLangOpts().DebuggerSupport) 2708 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2709 2710 // Success. 2711 return IV; 2712 } 2713 } else if (CurMethod->isInstanceMethod()) { 2714 // We should warn if a local variable hides an ivar. 2715 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2716 ObjCInterfaceDecl *ClassDeclared; 2717 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2718 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2719 declaresSameEntity(IFace, ClassDeclared)) 2720 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2721 } 2722 } 2723 } else if (Lookup.isSingleResult() && 2724 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2725 // If accessing a stand-alone ivar in a class method, this is an error. 2726 if (const ObjCIvarDecl *IV = 2727 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2728 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2729 return DeclResult(true); 2730 } 2731 } 2732 2733 // Didn't encounter an error, didn't find an ivar. 2734 return DeclResult(false); 2735 } 2736 2737 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2738 ObjCIvarDecl *IV) { 2739 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2740 assert(CurMethod && CurMethod->isInstanceMethod() && 2741 "should not reference ivar from this context"); 2742 2743 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2744 assert(IFace && "should not reference ivar from this context"); 2745 2746 // If we're referencing an invalid decl, just return this as a silent 2747 // error node. The error diagnostic was already emitted on the decl. 2748 if (IV->isInvalidDecl()) 2749 return ExprError(); 2750 2751 // Check if referencing a field with __attribute__((deprecated)). 2752 if (DiagnoseUseOfDecl(IV, Loc)) 2753 return ExprError(); 2754 2755 // FIXME: This should use a new expr for a direct reference, don't 2756 // turn this into Self->ivar, just return a BareIVarExpr or something. 2757 IdentifierInfo &II = Context.Idents.get("self"); 2758 UnqualifiedId SelfName; 2759 SelfName.setIdentifier(&II, SourceLocation()); 2760 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2761 CXXScopeSpec SelfScopeSpec; 2762 SourceLocation TemplateKWLoc; 2763 ExprResult SelfExpr = 2764 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2765 /*HasTrailingLParen=*/false, 2766 /*IsAddressOfOperand=*/false); 2767 if (SelfExpr.isInvalid()) 2768 return ExprError(); 2769 2770 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2771 if (SelfExpr.isInvalid()) 2772 return ExprError(); 2773 2774 MarkAnyDeclReferenced(Loc, IV, true); 2775 2776 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2777 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2778 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2779 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2780 2781 ObjCIvarRefExpr *Result = new (Context) 2782 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2783 IV->getLocation(), SelfExpr.get(), true, true); 2784 2785 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2786 if (!isUnevaluatedContext() && 2787 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2788 getCurFunction()->recordUseOfWeak(Result); 2789 } 2790 if (getLangOpts().ObjCAutoRefCount) 2791 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2792 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2793 2794 return Result; 2795 } 2796 2797 /// The parser has read a name in, and Sema has detected that we're currently 2798 /// inside an ObjC method. Perform some additional checks and determine if we 2799 /// should form a reference to an ivar. If so, build an expression referencing 2800 /// that ivar. 2801 ExprResult 2802 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2803 IdentifierInfo *II, bool AllowBuiltinCreation) { 2804 // FIXME: Integrate this lookup step into LookupParsedName. 2805 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2806 if (Ivar.isInvalid()) 2807 return ExprError(); 2808 if (Ivar.isUsable()) 2809 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2810 cast<ObjCIvarDecl>(Ivar.get())); 2811 2812 if (Lookup.empty() && II && AllowBuiltinCreation) 2813 LookupBuiltin(Lookup); 2814 2815 // Sentinel value saying that we didn't do anything special. 2816 return ExprResult(false); 2817 } 2818 2819 /// Cast a base object to a member's actual type. 2820 /// 2821 /// Logically this happens in three phases: 2822 /// 2823 /// * First we cast from the base type to the naming class. 2824 /// The naming class is the class into which we were looking 2825 /// when we found the member; it's the qualifier type if a 2826 /// qualifier was provided, and otherwise it's the base type. 2827 /// 2828 /// * Next we cast from the naming class to the declaring class. 2829 /// If the member we found was brought into a class's scope by 2830 /// a using declaration, this is that class; otherwise it's 2831 /// the class declaring the member. 2832 /// 2833 /// * Finally we cast from the declaring class to the "true" 2834 /// declaring class of the member. This conversion does not 2835 /// obey access control. 2836 ExprResult 2837 Sema::PerformObjectMemberConversion(Expr *From, 2838 NestedNameSpecifier *Qualifier, 2839 NamedDecl *FoundDecl, 2840 NamedDecl *Member) { 2841 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2842 if (!RD) 2843 return From; 2844 2845 QualType DestRecordType; 2846 QualType DestType; 2847 QualType FromRecordType; 2848 QualType FromType = From->getType(); 2849 bool PointerConversions = false; 2850 if (isa<FieldDecl>(Member)) { 2851 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2852 auto FromPtrType = FromType->getAs<PointerType>(); 2853 DestRecordType = Context.getAddrSpaceQualType( 2854 DestRecordType, FromPtrType 2855 ? FromType->getPointeeType().getAddressSpace() 2856 : FromType.getAddressSpace()); 2857 2858 if (FromPtrType) { 2859 DestType = Context.getPointerType(DestRecordType); 2860 FromRecordType = FromPtrType->getPointeeType(); 2861 PointerConversions = true; 2862 } else { 2863 DestType = DestRecordType; 2864 FromRecordType = FromType; 2865 } 2866 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2867 if (Method->isStatic()) 2868 return From; 2869 2870 DestType = Method->getThisType(); 2871 DestRecordType = DestType->getPointeeType(); 2872 2873 if (FromType->getAs<PointerType>()) { 2874 FromRecordType = FromType->getPointeeType(); 2875 PointerConversions = true; 2876 } else { 2877 FromRecordType = FromType; 2878 DestType = DestRecordType; 2879 } 2880 2881 LangAS FromAS = FromRecordType.getAddressSpace(); 2882 LangAS DestAS = DestRecordType.getAddressSpace(); 2883 if (FromAS != DestAS) { 2884 QualType FromRecordTypeWithoutAS = 2885 Context.removeAddrSpaceQualType(FromRecordType); 2886 QualType FromTypeWithDestAS = 2887 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2888 if (PointerConversions) 2889 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2890 From = ImpCastExprToType(From, FromTypeWithDestAS, 2891 CK_AddressSpaceConversion, From->getValueKind()) 2892 .get(); 2893 } 2894 } else { 2895 // No conversion necessary. 2896 return From; 2897 } 2898 2899 if (DestType->isDependentType() || FromType->isDependentType()) 2900 return From; 2901 2902 // If the unqualified types are the same, no conversion is necessary. 2903 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2904 return From; 2905 2906 SourceRange FromRange = From->getSourceRange(); 2907 SourceLocation FromLoc = FromRange.getBegin(); 2908 2909 ExprValueKind VK = From->getValueKind(); 2910 2911 // C++ [class.member.lookup]p8: 2912 // [...] Ambiguities can often be resolved by qualifying a name with its 2913 // class name. 2914 // 2915 // If the member was a qualified name and the qualified referred to a 2916 // specific base subobject type, we'll cast to that intermediate type 2917 // first and then to the object in which the member is declared. That allows 2918 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2919 // 2920 // class Base { public: int x; }; 2921 // class Derived1 : public Base { }; 2922 // class Derived2 : public Base { }; 2923 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2924 // 2925 // void VeryDerived::f() { 2926 // x = 17; // error: ambiguous base subobjects 2927 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2928 // } 2929 if (Qualifier && Qualifier->getAsType()) { 2930 QualType QType = QualType(Qualifier->getAsType(), 0); 2931 assert(QType->isRecordType() && "lookup done with non-record type"); 2932 2933 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2934 2935 // In C++98, the qualifier type doesn't actually have to be a base 2936 // type of the object type, in which case we just ignore it. 2937 // Otherwise build the appropriate casts. 2938 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2939 CXXCastPath BasePath; 2940 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2941 FromLoc, FromRange, &BasePath)) 2942 return ExprError(); 2943 2944 if (PointerConversions) 2945 QType = Context.getPointerType(QType); 2946 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2947 VK, &BasePath).get(); 2948 2949 FromType = QType; 2950 FromRecordType = QRecordType; 2951 2952 // If the qualifier type was the same as the destination type, 2953 // we're done. 2954 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2955 return From; 2956 } 2957 } 2958 2959 bool IgnoreAccess = false; 2960 2961 // If we actually found the member through a using declaration, cast 2962 // down to the using declaration's type. 2963 // 2964 // Pointer equality is fine here because only one declaration of a 2965 // class ever has member declarations. 2966 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2967 assert(isa<UsingShadowDecl>(FoundDecl)); 2968 QualType URecordType = Context.getTypeDeclType( 2969 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2970 2971 // We only need to do this if the naming-class to declaring-class 2972 // conversion is non-trivial. 2973 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2974 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2975 CXXCastPath BasePath; 2976 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2977 FromLoc, FromRange, &BasePath)) 2978 return ExprError(); 2979 2980 QualType UType = URecordType; 2981 if (PointerConversions) 2982 UType = Context.getPointerType(UType); 2983 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2984 VK, &BasePath).get(); 2985 FromType = UType; 2986 FromRecordType = URecordType; 2987 } 2988 2989 // We don't do access control for the conversion from the 2990 // declaring class to the true declaring class. 2991 IgnoreAccess = true; 2992 } 2993 2994 CXXCastPath BasePath; 2995 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2996 FromLoc, FromRange, &BasePath, 2997 IgnoreAccess)) 2998 return ExprError(); 2999 3000 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3001 VK, &BasePath); 3002 } 3003 3004 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3005 const LookupResult &R, 3006 bool HasTrailingLParen) { 3007 // Only when used directly as the postfix-expression of a call. 3008 if (!HasTrailingLParen) 3009 return false; 3010 3011 // Never if a scope specifier was provided. 3012 if (SS.isSet()) 3013 return false; 3014 3015 // Only in C++ or ObjC++. 3016 if (!getLangOpts().CPlusPlus) 3017 return false; 3018 3019 // Turn off ADL when we find certain kinds of declarations during 3020 // normal lookup: 3021 for (NamedDecl *D : R) { 3022 // C++0x [basic.lookup.argdep]p3: 3023 // -- a declaration of a class member 3024 // Since using decls preserve this property, we check this on the 3025 // original decl. 3026 if (D->isCXXClassMember()) 3027 return false; 3028 3029 // C++0x [basic.lookup.argdep]p3: 3030 // -- a block-scope function declaration that is not a 3031 // using-declaration 3032 // NOTE: we also trigger this for function templates (in fact, we 3033 // don't check the decl type at all, since all other decl types 3034 // turn off ADL anyway). 3035 if (isa<UsingShadowDecl>(D)) 3036 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3037 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3038 return false; 3039 3040 // C++0x [basic.lookup.argdep]p3: 3041 // -- a declaration that is neither a function or a function 3042 // template 3043 // And also for builtin functions. 3044 if (isa<FunctionDecl>(D)) { 3045 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3046 3047 // But also builtin functions. 3048 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3049 return false; 3050 } else if (!isa<FunctionTemplateDecl>(D)) 3051 return false; 3052 } 3053 3054 return true; 3055 } 3056 3057 3058 /// Diagnoses obvious problems with the use of the given declaration 3059 /// as an expression. This is only actually called for lookups that 3060 /// were not overloaded, and it doesn't promise that the declaration 3061 /// will in fact be used. 3062 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3063 if (D->isInvalidDecl()) 3064 return true; 3065 3066 if (isa<TypedefNameDecl>(D)) { 3067 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3068 return true; 3069 } 3070 3071 if (isa<ObjCInterfaceDecl>(D)) { 3072 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3073 return true; 3074 } 3075 3076 if (isa<NamespaceDecl>(D)) { 3077 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3078 return true; 3079 } 3080 3081 return false; 3082 } 3083 3084 // Certain multiversion types should be treated as overloaded even when there is 3085 // only one result. 3086 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3087 assert(R.isSingleResult() && "Expected only a single result"); 3088 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3089 return FD && 3090 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3091 } 3092 3093 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3094 LookupResult &R, bool NeedsADL, 3095 bool AcceptInvalidDecl) { 3096 // If this is a single, fully-resolved result and we don't need ADL, 3097 // just build an ordinary singleton decl ref. 3098 if (!NeedsADL && R.isSingleResult() && 3099 !R.getAsSingle<FunctionTemplateDecl>() && 3100 !ShouldLookupResultBeMultiVersionOverload(R)) 3101 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3102 R.getRepresentativeDecl(), nullptr, 3103 AcceptInvalidDecl); 3104 3105 // We only need to check the declaration if there's exactly one 3106 // result, because in the overloaded case the results can only be 3107 // functions and function templates. 3108 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3109 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3110 return ExprError(); 3111 3112 // Otherwise, just build an unresolved lookup expression. Suppress 3113 // any lookup-related diagnostics; we'll hash these out later, when 3114 // we've picked a target. 3115 R.suppressDiagnostics(); 3116 3117 UnresolvedLookupExpr *ULE 3118 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3119 SS.getWithLocInContext(Context), 3120 R.getLookupNameInfo(), 3121 NeedsADL, R.isOverloadedResult(), 3122 R.begin(), R.end()); 3123 3124 return ULE; 3125 } 3126 3127 static void 3128 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3129 ValueDecl *var, DeclContext *DC); 3130 3131 /// Complete semantic analysis for a reference to the given declaration. 3132 ExprResult Sema::BuildDeclarationNameExpr( 3133 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3134 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3135 bool AcceptInvalidDecl) { 3136 assert(D && "Cannot refer to a NULL declaration"); 3137 assert(!isa<FunctionTemplateDecl>(D) && 3138 "Cannot refer unambiguously to a function template"); 3139 3140 SourceLocation Loc = NameInfo.getLoc(); 3141 if (CheckDeclInExpr(*this, Loc, D)) 3142 return ExprError(); 3143 3144 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3145 // Specifically diagnose references to class templates that are missing 3146 // a template argument list. 3147 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3148 return ExprError(); 3149 } 3150 3151 // Make sure that we're referring to a value. 3152 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3153 if (!VD) { 3154 Diag(Loc, diag::err_ref_non_value) 3155 << D << SS.getRange(); 3156 Diag(D->getLocation(), diag::note_declared_at); 3157 return ExprError(); 3158 } 3159 3160 // Check whether this declaration can be used. Note that we suppress 3161 // this check when we're going to perform argument-dependent lookup 3162 // on this function name, because this might not be the function 3163 // that overload resolution actually selects. 3164 if (DiagnoseUseOfDecl(VD, Loc)) 3165 return ExprError(); 3166 3167 // Only create DeclRefExpr's for valid Decl's. 3168 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3169 return ExprError(); 3170 3171 // Handle members of anonymous structs and unions. If we got here, 3172 // and the reference is to a class member indirect field, then this 3173 // must be the subject of a pointer-to-member expression. 3174 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3175 if (!indirectField->isCXXClassMember()) 3176 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3177 indirectField); 3178 3179 { 3180 QualType type = VD->getType(); 3181 if (type.isNull()) 3182 return ExprError(); 3183 ExprValueKind valueKind = VK_RValue; 3184 3185 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3186 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3187 // is expanded by some outer '...' in the context of the use. 3188 type = type.getNonPackExpansionType(); 3189 3190 switch (D->getKind()) { 3191 // Ignore all the non-ValueDecl kinds. 3192 #define ABSTRACT_DECL(kind) 3193 #define VALUE(type, base) 3194 #define DECL(type, base) \ 3195 case Decl::type: 3196 #include "clang/AST/DeclNodes.inc" 3197 llvm_unreachable("invalid value decl kind"); 3198 3199 // These shouldn't make it here. 3200 case Decl::ObjCAtDefsField: 3201 llvm_unreachable("forming non-member reference to ivar?"); 3202 3203 // Enum constants are always r-values and never references. 3204 // Unresolved using declarations are dependent. 3205 case Decl::EnumConstant: 3206 case Decl::UnresolvedUsingValue: 3207 case Decl::OMPDeclareReduction: 3208 case Decl::OMPDeclareMapper: 3209 valueKind = VK_RValue; 3210 break; 3211 3212 // Fields and indirect fields that got here must be for 3213 // pointer-to-member expressions; we just call them l-values for 3214 // internal consistency, because this subexpression doesn't really 3215 // exist in the high-level semantics. 3216 case Decl::Field: 3217 case Decl::IndirectField: 3218 case Decl::ObjCIvar: 3219 assert(getLangOpts().CPlusPlus && 3220 "building reference to field in C?"); 3221 3222 // These can't have reference type in well-formed programs, but 3223 // for internal consistency we do this anyway. 3224 type = type.getNonReferenceType(); 3225 valueKind = VK_LValue; 3226 break; 3227 3228 // Non-type template parameters are either l-values or r-values 3229 // depending on the type. 3230 case Decl::NonTypeTemplateParm: { 3231 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3232 type = reftype->getPointeeType(); 3233 valueKind = VK_LValue; // even if the parameter is an r-value reference 3234 break; 3235 } 3236 3237 // [expr.prim.id.unqual]p2: 3238 // If the entity is a template parameter object for a template 3239 // parameter of type T, the type of the expression is const T. 3240 // [...] The expression is an lvalue if the entity is a [...] template 3241 // parameter object. 3242 if (type->isRecordType()) { 3243 type = type.getUnqualifiedType().withConst(); 3244 valueKind = VK_LValue; 3245 break; 3246 } 3247 3248 // For non-references, we need to strip qualifiers just in case 3249 // the template parameter was declared as 'const int' or whatever. 3250 valueKind = VK_RValue; 3251 type = type.getUnqualifiedType(); 3252 break; 3253 } 3254 3255 case Decl::Var: 3256 case Decl::VarTemplateSpecialization: 3257 case Decl::VarTemplatePartialSpecialization: 3258 case Decl::Decomposition: 3259 case Decl::OMPCapturedExpr: 3260 // In C, "extern void blah;" is valid and is an r-value. 3261 if (!getLangOpts().CPlusPlus && 3262 !type.hasQualifiers() && 3263 type->isVoidType()) { 3264 valueKind = VK_RValue; 3265 break; 3266 } 3267 LLVM_FALLTHROUGH; 3268 3269 case Decl::ImplicitParam: 3270 case Decl::ParmVar: { 3271 // These are always l-values. 3272 valueKind = VK_LValue; 3273 type = type.getNonReferenceType(); 3274 3275 // FIXME: Does the addition of const really only apply in 3276 // potentially-evaluated contexts? Since the variable isn't actually 3277 // captured in an unevaluated context, it seems that the answer is no. 3278 if (!isUnevaluatedContext()) { 3279 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3280 if (!CapturedType.isNull()) 3281 type = CapturedType; 3282 } 3283 3284 break; 3285 } 3286 3287 case Decl::Binding: { 3288 // These are always lvalues. 3289 valueKind = VK_LValue; 3290 type = type.getNonReferenceType(); 3291 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3292 // decides how that's supposed to work. 3293 auto *BD = cast<BindingDecl>(VD); 3294 if (BD->getDeclContext() != CurContext) { 3295 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3296 if (DD && DD->hasLocalStorage()) 3297 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3298 } 3299 break; 3300 } 3301 3302 case Decl::Function: { 3303 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3304 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3305 type = Context.BuiltinFnTy; 3306 valueKind = VK_RValue; 3307 break; 3308 } 3309 } 3310 3311 const FunctionType *fty = type->castAs<FunctionType>(); 3312 3313 // If we're referring to a function with an __unknown_anytype 3314 // result type, make the entire expression __unknown_anytype. 3315 if (fty->getReturnType() == Context.UnknownAnyTy) { 3316 type = Context.UnknownAnyTy; 3317 valueKind = VK_RValue; 3318 break; 3319 } 3320 3321 // Functions are l-values in C++. 3322 if (getLangOpts().CPlusPlus) { 3323 valueKind = VK_LValue; 3324 break; 3325 } 3326 3327 // C99 DR 316 says that, if a function type comes from a 3328 // function definition (without a prototype), that type is only 3329 // used for checking compatibility. Therefore, when referencing 3330 // the function, we pretend that we don't have the full function 3331 // type. 3332 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3333 isa<FunctionProtoType>(fty)) 3334 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3335 fty->getExtInfo()); 3336 3337 // Functions are r-values in C. 3338 valueKind = VK_RValue; 3339 break; 3340 } 3341 3342 case Decl::CXXDeductionGuide: 3343 llvm_unreachable("building reference to deduction guide"); 3344 3345 case Decl::MSProperty: 3346 case Decl::MSGuid: 3347 case Decl::TemplateParamObject: 3348 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3349 // capture in OpenMP, or duplicated between host and device? 3350 valueKind = VK_LValue; 3351 break; 3352 3353 case Decl::CXXMethod: 3354 // If we're referring to a method with an __unknown_anytype 3355 // result type, make the entire expression __unknown_anytype. 3356 // This should only be possible with a type written directly. 3357 if (const FunctionProtoType *proto 3358 = dyn_cast<FunctionProtoType>(VD->getType())) 3359 if (proto->getReturnType() == Context.UnknownAnyTy) { 3360 type = Context.UnknownAnyTy; 3361 valueKind = VK_RValue; 3362 break; 3363 } 3364 3365 // C++ methods are l-values if static, r-values if non-static. 3366 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3367 valueKind = VK_LValue; 3368 break; 3369 } 3370 LLVM_FALLTHROUGH; 3371 3372 case Decl::CXXConversion: 3373 case Decl::CXXDestructor: 3374 case Decl::CXXConstructor: 3375 valueKind = VK_RValue; 3376 break; 3377 } 3378 3379 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3380 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3381 TemplateArgs); 3382 } 3383 } 3384 3385 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3386 SmallString<32> &Target) { 3387 Target.resize(CharByteWidth * (Source.size() + 1)); 3388 char *ResultPtr = &Target[0]; 3389 const llvm::UTF8 *ErrorPtr; 3390 bool success = 3391 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3392 (void)success; 3393 assert(success); 3394 Target.resize(ResultPtr - &Target[0]); 3395 } 3396 3397 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3398 PredefinedExpr::IdentKind IK) { 3399 // Pick the current block, lambda, captured statement or function. 3400 Decl *currentDecl = nullptr; 3401 if (const BlockScopeInfo *BSI = getCurBlock()) 3402 currentDecl = BSI->TheDecl; 3403 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3404 currentDecl = LSI->CallOperator; 3405 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3406 currentDecl = CSI->TheCapturedDecl; 3407 else 3408 currentDecl = getCurFunctionOrMethodDecl(); 3409 3410 if (!currentDecl) { 3411 Diag(Loc, diag::ext_predef_outside_function); 3412 currentDecl = Context.getTranslationUnitDecl(); 3413 } 3414 3415 QualType ResTy; 3416 StringLiteral *SL = nullptr; 3417 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3418 ResTy = Context.DependentTy; 3419 else { 3420 // Pre-defined identifiers are of type char[x], where x is the length of 3421 // the string. 3422 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3423 unsigned Length = Str.length(); 3424 3425 llvm::APInt LengthI(32, Length + 1); 3426 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3427 ResTy = 3428 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3429 SmallString<32> RawChars; 3430 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3431 Str, RawChars); 3432 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3433 ArrayType::Normal, 3434 /*IndexTypeQuals*/ 0); 3435 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3436 /*Pascal*/ false, ResTy, Loc); 3437 } else { 3438 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3439 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3440 ArrayType::Normal, 3441 /*IndexTypeQuals*/ 0); 3442 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3443 /*Pascal*/ false, ResTy, Loc); 3444 } 3445 } 3446 3447 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3448 } 3449 3450 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3451 PredefinedExpr::IdentKind IK; 3452 3453 switch (Kind) { 3454 default: llvm_unreachable("Unknown simple primary expr!"); 3455 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3456 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3457 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3458 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3459 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3460 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3461 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3462 } 3463 3464 return BuildPredefinedExpr(Loc, IK); 3465 } 3466 3467 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3468 SmallString<16> CharBuffer; 3469 bool Invalid = false; 3470 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3471 if (Invalid) 3472 return ExprError(); 3473 3474 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3475 PP, Tok.getKind()); 3476 if (Literal.hadError()) 3477 return ExprError(); 3478 3479 QualType Ty; 3480 if (Literal.isWide()) 3481 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3482 else if (Literal.isUTF8() && getLangOpts().Char8) 3483 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3484 else if (Literal.isUTF16()) 3485 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3486 else if (Literal.isUTF32()) 3487 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3488 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3489 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3490 else 3491 Ty = Context.CharTy; // 'x' -> char in C++ 3492 3493 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3494 if (Literal.isWide()) 3495 Kind = CharacterLiteral::Wide; 3496 else if (Literal.isUTF16()) 3497 Kind = CharacterLiteral::UTF16; 3498 else if (Literal.isUTF32()) 3499 Kind = CharacterLiteral::UTF32; 3500 else if (Literal.isUTF8()) 3501 Kind = CharacterLiteral::UTF8; 3502 3503 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3504 Tok.getLocation()); 3505 3506 if (Literal.getUDSuffix().empty()) 3507 return Lit; 3508 3509 // We're building a user-defined literal. 3510 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3511 SourceLocation UDSuffixLoc = 3512 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3513 3514 // Make sure we're allowed user-defined literals here. 3515 if (!UDLScope) 3516 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3517 3518 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3519 // operator "" X (ch) 3520 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3521 Lit, Tok.getLocation()); 3522 } 3523 3524 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3525 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3526 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3527 Context.IntTy, Loc); 3528 } 3529 3530 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3531 QualType Ty, SourceLocation Loc) { 3532 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3533 3534 using llvm::APFloat; 3535 APFloat Val(Format); 3536 3537 APFloat::opStatus result = Literal.GetFloatValue(Val); 3538 3539 // Overflow is always an error, but underflow is only an error if 3540 // we underflowed to zero (APFloat reports denormals as underflow). 3541 if ((result & APFloat::opOverflow) || 3542 ((result & APFloat::opUnderflow) && Val.isZero())) { 3543 unsigned diagnostic; 3544 SmallString<20> buffer; 3545 if (result & APFloat::opOverflow) { 3546 diagnostic = diag::warn_float_overflow; 3547 APFloat::getLargest(Format).toString(buffer); 3548 } else { 3549 diagnostic = diag::warn_float_underflow; 3550 APFloat::getSmallest(Format).toString(buffer); 3551 } 3552 3553 S.Diag(Loc, diagnostic) 3554 << Ty 3555 << StringRef(buffer.data(), buffer.size()); 3556 } 3557 3558 bool isExact = (result == APFloat::opOK); 3559 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3560 } 3561 3562 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3563 assert(E && "Invalid expression"); 3564 3565 if (E->isValueDependent()) 3566 return false; 3567 3568 QualType QT = E->getType(); 3569 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3570 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3571 return true; 3572 } 3573 3574 llvm::APSInt ValueAPS; 3575 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3576 3577 if (R.isInvalid()) 3578 return true; 3579 3580 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3581 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3582 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3583 << ValueAPS.toString(10) << ValueIsPositive; 3584 return true; 3585 } 3586 3587 return false; 3588 } 3589 3590 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3591 // Fast path for a single digit (which is quite common). A single digit 3592 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3593 if (Tok.getLength() == 1) { 3594 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3595 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3596 } 3597 3598 SmallString<128> SpellingBuffer; 3599 // NumericLiteralParser wants to overread by one character. Add padding to 3600 // the buffer in case the token is copied to the buffer. If getSpelling() 3601 // returns a StringRef to the memory buffer, it should have a null char at 3602 // the EOF, so it is also safe. 3603 SpellingBuffer.resize(Tok.getLength() + 1); 3604 3605 // Get the spelling of the token, which eliminates trigraphs, etc. 3606 bool Invalid = false; 3607 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3608 if (Invalid) 3609 return ExprError(); 3610 3611 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3612 PP.getSourceManager(), PP.getLangOpts(), 3613 PP.getTargetInfo(), PP.getDiagnostics()); 3614 if (Literal.hadError) 3615 return ExprError(); 3616 3617 if (Literal.hasUDSuffix()) { 3618 // We're building a user-defined literal. 3619 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3620 SourceLocation UDSuffixLoc = 3621 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3622 3623 // Make sure we're allowed user-defined literals here. 3624 if (!UDLScope) 3625 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3626 3627 QualType CookedTy; 3628 if (Literal.isFloatingLiteral()) { 3629 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3630 // long double, the literal is treated as a call of the form 3631 // operator "" X (f L) 3632 CookedTy = Context.LongDoubleTy; 3633 } else { 3634 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3635 // unsigned long long, the literal is treated as a call of the form 3636 // operator "" X (n ULL) 3637 CookedTy = Context.UnsignedLongLongTy; 3638 } 3639 3640 DeclarationName OpName = 3641 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3642 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3643 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3644 3645 SourceLocation TokLoc = Tok.getLocation(); 3646 3647 // Perform literal operator lookup to determine if we're building a raw 3648 // literal or a cooked one. 3649 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3650 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3651 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3652 /*AllowStringTemplatePack*/ false, 3653 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3654 case LOLR_ErrorNoDiagnostic: 3655 // Lookup failure for imaginary constants isn't fatal, there's still the 3656 // GNU extension producing _Complex types. 3657 break; 3658 case LOLR_Error: 3659 return ExprError(); 3660 case LOLR_Cooked: { 3661 Expr *Lit; 3662 if (Literal.isFloatingLiteral()) { 3663 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3664 } else { 3665 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3666 if (Literal.GetIntegerValue(ResultVal)) 3667 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3668 << /* Unsigned */ 1; 3669 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3670 Tok.getLocation()); 3671 } 3672 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3673 } 3674 3675 case LOLR_Raw: { 3676 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3677 // literal is treated as a call of the form 3678 // operator "" X ("n") 3679 unsigned Length = Literal.getUDSuffixOffset(); 3680 QualType StrTy = Context.getConstantArrayType( 3681 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3682 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3683 Expr *Lit = StringLiteral::Create( 3684 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3685 /*Pascal*/false, StrTy, &TokLoc, 1); 3686 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3687 } 3688 3689 case LOLR_Template: { 3690 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3691 // template), L is treated as a call fo the form 3692 // operator "" X <'c1', 'c2', ... 'ck'>() 3693 // where n is the source character sequence c1 c2 ... ck. 3694 TemplateArgumentListInfo ExplicitArgs; 3695 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3696 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3697 llvm::APSInt Value(CharBits, CharIsUnsigned); 3698 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3699 Value = TokSpelling[I]; 3700 TemplateArgument Arg(Context, Value, Context.CharTy); 3701 TemplateArgumentLocInfo ArgInfo; 3702 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3703 } 3704 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3705 &ExplicitArgs); 3706 } 3707 case LOLR_StringTemplatePack: 3708 llvm_unreachable("unexpected literal operator lookup result"); 3709 } 3710 } 3711 3712 Expr *Res; 3713 3714 if (Literal.isFixedPointLiteral()) { 3715 QualType Ty; 3716 3717 if (Literal.isAccum) { 3718 if (Literal.isHalf) { 3719 Ty = Context.ShortAccumTy; 3720 } else if (Literal.isLong) { 3721 Ty = Context.LongAccumTy; 3722 } else { 3723 Ty = Context.AccumTy; 3724 } 3725 } else if (Literal.isFract) { 3726 if (Literal.isHalf) { 3727 Ty = Context.ShortFractTy; 3728 } else if (Literal.isLong) { 3729 Ty = Context.LongFractTy; 3730 } else { 3731 Ty = Context.FractTy; 3732 } 3733 } 3734 3735 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3736 3737 bool isSigned = !Literal.isUnsigned; 3738 unsigned scale = Context.getFixedPointScale(Ty); 3739 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3740 3741 llvm::APInt Val(bit_width, 0, isSigned); 3742 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3743 bool ValIsZero = Val.isNullValue() && !Overflowed; 3744 3745 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3746 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3747 // Clause 6.4.4 - The value of a constant shall be in the range of 3748 // representable values for its type, with exception for constants of a 3749 // fract type with a value of exactly 1; such a constant shall denote 3750 // the maximal value for the type. 3751 --Val; 3752 else if (Val.ugt(MaxVal) || Overflowed) 3753 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3754 3755 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3756 Tok.getLocation(), scale); 3757 } else if (Literal.isFloatingLiteral()) { 3758 QualType Ty; 3759 if (Literal.isHalf){ 3760 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3761 Ty = Context.HalfTy; 3762 else { 3763 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3764 return ExprError(); 3765 } 3766 } else if (Literal.isFloat) 3767 Ty = Context.FloatTy; 3768 else if (Literal.isLong) 3769 Ty = Context.LongDoubleTy; 3770 else if (Literal.isFloat16) 3771 Ty = Context.Float16Ty; 3772 else if (Literal.isFloat128) 3773 Ty = Context.Float128Ty; 3774 else 3775 Ty = Context.DoubleTy; 3776 3777 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3778 3779 if (Ty == Context.DoubleTy) { 3780 if (getLangOpts().SinglePrecisionConstants) { 3781 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3782 if (BTy->getKind() != BuiltinType::Float) { 3783 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3784 } 3785 } else if (getLangOpts().OpenCL && 3786 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3787 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3788 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3789 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3790 } 3791 } 3792 } else if (!Literal.isIntegerLiteral()) { 3793 return ExprError(); 3794 } else { 3795 QualType Ty; 3796 3797 // 'long long' is a C99 or C++11 feature. 3798 if (!getLangOpts().C99 && Literal.isLongLong) { 3799 if (getLangOpts().CPlusPlus) 3800 Diag(Tok.getLocation(), 3801 getLangOpts().CPlusPlus11 ? 3802 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3803 else 3804 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3805 } 3806 3807 // Get the value in the widest-possible width. 3808 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3809 llvm::APInt ResultVal(MaxWidth, 0); 3810 3811 if (Literal.GetIntegerValue(ResultVal)) { 3812 // If this value didn't fit into uintmax_t, error and force to ull. 3813 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3814 << /* Unsigned */ 1; 3815 Ty = Context.UnsignedLongLongTy; 3816 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3817 "long long is not intmax_t?"); 3818 } else { 3819 // If this value fits into a ULL, try to figure out what else it fits into 3820 // according to the rules of C99 6.4.4.1p5. 3821 3822 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3823 // be an unsigned int. 3824 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3825 3826 // Check from smallest to largest, picking the smallest type we can. 3827 unsigned Width = 0; 3828 3829 // Microsoft specific integer suffixes are explicitly sized. 3830 if (Literal.MicrosoftInteger) { 3831 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3832 Width = 8; 3833 Ty = Context.CharTy; 3834 } else { 3835 Width = Literal.MicrosoftInteger; 3836 Ty = Context.getIntTypeForBitwidth(Width, 3837 /*Signed=*/!Literal.isUnsigned); 3838 } 3839 } 3840 3841 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3842 // Are int/unsigned possibilities? 3843 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3844 3845 // Does it fit in a unsigned int? 3846 if (ResultVal.isIntN(IntSize)) { 3847 // Does it fit in a signed int? 3848 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3849 Ty = Context.IntTy; 3850 else if (AllowUnsigned) 3851 Ty = Context.UnsignedIntTy; 3852 Width = IntSize; 3853 } 3854 } 3855 3856 // Are long/unsigned long possibilities? 3857 if (Ty.isNull() && !Literal.isLongLong) { 3858 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3859 3860 // Does it fit in a unsigned long? 3861 if (ResultVal.isIntN(LongSize)) { 3862 // Does it fit in a signed long? 3863 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3864 Ty = Context.LongTy; 3865 else if (AllowUnsigned) 3866 Ty = Context.UnsignedLongTy; 3867 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3868 // is compatible. 3869 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3870 const unsigned LongLongSize = 3871 Context.getTargetInfo().getLongLongWidth(); 3872 Diag(Tok.getLocation(), 3873 getLangOpts().CPlusPlus 3874 ? Literal.isLong 3875 ? diag::warn_old_implicitly_unsigned_long_cxx 3876 : /*C++98 UB*/ diag:: 3877 ext_old_implicitly_unsigned_long_cxx 3878 : diag::warn_old_implicitly_unsigned_long) 3879 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3880 : /*will be ill-formed*/ 1); 3881 Ty = Context.UnsignedLongTy; 3882 } 3883 Width = LongSize; 3884 } 3885 } 3886 3887 // Check long long if needed. 3888 if (Ty.isNull()) { 3889 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3890 3891 // Does it fit in a unsigned long long? 3892 if (ResultVal.isIntN(LongLongSize)) { 3893 // Does it fit in a signed long long? 3894 // To be compatible with MSVC, hex integer literals ending with the 3895 // LL or i64 suffix are always signed in Microsoft mode. 3896 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3897 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3898 Ty = Context.LongLongTy; 3899 else if (AllowUnsigned) 3900 Ty = Context.UnsignedLongLongTy; 3901 Width = LongLongSize; 3902 } 3903 } 3904 3905 // If we still couldn't decide a type, we probably have something that 3906 // does not fit in a signed long long, but has no U suffix. 3907 if (Ty.isNull()) { 3908 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3909 Ty = Context.UnsignedLongLongTy; 3910 Width = Context.getTargetInfo().getLongLongWidth(); 3911 } 3912 3913 if (ResultVal.getBitWidth() != Width) 3914 ResultVal = ResultVal.trunc(Width); 3915 } 3916 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3917 } 3918 3919 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3920 if (Literal.isImaginary) { 3921 Res = new (Context) ImaginaryLiteral(Res, 3922 Context.getComplexType(Res->getType())); 3923 3924 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3925 } 3926 return Res; 3927 } 3928 3929 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3930 assert(E && "ActOnParenExpr() missing expr"); 3931 return new (Context) ParenExpr(L, R, E); 3932 } 3933 3934 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3935 SourceLocation Loc, 3936 SourceRange ArgRange) { 3937 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3938 // scalar or vector data type argument..." 3939 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3940 // type (C99 6.2.5p18) or void. 3941 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3942 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3943 << T << ArgRange; 3944 return true; 3945 } 3946 3947 assert((T->isVoidType() || !T->isIncompleteType()) && 3948 "Scalar types should always be complete"); 3949 return false; 3950 } 3951 3952 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3953 SourceLocation Loc, 3954 SourceRange ArgRange, 3955 UnaryExprOrTypeTrait TraitKind) { 3956 // Invalid types must be hard errors for SFINAE in C++. 3957 if (S.LangOpts.CPlusPlus) 3958 return true; 3959 3960 // C99 6.5.3.4p1: 3961 if (T->isFunctionType() && 3962 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3963 TraitKind == UETT_PreferredAlignOf)) { 3964 // sizeof(function)/alignof(function) is allowed as an extension. 3965 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3966 << getTraitSpelling(TraitKind) << ArgRange; 3967 return false; 3968 } 3969 3970 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3971 // this is an error (OpenCL v1.1 s6.3.k) 3972 if (T->isVoidType()) { 3973 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3974 : diag::ext_sizeof_alignof_void_type; 3975 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 3976 return false; 3977 } 3978 3979 return true; 3980 } 3981 3982 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3983 SourceLocation Loc, 3984 SourceRange ArgRange, 3985 UnaryExprOrTypeTrait TraitKind) { 3986 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3987 // runtime doesn't allow it. 3988 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3989 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3990 << T << (TraitKind == UETT_SizeOf) 3991 << ArgRange; 3992 return true; 3993 } 3994 3995 return false; 3996 } 3997 3998 /// Check whether E is a pointer from a decayed array type (the decayed 3999 /// pointer type is equal to T) and emit a warning if it is. 4000 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4001 Expr *E) { 4002 // Don't warn if the operation changed the type. 4003 if (T != E->getType()) 4004 return; 4005 4006 // Now look for array decays. 4007 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4008 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4009 return; 4010 4011 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4012 << ICE->getType() 4013 << ICE->getSubExpr()->getType(); 4014 } 4015 4016 /// Check the constraints on expression operands to unary type expression 4017 /// and type traits. 4018 /// 4019 /// Completes any types necessary and validates the constraints on the operand 4020 /// expression. The logic mostly mirrors the type-based overload, but may modify 4021 /// the expression as it completes the type for that expression through template 4022 /// instantiation, etc. 4023 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4024 UnaryExprOrTypeTrait ExprKind) { 4025 QualType ExprTy = E->getType(); 4026 assert(!ExprTy->isReferenceType()); 4027 4028 bool IsUnevaluatedOperand = 4029 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4030 ExprKind == UETT_PreferredAlignOf); 4031 if (IsUnevaluatedOperand) { 4032 ExprResult Result = CheckUnevaluatedOperand(E); 4033 if (Result.isInvalid()) 4034 return true; 4035 E = Result.get(); 4036 } 4037 4038 if (ExprKind == UETT_VecStep) 4039 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4040 E->getSourceRange()); 4041 4042 // Explicitly list some types as extensions. 4043 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4044 E->getSourceRange(), ExprKind)) 4045 return false; 4046 4047 // 'alignof' applied to an expression only requires the base element type of 4048 // the expression to be complete. 'sizeof' requires the expression's type to 4049 // be complete (and will attempt to complete it if it's an array of unknown 4050 // bound). 4051 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4052 if (RequireCompleteSizedType( 4053 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4054 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4055 getTraitSpelling(ExprKind), E->getSourceRange())) 4056 return true; 4057 } else { 4058 if (RequireCompleteSizedExprType( 4059 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4060 getTraitSpelling(ExprKind), E->getSourceRange())) 4061 return true; 4062 } 4063 4064 // Completing the expression's type may have changed it. 4065 ExprTy = E->getType(); 4066 assert(!ExprTy->isReferenceType()); 4067 4068 if (ExprTy->isFunctionType()) { 4069 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4070 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4071 return true; 4072 } 4073 4074 // The operand for sizeof and alignof is in an unevaluated expression context, 4075 // so side effects could result in unintended consequences. 4076 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4077 E->HasSideEffects(Context, false)) 4078 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4079 4080 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4081 E->getSourceRange(), ExprKind)) 4082 return true; 4083 4084 if (ExprKind == UETT_SizeOf) { 4085 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4086 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4087 QualType OType = PVD->getOriginalType(); 4088 QualType Type = PVD->getType(); 4089 if (Type->isPointerType() && OType->isArrayType()) { 4090 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4091 << Type << OType; 4092 Diag(PVD->getLocation(), diag::note_declared_at); 4093 } 4094 } 4095 } 4096 4097 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4098 // decays into a pointer and returns an unintended result. This is most 4099 // likely a typo for "sizeof(array) op x". 4100 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4101 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4102 BO->getLHS()); 4103 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4104 BO->getRHS()); 4105 } 4106 } 4107 4108 return false; 4109 } 4110 4111 /// Check the constraints on operands to unary expression and type 4112 /// traits. 4113 /// 4114 /// This will complete any types necessary, and validate the various constraints 4115 /// on those operands. 4116 /// 4117 /// The UsualUnaryConversions() function is *not* called by this routine. 4118 /// C99 6.3.2.1p[2-4] all state: 4119 /// Except when it is the operand of the sizeof operator ... 4120 /// 4121 /// C++ [expr.sizeof]p4 4122 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4123 /// standard conversions are not applied to the operand of sizeof. 4124 /// 4125 /// This policy is followed for all of the unary trait expressions. 4126 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4127 SourceLocation OpLoc, 4128 SourceRange ExprRange, 4129 UnaryExprOrTypeTrait ExprKind) { 4130 if (ExprType->isDependentType()) 4131 return false; 4132 4133 // C++ [expr.sizeof]p2: 4134 // When applied to a reference or a reference type, the result 4135 // is the size of the referenced type. 4136 // C++11 [expr.alignof]p3: 4137 // When alignof is applied to a reference type, the result 4138 // shall be the alignment of the referenced type. 4139 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4140 ExprType = Ref->getPointeeType(); 4141 4142 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4143 // When alignof or _Alignof is applied to an array type, the result 4144 // is the alignment of the element type. 4145 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4146 ExprKind == UETT_OpenMPRequiredSimdAlign) 4147 ExprType = Context.getBaseElementType(ExprType); 4148 4149 if (ExprKind == UETT_VecStep) 4150 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4151 4152 // Explicitly list some types as extensions. 4153 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4154 ExprKind)) 4155 return false; 4156 4157 if (RequireCompleteSizedType( 4158 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4159 getTraitSpelling(ExprKind), ExprRange)) 4160 return true; 4161 4162 if (ExprType->isFunctionType()) { 4163 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4164 << getTraitSpelling(ExprKind) << ExprRange; 4165 return true; 4166 } 4167 4168 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4169 ExprKind)) 4170 return true; 4171 4172 return false; 4173 } 4174 4175 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4176 // Cannot know anything else if the expression is dependent. 4177 if (E->isTypeDependent()) 4178 return false; 4179 4180 if (E->getObjectKind() == OK_BitField) { 4181 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4182 << 1 << E->getSourceRange(); 4183 return true; 4184 } 4185 4186 ValueDecl *D = nullptr; 4187 Expr *Inner = E->IgnoreParens(); 4188 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4189 D = DRE->getDecl(); 4190 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4191 D = ME->getMemberDecl(); 4192 } 4193 4194 // If it's a field, require the containing struct to have a 4195 // complete definition so that we can compute the layout. 4196 // 4197 // This can happen in C++11 onwards, either by naming the member 4198 // in a way that is not transformed into a member access expression 4199 // (in an unevaluated operand, for instance), or by naming the member 4200 // in a trailing-return-type. 4201 // 4202 // For the record, since __alignof__ on expressions is a GCC 4203 // extension, GCC seems to permit this but always gives the 4204 // nonsensical answer 0. 4205 // 4206 // We don't really need the layout here --- we could instead just 4207 // directly check for all the appropriate alignment-lowing 4208 // attributes --- but that would require duplicating a lot of 4209 // logic that just isn't worth duplicating for such a marginal 4210 // use-case. 4211 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4212 // Fast path this check, since we at least know the record has a 4213 // definition if we can find a member of it. 4214 if (!FD->getParent()->isCompleteDefinition()) { 4215 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4216 << E->getSourceRange(); 4217 return true; 4218 } 4219 4220 // Otherwise, if it's a field, and the field doesn't have 4221 // reference type, then it must have a complete type (or be a 4222 // flexible array member, which we explicitly want to 4223 // white-list anyway), which makes the following checks trivial. 4224 if (!FD->getType()->isReferenceType()) 4225 return false; 4226 } 4227 4228 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4229 } 4230 4231 bool Sema::CheckVecStepExpr(Expr *E) { 4232 E = E->IgnoreParens(); 4233 4234 // Cannot know anything else if the expression is dependent. 4235 if (E->isTypeDependent()) 4236 return false; 4237 4238 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4239 } 4240 4241 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4242 CapturingScopeInfo *CSI) { 4243 assert(T->isVariablyModifiedType()); 4244 assert(CSI != nullptr); 4245 4246 // We're going to walk down into the type and look for VLA expressions. 4247 do { 4248 const Type *Ty = T.getTypePtr(); 4249 switch (Ty->getTypeClass()) { 4250 #define TYPE(Class, Base) 4251 #define ABSTRACT_TYPE(Class, Base) 4252 #define NON_CANONICAL_TYPE(Class, Base) 4253 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4254 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4255 #include "clang/AST/TypeNodes.inc" 4256 T = QualType(); 4257 break; 4258 // These types are never variably-modified. 4259 case Type::Builtin: 4260 case Type::Complex: 4261 case Type::Vector: 4262 case Type::ExtVector: 4263 case Type::ConstantMatrix: 4264 case Type::Record: 4265 case Type::Enum: 4266 case Type::Elaborated: 4267 case Type::TemplateSpecialization: 4268 case Type::ObjCObject: 4269 case Type::ObjCInterface: 4270 case Type::ObjCObjectPointer: 4271 case Type::ObjCTypeParam: 4272 case Type::Pipe: 4273 case Type::ExtInt: 4274 llvm_unreachable("type class is never variably-modified!"); 4275 case Type::Adjusted: 4276 T = cast<AdjustedType>(Ty)->getOriginalType(); 4277 break; 4278 case Type::Decayed: 4279 T = cast<DecayedType>(Ty)->getPointeeType(); 4280 break; 4281 case Type::Pointer: 4282 T = cast<PointerType>(Ty)->getPointeeType(); 4283 break; 4284 case Type::BlockPointer: 4285 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4286 break; 4287 case Type::LValueReference: 4288 case Type::RValueReference: 4289 T = cast<ReferenceType>(Ty)->getPointeeType(); 4290 break; 4291 case Type::MemberPointer: 4292 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4293 break; 4294 case Type::ConstantArray: 4295 case Type::IncompleteArray: 4296 // Losing element qualification here is fine. 4297 T = cast<ArrayType>(Ty)->getElementType(); 4298 break; 4299 case Type::VariableArray: { 4300 // Losing element qualification here is fine. 4301 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4302 4303 // Unknown size indication requires no size computation. 4304 // Otherwise, evaluate and record it. 4305 auto Size = VAT->getSizeExpr(); 4306 if (Size && !CSI->isVLATypeCaptured(VAT) && 4307 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4308 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4309 4310 T = VAT->getElementType(); 4311 break; 4312 } 4313 case Type::FunctionProto: 4314 case Type::FunctionNoProto: 4315 T = cast<FunctionType>(Ty)->getReturnType(); 4316 break; 4317 case Type::Paren: 4318 case Type::TypeOf: 4319 case Type::UnaryTransform: 4320 case Type::Attributed: 4321 case Type::SubstTemplateTypeParm: 4322 case Type::MacroQualified: 4323 // Keep walking after single level desugaring. 4324 T = T.getSingleStepDesugaredType(Context); 4325 break; 4326 case Type::Typedef: 4327 T = cast<TypedefType>(Ty)->desugar(); 4328 break; 4329 case Type::Decltype: 4330 T = cast<DecltypeType>(Ty)->desugar(); 4331 break; 4332 case Type::Auto: 4333 case Type::DeducedTemplateSpecialization: 4334 T = cast<DeducedType>(Ty)->getDeducedType(); 4335 break; 4336 case Type::TypeOfExpr: 4337 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4338 break; 4339 case Type::Atomic: 4340 T = cast<AtomicType>(Ty)->getValueType(); 4341 break; 4342 } 4343 } while (!T.isNull() && T->isVariablyModifiedType()); 4344 } 4345 4346 /// Build a sizeof or alignof expression given a type operand. 4347 ExprResult 4348 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4349 SourceLocation OpLoc, 4350 UnaryExprOrTypeTrait ExprKind, 4351 SourceRange R) { 4352 if (!TInfo) 4353 return ExprError(); 4354 4355 QualType T = TInfo->getType(); 4356 4357 if (!T->isDependentType() && 4358 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4359 return ExprError(); 4360 4361 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4362 if (auto *TT = T->getAs<TypedefType>()) { 4363 for (auto I = FunctionScopes.rbegin(), 4364 E = std::prev(FunctionScopes.rend()); 4365 I != E; ++I) { 4366 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4367 if (CSI == nullptr) 4368 break; 4369 DeclContext *DC = nullptr; 4370 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4371 DC = LSI->CallOperator; 4372 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4373 DC = CRSI->TheCapturedDecl; 4374 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4375 DC = BSI->TheDecl; 4376 if (DC) { 4377 if (DC->containsDecl(TT->getDecl())) 4378 break; 4379 captureVariablyModifiedType(Context, T, CSI); 4380 } 4381 } 4382 } 4383 } 4384 4385 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4386 return new (Context) UnaryExprOrTypeTraitExpr( 4387 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4388 } 4389 4390 /// Build a sizeof or alignof expression given an expression 4391 /// operand. 4392 ExprResult 4393 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4394 UnaryExprOrTypeTrait ExprKind) { 4395 ExprResult PE = CheckPlaceholderExpr(E); 4396 if (PE.isInvalid()) 4397 return ExprError(); 4398 4399 E = PE.get(); 4400 4401 // Verify that the operand is valid. 4402 bool isInvalid = false; 4403 if (E->isTypeDependent()) { 4404 // Delay type-checking for type-dependent expressions. 4405 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4406 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4407 } else if (ExprKind == UETT_VecStep) { 4408 isInvalid = CheckVecStepExpr(E); 4409 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4410 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4411 isInvalid = true; 4412 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4413 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4414 isInvalid = true; 4415 } else { 4416 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4417 } 4418 4419 if (isInvalid) 4420 return ExprError(); 4421 4422 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4423 PE = TransformToPotentiallyEvaluated(E); 4424 if (PE.isInvalid()) return ExprError(); 4425 E = PE.get(); 4426 } 4427 4428 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4429 return new (Context) UnaryExprOrTypeTraitExpr( 4430 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4431 } 4432 4433 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4434 /// expr and the same for @c alignof and @c __alignof 4435 /// Note that the ArgRange is invalid if isType is false. 4436 ExprResult 4437 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4438 UnaryExprOrTypeTrait ExprKind, bool IsType, 4439 void *TyOrEx, SourceRange ArgRange) { 4440 // If error parsing type, ignore. 4441 if (!TyOrEx) return ExprError(); 4442 4443 if (IsType) { 4444 TypeSourceInfo *TInfo; 4445 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4446 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4447 } 4448 4449 Expr *ArgEx = (Expr *)TyOrEx; 4450 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4451 return Result; 4452 } 4453 4454 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4455 bool IsReal) { 4456 if (V.get()->isTypeDependent()) 4457 return S.Context.DependentTy; 4458 4459 // _Real and _Imag are only l-values for normal l-values. 4460 if (V.get()->getObjectKind() != OK_Ordinary) { 4461 V = S.DefaultLvalueConversion(V.get()); 4462 if (V.isInvalid()) 4463 return QualType(); 4464 } 4465 4466 // These operators return the element type of a complex type. 4467 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4468 return CT->getElementType(); 4469 4470 // Otherwise they pass through real integer and floating point types here. 4471 if (V.get()->getType()->isArithmeticType()) 4472 return V.get()->getType(); 4473 4474 // Test for placeholders. 4475 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4476 if (PR.isInvalid()) return QualType(); 4477 if (PR.get() != V.get()) { 4478 V = PR; 4479 return CheckRealImagOperand(S, V, Loc, IsReal); 4480 } 4481 4482 // Reject anything else. 4483 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4484 << (IsReal ? "__real" : "__imag"); 4485 return QualType(); 4486 } 4487 4488 4489 4490 ExprResult 4491 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4492 tok::TokenKind Kind, Expr *Input) { 4493 UnaryOperatorKind Opc; 4494 switch (Kind) { 4495 default: llvm_unreachable("Unknown unary op!"); 4496 case tok::plusplus: Opc = UO_PostInc; break; 4497 case tok::minusminus: Opc = UO_PostDec; break; 4498 } 4499 4500 // Since this might is a postfix expression, get rid of ParenListExprs. 4501 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4502 if (Result.isInvalid()) return ExprError(); 4503 Input = Result.get(); 4504 4505 return BuildUnaryOp(S, OpLoc, Opc, Input); 4506 } 4507 4508 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4509 /// 4510 /// \return true on error 4511 static bool checkArithmeticOnObjCPointer(Sema &S, 4512 SourceLocation opLoc, 4513 Expr *op) { 4514 assert(op->getType()->isObjCObjectPointerType()); 4515 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4516 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4517 return false; 4518 4519 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4520 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4521 << op->getSourceRange(); 4522 return true; 4523 } 4524 4525 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4526 auto *BaseNoParens = Base->IgnoreParens(); 4527 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4528 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4529 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4530 } 4531 4532 ExprResult 4533 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4534 Expr *idx, SourceLocation rbLoc) { 4535 if (base && !base->getType().isNull() && 4536 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4537 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4538 SourceLocation(), /*Length*/ nullptr, 4539 /*Stride=*/nullptr, rbLoc); 4540 4541 // Since this might be a postfix expression, get rid of ParenListExprs. 4542 if (isa<ParenListExpr>(base)) { 4543 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4544 if (result.isInvalid()) return ExprError(); 4545 base = result.get(); 4546 } 4547 4548 // Check if base and idx form a MatrixSubscriptExpr. 4549 // 4550 // Helper to check for comma expressions, which are not allowed as indices for 4551 // matrix subscript expressions. 4552 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4553 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4554 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4555 << SourceRange(base->getBeginLoc(), rbLoc); 4556 return true; 4557 } 4558 return false; 4559 }; 4560 // The matrix subscript operator ([][])is considered a single operator. 4561 // Separating the index expressions by parenthesis is not allowed. 4562 if (base->getType()->isSpecificPlaceholderType( 4563 BuiltinType::IncompleteMatrixIdx) && 4564 !isa<MatrixSubscriptExpr>(base)) { 4565 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4566 << SourceRange(base->getBeginLoc(), rbLoc); 4567 return ExprError(); 4568 } 4569 // If the base is a MatrixSubscriptExpr, try to create a new 4570 // MatrixSubscriptExpr. 4571 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4572 if (matSubscriptE) { 4573 if (CheckAndReportCommaError(idx)) 4574 return ExprError(); 4575 4576 assert(matSubscriptE->isIncomplete() && 4577 "base has to be an incomplete matrix subscript"); 4578 return CreateBuiltinMatrixSubscriptExpr( 4579 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4580 } 4581 4582 // Handle any non-overload placeholder types in the base and index 4583 // expressions. We can't handle overloads here because the other 4584 // operand might be an overloadable type, in which case the overload 4585 // resolution for the operator overload should get the first crack 4586 // at the overload. 4587 bool IsMSPropertySubscript = false; 4588 if (base->getType()->isNonOverloadPlaceholderType()) { 4589 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4590 if (!IsMSPropertySubscript) { 4591 ExprResult result = CheckPlaceholderExpr(base); 4592 if (result.isInvalid()) 4593 return ExprError(); 4594 base = result.get(); 4595 } 4596 } 4597 4598 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4599 if (base->getType()->isMatrixType()) { 4600 if (CheckAndReportCommaError(idx)) 4601 return ExprError(); 4602 4603 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4604 } 4605 4606 // A comma-expression as the index is deprecated in C++2a onwards. 4607 if (getLangOpts().CPlusPlus20 && 4608 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4609 (isa<CXXOperatorCallExpr>(idx) && 4610 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4611 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4612 << SourceRange(base->getBeginLoc(), rbLoc); 4613 } 4614 4615 if (idx->getType()->isNonOverloadPlaceholderType()) { 4616 ExprResult result = CheckPlaceholderExpr(idx); 4617 if (result.isInvalid()) return ExprError(); 4618 idx = result.get(); 4619 } 4620 4621 // Build an unanalyzed expression if either operand is type-dependent. 4622 if (getLangOpts().CPlusPlus && 4623 (base->isTypeDependent() || idx->isTypeDependent())) { 4624 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4625 VK_LValue, OK_Ordinary, rbLoc); 4626 } 4627 4628 // MSDN, property (C++) 4629 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4630 // This attribute can also be used in the declaration of an empty array in a 4631 // class or structure definition. For example: 4632 // __declspec(property(get=GetX, put=PutX)) int x[]; 4633 // The above statement indicates that x[] can be used with one or more array 4634 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4635 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4636 if (IsMSPropertySubscript) { 4637 // Build MS property subscript expression if base is MS property reference 4638 // or MS property subscript. 4639 return new (Context) MSPropertySubscriptExpr( 4640 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4641 } 4642 4643 // Use C++ overloaded-operator rules if either operand has record 4644 // type. The spec says to do this if either type is *overloadable*, 4645 // but enum types can't declare subscript operators or conversion 4646 // operators, so there's nothing interesting for overload resolution 4647 // to do if there aren't any record types involved. 4648 // 4649 // ObjC pointers have their own subscripting logic that is not tied 4650 // to overload resolution and so should not take this path. 4651 if (getLangOpts().CPlusPlus && 4652 (base->getType()->isRecordType() || 4653 (!base->getType()->isObjCObjectPointerType() && 4654 idx->getType()->isRecordType()))) { 4655 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4656 } 4657 4658 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4659 4660 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4661 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4662 4663 return Res; 4664 } 4665 4666 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4667 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4668 InitializationKind Kind = 4669 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4670 InitializationSequence InitSeq(*this, Entity, Kind, E); 4671 return InitSeq.Perform(*this, Entity, Kind, E); 4672 } 4673 4674 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4675 Expr *ColumnIdx, 4676 SourceLocation RBLoc) { 4677 ExprResult BaseR = CheckPlaceholderExpr(Base); 4678 if (BaseR.isInvalid()) 4679 return BaseR; 4680 Base = BaseR.get(); 4681 4682 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4683 if (RowR.isInvalid()) 4684 return RowR; 4685 RowIdx = RowR.get(); 4686 4687 if (!ColumnIdx) 4688 return new (Context) MatrixSubscriptExpr( 4689 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4690 4691 // Build an unanalyzed expression if any of the operands is type-dependent. 4692 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4693 ColumnIdx->isTypeDependent()) 4694 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4695 Context.DependentTy, RBLoc); 4696 4697 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4698 if (ColumnR.isInvalid()) 4699 return ColumnR; 4700 ColumnIdx = ColumnR.get(); 4701 4702 // Check that IndexExpr is an integer expression. If it is a constant 4703 // expression, check that it is less than Dim (= the number of elements in the 4704 // corresponding dimension). 4705 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4706 bool IsColumnIdx) -> Expr * { 4707 if (!IndexExpr->getType()->isIntegerType() && 4708 !IndexExpr->isTypeDependent()) { 4709 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4710 << IsColumnIdx; 4711 return nullptr; 4712 } 4713 4714 if (Optional<llvm::APSInt> Idx = 4715 IndexExpr->getIntegerConstantExpr(Context)) { 4716 if ((*Idx < 0 || *Idx >= Dim)) { 4717 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4718 << IsColumnIdx << Dim; 4719 return nullptr; 4720 } 4721 } 4722 4723 ExprResult ConvExpr = 4724 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4725 assert(!ConvExpr.isInvalid() && 4726 "should be able to convert any integer type to size type"); 4727 return ConvExpr.get(); 4728 }; 4729 4730 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4731 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4732 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4733 if (!RowIdx || !ColumnIdx) 4734 return ExprError(); 4735 4736 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4737 MTy->getElementType(), RBLoc); 4738 } 4739 4740 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4741 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4742 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4743 4744 // For expressions like `&(*s).b`, the base is recorded and what should be 4745 // checked. 4746 const MemberExpr *Member = nullptr; 4747 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4748 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4749 4750 LastRecord.PossibleDerefs.erase(StrippedExpr); 4751 } 4752 4753 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4754 QualType ResultTy = E->getType(); 4755 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4756 4757 // Bail if the element is an array since it is not memory access. 4758 if (isa<ArrayType>(ResultTy)) 4759 return; 4760 4761 if (ResultTy->hasAttr(attr::NoDeref)) { 4762 LastRecord.PossibleDerefs.insert(E); 4763 return; 4764 } 4765 4766 // Check if the base type is a pointer to a member access of a struct 4767 // marked with noderef. 4768 const Expr *Base = E->getBase(); 4769 QualType BaseTy = Base->getType(); 4770 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4771 // Not a pointer access 4772 return; 4773 4774 const MemberExpr *Member = nullptr; 4775 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4776 Member->isArrow()) 4777 Base = Member->getBase(); 4778 4779 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4780 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4781 LastRecord.PossibleDerefs.insert(E); 4782 } 4783 } 4784 4785 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4786 Expr *LowerBound, 4787 SourceLocation ColonLocFirst, 4788 SourceLocation ColonLocSecond, 4789 Expr *Length, Expr *Stride, 4790 SourceLocation RBLoc) { 4791 if (Base->getType()->isPlaceholderType() && 4792 !Base->getType()->isSpecificPlaceholderType( 4793 BuiltinType::OMPArraySection)) { 4794 ExprResult Result = CheckPlaceholderExpr(Base); 4795 if (Result.isInvalid()) 4796 return ExprError(); 4797 Base = Result.get(); 4798 } 4799 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4800 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4801 if (Result.isInvalid()) 4802 return ExprError(); 4803 Result = DefaultLvalueConversion(Result.get()); 4804 if (Result.isInvalid()) 4805 return ExprError(); 4806 LowerBound = Result.get(); 4807 } 4808 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4809 ExprResult Result = CheckPlaceholderExpr(Length); 4810 if (Result.isInvalid()) 4811 return ExprError(); 4812 Result = DefaultLvalueConversion(Result.get()); 4813 if (Result.isInvalid()) 4814 return ExprError(); 4815 Length = Result.get(); 4816 } 4817 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4818 ExprResult Result = CheckPlaceholderExpr(Stride); 4819 if (Result.isInvalid()) 4820 return ExprError(); 4821 Result = DefaultLvalueConversion(Result.get()); 4822 if (Result.isInvalid()) 4823 return ExprError(); 4824 Stride = Result.get(); 4825 } 4826 4827 // Build an unanalyzed expression if either operand is type-dependent. 4828 if (Base->isTypeDependent() || 4829 (LowerBound && 4830 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4831 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4832 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4833 return new (Context) OMPArraySectionExpr( 4834 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4835 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4836 } 4837 4838 // Perform default conversions. 4839 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4840 QualType ResultTy; 4841 if (OriginalTy->isAnyPointerType()) { 4842 ResultTy = OriginalTy->getPointeeType(); 4843 } else if (OriginalTy->isArrayType()) { 4844 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4845 } else { 4846 return ExprError( 4847 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4848 << Base->getSourceRange()); 4849 } 4850 // C99 6.5.2.1p1 4851 if (LowerBound) { 4852 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4853 LowerBound); 4854 if (Res.isInvalid()) 4855 return ExprError(Diag(LowerBound->getExprLoc(), 4856 diag::err_omp_typecheck_section_not_integer) 4857 << 0 << LowerBound->getSourceRange()); 4858 LowerBound = Res.get(); 4859 4860 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4861 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4862 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4863 << 0 << LowerBound->getSourceRange(); 4864 } 4865 if (Length) { 4866 auto Res = 4867 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4868 if (Res.isInvalid()) 4869 return ExprError(Diag(Length->getExprLoc(), 4870 diag::err_omp_typecheck_section_not_integer) 4871 << 1 << Length->getSourceRange()); 4872 Length = Res.get(); 4873 4874 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4875 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4876 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4877 << 1 << Length->getSourceRange(); 4878 } 4879 if (Stride) { 4880 ExprResult Res = 4881 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4882 if (Res.isInvalid()) 4883 return ExprError(Diag(Stride->getExprLoc(), 4884 diag::err_omp_typecheck_section_not_integer) 4885 << 1 << Stride->getSourceRange()); 4886 Stride = Res.get(); 4887 4888 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4889 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4890 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4891 << 1 << Stride->getSourceRange(); 4892 } 4893 4894 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4895 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4896 // type. Note that functions are not objects, and that (in C99 parlance) 4897 // incomplete types are not object types. 4898 if (ResultTy->isFunctionType()) { 4899 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4900 << ResultTy << Base->getSourceRange(); 4901 return ExprError(); 4902 } 4903 4904 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4905 diag::err_omp_section_incomplete_type, Base)) 4906 return ExprError(); 4907 4908 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4909 Expr::EvalResult Result; 4910 if (LowerBound->EvaluateAsInt(Result, Context)) { 4911 // OpenMP 5.0, [2.1.5 Array Sections] 4912 // The array section must be a subset of the original array. 4913 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4914 if (LowerBoundValue.isNegative()) { 4915 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4916 << LowerBound->getSourceRange(); 4917 return ExprError(); 4918 } 4919 } 4920 } 4921 4922 if (Length) { 4923 Expr::EvalResult Result; 4924 if (Length->EvaluateAsInt(Result, Context)) { 4925 // OpenMP 5.0, [2.1.5 Array Sections] 4926 // The length must evaluate to non-negative integers. 4927 llvm::APSInt LengthValue = Result.Val.getInt(); 4928 if (LengthValue.isNegative()) { 4929 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4930 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4931 << Length->getSourceRange(); 4932 return ExprError(); 4933 } 4934 } 4935 } else if (ColonLocFirst.isValid() && 4936 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4937 !OriginalTy->isVariableArrayType()))) { 4938 // OpenMP 5.0, [2.1.5 Array Sections] 4939 // When the size of the array dimension is not known, the length must be 4940 // specified explicitly. 4941 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 4942 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4943 return ExprError(); 4944 } 4945 4946 if (Stride) { 4947 Expr::EvalResult Result; 4948 if (Stride->EvaluateAsInt(Result, Context)) { 4949 // OpenMP 5.0, [2.1.5 Array Sections] 4950 // The stride must evaluate to a positive integer. 4951 llvm::APSInt StrideValue = Result.Val.getInt(); 4952 if (!StrideValue.isStrictlyPositive()) { 4953 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 4954 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 4955 << Stride->getSourceRange(); 4956 return ExprError(); 4957 } 4958 } 4959 } 4960 4961 if (!Base->getType()->isSpecificPlaceholderType( 4962 BuiltinType::OMPArraySection)) { 4963 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4964 if (Result.isInvalid()) 4965 return ExprError(); 4966 Base = Result.get(); 4967 } 4968 return new (Context) OMPArraySectionExpr( 4969 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 4970 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4971 } 4972 4973 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4974 SourceLocation RParenLoc, 4975 ArrayRef<Expr *> Dims, 4976 ArrayRef<SourceRange> Brackets) { 4977 if (Base->getType()->isPlaceholderType()) { 4978 ExprResult Result = CheckPlaceholderExpr(Base); 4979 if (Result.isInvalid()) 4980 return ExprError(); 4981 Result = DefaultLvalueConversion(Result.get()); 4982 if (Result.isInvalid()) 4983 return ExprError(); 4984 Base = Result.get(); 4985 } 4986 QualType BaseTy = Base->getType(); 4987 // Delay analysis of the types/expressions if instantiation/specialization is 4988 // required. 4989 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 4990 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 4991 LParenLoc, RParenLoc, Dims, Brackets); 4992 if (!BaseTy->isPointerType() || 4993 (!Base->isTypeDependent() && 4994 BaseTy->getPointeeType()->isIncompleteType())) 4995 return ExprError(Diag(Base->getExprLoc(), 4996 diag::err_omp_non_pointer_type_array_shaping_base) 4997 << Base->getSourceRange()); 4998 4999 SmallVector<Expr *, 4> NewDims; 5000 bool ErrorFound = false; 5001 for (Expr *Dim : Dims) { 5002 if (Dim->getType()->isPlaceholderType()) { 5003 ExprResult Result = CheckPlaceholderExpr(Dim); 5004 if (Result.isInvalid()) { 5005 ErrorFound = true; 5006 continue; 5007 } 5008 Result = DefaultLvalueConversion(Result.get()); 5009 if (Result.isInvalid()) { 5010 ErrorFound = true; 5011 continue; 5012 } 5013 Dim = Result.get(); 5014 } 5015 if (!Dim->isTypeDependent()) { 5016 ExprResult Result = 5017 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5018 if (Result.isInvalid()) { 5019 ErrorFound = true; 5020 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5021 << Dim->getSourceRange(); 5022 continue; 5023 } 5024 Dim = Result.get(); 5025 Expr::EvalResult EvResult; 5026 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5027 // OpenMP 5.0, [2.1.4 Array Shaping] 5028 // Each si is an integral type expression that must evaluate to a 5029 // positive integer. 5030 llvm::APSInt Value = EvResult.Val.getInt(); 5031 if (!Value.isStrictlyPositive()) { 5032 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5033 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5034 << Dim->getSourceRange(); 5035 ErrorFound = true; 5036 continue; 5037 } 5038 } 5039 } 5040 NewDims.push_back(Dim); 5041 } 5042 if (ErrorFound) 5043 return ExprError(); 5044 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5045 LParenLoc, RParenLoc, NewDims, Brackets); 5046 } 5047 5048 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5049 SourceLocation LLoc, SourceLocation RLoc, 5050 ArrayRef<OMPIteratorData> Data) { 5051 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5052 bool IsCorrect = true; 5053 for (const OMPIteratorData &D : Data) { 5054 TypeSourceInfo *TInfo = nullptr; 5055 SourceLocation StartLoc; 5056 QualType DeclTy; 5057 if (!D.Type.getAsOpaquePtr()) { 5058 // OpenMP 5.0, 2.1.6 Iterators 5059 // In an iterator-specifier, if the iterator-type is not specified then 5060 // the type of that iterator is of int type. 5061 DeclTy = Context.IntTy; 5062 StartLoc = D.DeclIdentLoc; 5063 } else { 5064 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5065 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5066 } 5067 5068 bool IsDeclTyDependent = DeclTy->isDependentType() || 5069 DeclTy->containsUnexpandedParameterPack() || 5070 DeclTy->isInstantiationDependentType(); 5071 if (!IsDeclTyDependent) { 5072 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5073 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5074 // The iterator-type must be an integral or pointer type. 5075 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5076 << DeclTy; 5077 IsCorrect = false; 5078 continue; 5079 } 5080 if (DeclTy.isConstant(Context)) { 5081 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5082 // The iterator-type must not be const qualified. 5083 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5084 << DeclTy; 5085 IsCorrect = false; 5086 continue; 5087 } 5088 } 5089 5090 // Iterator declaration. 5091 assert(D.DeclIdent && "Identifier expected."); 5092 // Always try to create iterator declarator to avoid extra error messages 5093 // about unknown declarations use. 5094 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5095 D.DeclIdent, DeclTy, TInfo, SC_None); 5096 VD->setImplicit(); 5097 if (S) { 5098 // Check for conflicting previous declaration. 5099 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5100 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5101 ForVisibleRedeclaration); 5102 Previous.suppressDiagnostics(); 5103 LookupName(Previous, S); 5104 5105 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5106 /*AllowInlineNamespace=*/false); 5107 if (!Previous.empty()) { 5108 NamedDecl *Old = Previous.getRepresentativeDecl(); 5109 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5110 Diag(Old->getLocation(), diag::note_previous_definition); 5111 } else { 5112 PushOnScopeChains(VD, S); 5113 } 5114 } else { 5115 CurContext->addDecl(VD); 5116 } 5117 Expr *Begin = D.Range.Begin; 5118 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5119 ExprResult BeginRes = 5120 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5121 Begin = BeginRes.get(); 5122 } 5123 Expr *End = D.Range.End; 5124 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5125 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5126 End = EndRes.get(); 5127 } 5128 Expr *Step = D.Range.Step; 5129 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5130 if (!Step->getType()->isIntegralType(Context)) { 5131 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5132 << Step << Step->getSourceRange(); 5133 IsCorrect = false; 5134 continue; 5135 } 5136 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5137 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5138 // If the step expression of a range-specification equals zero, the 5139 // behavior is unspecified. 5140 if (Result && Result->isNullValue()) { 5141 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5142 << Step << Step->getSourceRange(); 5143 IsCorrect = false; 5144 continue; 5145 } 5146 } 5147 if (!Begin || !End || !IsCorrect) { 5148 IsCorrect = false; 5149 continue; 5150 } 5151 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5152 IDElem.IteratorDecl = VD; 5153 IDElem.AssignmentLoc = D.AssignLoc; 5154 IDElem.Range.Begin = Begin; 5155 IDElem.Range.End = End; 5156 IDElem.Range.Step = Step; 5157 IDElem.ColonLoc = D.ColonLoc; 5158 IDElem.SecondColonLoc = D.SecColonLoc; 5159 } 5160 if (!IsCorrect) { 5161 // Invalidate all created iterator declarations if error is found. 5162 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5163 if (Decl *ID = D.IteratorDecl) 5164 ID->setInvalidDecl(); 5165 } 5166 return ExprError(); 5167 } 5168 SmallVector<OMPIteratorHelperData, 4> Helpers; 5169 if (!CurContext->isDependentContext()) { 5170 // Build number of ityeration for each iteration range. 5171 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5172 // ((Begini-Stepi-1-Endi) / -Stepi); 5173 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5174 // (Endi - Begini) 5175 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5176 D.Range.Begin); 5177 if(!Res.isUsable()) { 5178 IsCorrect = false; 5179 continue; 5180 } 5181 ExprResult St, St1; 5182 if (D.Range.Step) { 5183 St = D.Range.Step; 5184 // (Endi - Begini) + Stepi 5185 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5186 if (!Res.isUsable()) { 5187 IsCorrect = false; 5188 continue; 5189 } 5190 // (Endi - Begini) + Stepi - 1 5191 Res = 5192 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5193 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5194 if (!Res.isUsable()) { 5195 IsCorrect = false; 5196 continue; 5197 } 5198 // ((Endi - Begini) + Stepi - 1) / Stepi 5199 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5200 if (!Res.isUsable()) { 5201 IsCorrect = false; 5202 continue; 5203 } 5204 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5205 // (Begini - Endi) 5206 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5207 D.Range.Begin, D.Range.End); 5208 if (!Res1.isUsable()) { 5209 IsCorrect = false; 5210 continue; 5211 } 5212 // (Begini - Endi) - Stepi 5213 Res1 = 5214 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5215 if (!Res1.isUsable()) { 5216 IsCorrect = false; 5217 continue; 5218 } 5219 // (Begini - Endi) - Stepi - 1 5220 Res1 = 5221 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5222 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5223 if (!Res1.isUsable()) { 5224 IsCorrect = false; 5225 continue; 5226 } 5227 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5228 Res1 = 5229 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5230 if (!Res1.isUsable()) { 5231 IsCorrect = false; 5232 continue; 5233 } 5234 // Stepi > 0. 5235 ExprResult CmpRes = 5236 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5237 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5238 if (!CmpRes.isUsable()) { 5239 IsCorrect = false; 5240 continue; 5241 } 5242 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5243 Res.get(), Res1.get()); 5244 if (!Res.isUsable()) { 5245 IsCorrect = false; 5246 continue; 5247 } 5248 } 5249 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5250 if (!Res.isUsable()) { 5251 IsCorrect = false; 5252 continue; 5253 } 5254 5255 // Build counter update. 5256 // Build counter. 5257 auto *CounterVD = 5258 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5259 D.IteratorDecl->getBeginLoc(), nullptr, 5260 Res.get()->getType(), nullptr, SC_None); 5261 CounterVD->setImplicit(); 5262 ExprResult RefRes = 5263 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5264 D.IteratorDecl->getBeginLoc()); 5265 // Build counter update. 5266 // I = Begini + counter * Stepi; 5267 ExprResult UpdateRes; 5268 if (D.Range.Step) { 5269 UpdateRes = CreateBuiltinBinOp( 5270 D.AssignmentLoc, BO_Mul, 5271 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5272 } else { 5273 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5274 } 5275 if (!UpdateRes.isUsable()) { 5276 IsCorrect = false; 5277 continue; 5278 } 5279 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5280 UpdateRes.get()); 5281 if (!UpdateRes.isUsable()) { 5282 IsCorrect = false; 5283 continue; 5284 } 5285 ExprResult VDRes = 5286 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5287 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5288 D.IteratorDecl->getBeginLoc()); 5289 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5290 UpdateRes.get()); 5291 if (!UpdateRes.isUsable()) { 5292 IsCorrect = false; 5293 continue; 5294 } 5295 UpdateRes = 5296 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5297 if (!UpdateRes.isUsable()) { 5298 IsCorrect = false; 5299 continue; 5300 } 5301 ExprResult CounterUpdateRes = 5302 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5303 if (!CounterUpdateRes.isUsable()) { 5304 IsCorrect = false; 5305 continue; 5306 } 5307 CounterUpdateRes = 5308 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5309 if (!CounterUpdateRes.isUsable()) { 5310 IsCorrect = false; 5311 continue; 5312 } 5313 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5314 HD.CounterVD = CounterVD; 5315 HD.Upper = Res.get(); 5316 HD.Update = UpdateRes.get(); 5317 HD.CounterUpdate = CounterUpdateRes.get(); 5318 } 5319 } else { 5320 Helpers.assign(ID.size(), {}); 5321 } 5322 if (!IsCorrect) { 5323 // Invalidate all created iterator declarations if error is found. 5324 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5325 if (Decl *ID = D.IteratorDecl) 5326 ID->setInvalidDecl(); 5327 } 5328 return ExprError(); 5329 } 5330 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5331 LLoc, RLoc, ID, Helpers); 5332 } 5333 5334 ExprResult 5335 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5336 Expr *Idx, SourceLocation RLoc) { 5337 Expr *LHSExp = Base; 5338 Expr *RHSExp = Idx; 5339 5340 ExprValueKind VK = VK_LValue; 5341 ExprObjectKind OK = OK_Ordinary; 5342 5343 // Per C++ core issue 1213, the result is an xvalue if either operand is 5344 // a non-lvalue array, and an lvalue otherwise. 5345 if (getLangOpts().CPlusPlus11) { 5346 for (auto *Op : {LHSExp, RHSExp}) { 5347 Op = Op->IgnoreImplicit(); 5348 if (Op->getType()->isArrayType() && !Op->isLValue()) 5349 VK = VK_XValue; 5350 } 5351 } 5352 5353 // Perform default conversions. 5354 if (!LHSExp->getType()->getAs<VectorType>()) { 5355 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5356 if (Result.isInvalid()) 5357 return ExprError(); 5358 LHSExp = Result.get(); 5359 } 5360 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5361 if (Result.isInvalid()) 5362 return ExprError(); 5363 RHSExp = Result.get(); 5364 5365 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5366 5367 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5368 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5369 // in the subscript position. As a result, we need to derive the array base 5370 // and index from the expression types. 5371 Expr *BaseExpr, *IndexExpr; 5372 QualType ResultType; 5373 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5374 BaseExpr = LHSExp; 5375 IndexExpr = RHSExp; 5376 ResultType = Context.DependentTy; 5377 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5378 BaseExpr = LHSExp; 5379 IndexExpr = RHSExp; 5380 ResultType = PTy->getPointeeType(); 5381 } else if (const ObjCObjectPointerType *PTy = 5382 LHSTy->getAs<ObjCObjectPointerType>()) { 5383 BaseExpr = LHSExp; 5384 IndexExpr = RHSExp; 5385 5386 // Use custom logic if this should be the pseudo-object subscript 5387 // expression. 5388 if (!LangOpts.isSubscriptPointerArithmetic()) 5389 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5390 nullptr); 5391 5392 ResultType = PTy->getPointeeType(); 5393 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5394 // Handle the uncommon case of "123[Ptr]". 5395 BaseExpr = RHSExp; 5396 IndexExpr = LHSExp; 5397 ResultType = PTy->getPointeeType(); 5398 } else if (const ObjCObjectPointerType *PTy = 5399 RHSTy->getAs<ObjCObjectPointerType>()) { 5400 // Handle the uncommon case of "123[Ptr]". 5401 BaseExpr = RHSExp; 5402 IndexExpr = LHSExp; 5403 ResultType = PTy->getPointeeType(); 5404 if (!LangOpts.isSubscriptPointerArithmetic()) { 5405 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5406 << ResultType << BaseExpr->getSourceRange(); 5407 return ExprError(); 5408 } 5409 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5410 BaseExpr = LHSExp; // vectors: V[123] 5411 IndexExpr = RHSExp; 5412 // We apply C++ DR1213 to vector subscripting too. 5413 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5414 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5415 if (Materialized.isInvalid()) 5416 return ExprError(); 5417 LHSExp = Materialized.get(); 5418 } 5419 VK = LHSExp->getValueKind(); 5420 if (VK != VK_RValue) 5421 OK = OK_VectorComponent; 5422 5423 ResultType = VTy->getElementType(); 5424 QualType BaseType = BaseExpr->getType(); 5425 Qualifiers BaseQuals = BaseType.getQualifiers(); 5426 Qualifiers MemberQuals = ResultType.getQualifiers(); 5427 Qualifiers Combined = BaseQuals + MemberQuals; 5428 if (Combined != MemberQuals) 5429 ResultType = Context.getQualifiedType(ResultType, Combined); 5430 } else if (LHSTy->isArrayType()) { 5431 // If we see an array that wasn't promoted by 5432 // DefaultFunctionArrayLvalueConversion, it must be an array that 5433 // wasn't promoted because of the C90 rule that doesn't 5434 // allow promoting non-lvalue arrays. Warn, then 5435 // force the promotion here. 5436 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5437 << LHSExp->getSourceRange(); 5438 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5439 CK_ArrayToPointerDecay).get(); 5440 LHSTy = LHSExp->getType(); 5441 5442 BaseExpr = LHSExp; 5443 IndexExpr = RHSExp; 5444 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5445 } else if (RHSTy->isArrayType()) { 5446 // Same as previous, except for 123[f().a] case 5447 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5448 << RHSExp->getSourceRange(); 5449 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5450 CK_ArrayToPointerDecay).get(); 5451 RHSTy = RHSExp->getType(); 5452 5453 BaseExpr = RHSExp; 5454 IndexExpr = LHSExp; 5455 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5456 } else { 5457 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5458 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5459 } 5460 // C99 6.5.2.1p1 5461 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5462 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5463 << IndexExpr->getSourceRange()); 5464 5465 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5466 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5467 && !IndexExpr->isTypeDependent()) 5468 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5469 5470 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5471 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5472 // type. Note that Functions are not objects, and that (in C99 parlance) 5473 // incomplete types are not object types. 5474 if (ResultType->isFunctionType()) { 5475 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5476 << ResultType << BaseExpr->getSourceRange(); 5477 return ExprError(); 5478 } 5479 5480 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5481 // GNU extension: subscripting on pointer to void 5482 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5483 << BaseExpr->getSourceRange(); 5484 5485 // C forbids expressions of unqualified void type from being l-values. 5486 // See IsCForbiddenLValueType. 5487 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5488 } else if (!ResultType->isDependentType() && 5489 RequireCompleteSizedType( 5490 LLoc, ResultType, 5491 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5492 return ExprError(); 5493 5494 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5495 !ResultType.isCForbiddenLValueType()); 5496 5497 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5498 FunctionScopes.size() > 1) { 5499 if (auto *TT = 5500 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5501 for (auto I = FunctionScopes.rbegin(), 5502 E = std::prev(FunctionScopes.rend()); 5503 I != E; ++I) { 5504 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5505 if (CSI == nullptr) 5506 break; 5507 DeclContext *DC = nullptr; 5508 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5509 DC = LSI->CallOperator; 5510 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5511 DC = CRSI->TheCapturedDecl; 5512 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5513 DC = BSI->TheDecl; 5514 if (DC) { 5515 if (DC->containsDecl(TT->getDecl())) 5516 break; 5517 captureVariablyModifiedType( 5518 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5519 } 5520 } 5521 } 5522 } 5523 5524 return new (Context) 5525 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5526 } 5527 5528 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5529 ParmVarDecl *Param) { 5530 if (Param->hasUnparsedDefaultArg()) { 5531 // If we've already cleared out the location for the default argument, 5532 // that means we're parsing it right now. 5533 if (!UnparsedDefaultArgLocs.count(Param)) { 5534 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5535 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5536 Param->setInvalidDecl(); 5537 return true; 5538 } 5539 5540 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5541 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5542 Diag(UnparsedDefaultArgLocs[Param], 5543 diag::note_default_argument_declared_here); 5544 return true; 5545 } 5546 5547 if (Param->hasUninstantiatedDefaultArg() && 5548 InstantiateDefaultArgument(CallLoc, FD, Param)) 5549 return true; 5550 5551 assert(Param->hasInit() && "default argument but no initializer?"); 5552 5553 // If the default expression creates temporaries, we need to 5554 // push them to the current stack of expression temporaries so they'll 5555 // be properly destroyed. 5556 // FIXME: We should really be rebuilding the default argument with new 5557 // bound temporaries; see the comment in PR5810. 5558 // We don't need to do that with block decls, though, because 5559 // blocks in default argument expression can never capture anything. 5560 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5561 // Set the "needs cleanups" bit regardless of whether there are 5562 // any explicit objects. 5563 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5564 5565 // Append all the objects to the cleanup list. Right now, this 5566 // should always be a no-op, because blocks in default argument 5567 // expressions should never be able to capture anything. 5568 assert(!Init->getNumObjects() && 5569 "default argument expression has capturing blocks?"); 5570 } 5571 5572 // We already type-checked the argument, so we know it works. 5573 // Just mark all of the declarations in this potentially-evaluated expression 5574 // as being "referenced". 5575 EnterExpressionEvaluationContext EvalContext( 5576 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5577 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5578 /*SkipLocalVariables=*/true); 5579 return false; 5580 } 5581 5582 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5583 FunctionDecl *FD, ParmVarDecl *Param) { 5584 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5585 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5586 return ExprError(); 5587 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5588 } 5589 5590 Sema::VariadicCallType 5591 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5592 Expr *Fn) { 5593 if (Proto && Proto->isVariadic()) { 5594 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5595 return VariadicConstructor; 5596 else if (Fn && Fn->getType()->isBlockPointerType()) 5597 return VariadicBlock; 5598 else if (FDecl) { 5599 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5600 if (Method->isInstance()) 5601 return VariadicMethod; 5602 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5603 return VariadicMethod; 5604 return VariadicFunction; 5605 } 5606 return VariadicDoesNotApply; 5607 } 5608 5609 namespace { 5610 class FunctionCallCCC final : public FunctionCallFilterCCC { 5611 public: 5612 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5613 unsigned NumArgs, MemberExpr *ME) 5614 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5615 FunctionName(FuncName) {} 5616 5617 bool ValidateCandidate(const TypoCorrection &candidate) override { 5618 if (!candidate.getCorrectionSpecifier() || 5619 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5620 return false; 5621 } 5622 5623 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5624 } 5625 5626 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5627 return std::make_unique<FunctionCallCCC>(*this); 5628 } 5629 5630 private: 5631 const IdentifierInfo *const FunctionName; 5632 }; 5633 } 5634 5635 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5636 FunctionDecl *FDecl, 5637 ArrayRef<Expr *> Args) { 5638 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5639 DeclarationName FuncName = FDecl->getDeclName(); 5640 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5641 5642 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5643 if (TypoCorrection Corrected = S.CorrectTypo( 5644 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5645 S.getScopeForContext(S.CurContext), nullptr, CCC, 5646 Sema::CTK_ErrorRecovery)) { 5647 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5648 if (Corrected.isOverloaded()) { 5649 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5650 OverloadCandidateSet::iterator Best; 5651 for (NamedDecl *CD : Corrected) { 5652 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5653 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5654 OCS); 5655 } 5656 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5657 case OR_Success: 5658 ND = Best->FoundDecl; 5659 Corrected.setCorrectionDecl(ND); 5660 break; 5661 default: 5662 break; 5663 } 5664 } 5665 ND = ND->getUnderlyingDecl(); 5666 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5667 return Corrected; 5668 } 5669 } 5670 return TypoCorrection(); 5671 } 5672 5673 /// ConvertArgumentsForCall - Converts the arguments specified in 5674 /// Args/NumArgs to the parameter types of the function FDecl with 5675 /// function prototype Proto. Call is the call expression itself, and 5676 /// Fn is the function expression. For a C++ member function, this 5677 /// routine does not attempt to convert the object argument. Returns 5678 /// true if the call is ill-formed. 5679 bool 5680 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5681 FunctionDecl *FDecl, 5682 const FunctionProtoType *Proto, 5683 ArrayRef<Expr *> Args, 5684 SourceLocation RParenLoc, 5685 bool IsExecConfig) { 5686 // Bail out early if calling a builtin with custom typechecking. 5687 if (FDecl) 5688 if (unsigned ID = FDecl->getBuiltinID()) 5689 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5690 return false; 5691 5692 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5693 // assignment, to the types of the corresponding parameter, ... 5694 unsigned NumParams = Proto->getNumParams(); 5695 bool Invalid = false; 5696 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5697 unsigned FnKind = Fn->getType()->isBlockPointerType() 5698 ? 1 /* block */ 5699 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5700 : 0 /* function */); 5701 5702 // If too few arguments are available (and we don't have default 5703 // arguments for the remaining parameters), don't make the call. 5704 if (Args.size() < NumParams) { 5705 if (Args.size() < MinArgs) { 5706 TypoCorrection TC; 5707 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5708 unsigned diag_id = 5709 MinArgs == NumParams && !Proto->isVariadic() 5710 ? diag::err_typecheck_call_too_few_args_suggest 5711 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5712 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5713 << static_cast<unsigned>(Args.size()) 5714 << TC.getCorrectionRange()); 5715 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5716 Diag(RParenLoc, 5717 MinArgs == NumParams && !Proto->isVariadic() 5718 ? diag::err_typecheck_call_too_few_args_one 5719 : diag::err_typecheck_call_too_few_args_at_least_one) 5720 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5721 else 5722 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5723 ? diag::err_typecheck_call_too_few_args 5724 : diag::err_typecheck_call_too_few_args_at_least) 5725 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5726 << Fn->getSourceRange(); 5727 5728 // Emit the location of the prototype. 5729 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5730 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5731 5732 return true; 5733 } 5734 // We reserve space for the default arguments when we create 5735 // the call expression, before calling ConvertArgumentsForCall. 5736 assert((Call->getNumArgs() == NumParams) && 5737 "We should have reserved space for the default arguments before!"); 5738 } 5739 5740 // If too many are passed and not variadic, error on the extras and drop 5741 // them. 5742 if (Args.size() > NumParams) { 5743 if (!Proto->isVariadic()) { 5744 TypoCorrection TC; 5745 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5746 unsigned diag_id = 5747 MinArgs == NumParams && !Proto->isVariadic() 5748 ? diag::err_typecheck_call_too_many_args_suggest 5749 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5750 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5751 << static_cast<unsigned>(Args.size()) 5752 << TC.getCorrectionRange()); 5753 } else if (NumParams == 1 && FDecl && 5754 FDecl->getParamDecl(0)->getDeclName()) 5755 Diag(Args[NumParams]->getBeginLoc(), 5756 MinArgs == NumParams 5757 ? diag::err_typecheck_call_too_many_args_one 5758 : diag::err_typecheck_call_too_many_args_at_most_one) 5759 << FnKind << FDecl->getParamDecl(0) 5760 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5761 << SourceRange(Args[NumParams]->getBeginLoc(), 5762 Args.back()->getEndLoc()); 5763 else 5764 Diag(Args[NumParams]->getBeginLoc(), 5765 MinArgs == NumParams 5766 ? diag::err_typecheck_call_too_many_args 5767 : diag::err_typecheck_call_too_many_args_at_most) 5768 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5769 << Fn->getSourceRange() 5770 << SourceRange(Args[NumParams]->getBeginLoc(), 5771 Args.back()->getEndLoc()); 5772 5773 // Emit the location of the prototype. 5774 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5775 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5776 5777 // This deletes the extra arguments. 5778 Call->shrinkNumArgs(NumParams); 5779 return true; 5780 } 5781 } 5782 SmallVector<Expr *, 8> AllArgs; 5783 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5784 5785 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5786 AllArgs, CallType); 5787 if (Invalid) 5788 return true; 5789 unsigned TotalNumArgs = AllArgs.size(); 5790 for (unsigned i = 0; i < TotalNumArgs; ++i) 5791 Call->setArg(i, AllArgs[i]); 5792 5793 return false; 5794 } 5795 5796 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5797 const FunctionProtoType *Proto, 5798 unsigned FirstParam, ArrayRef<Expr *> Args, 5799 SmallVectorImpl<Expr *> &AllArgs, 5800 VariadicCallType CallType, bool AllowExplicit, 5801 bool IsListInitialization) { 5802 unsigned NumParams = Proto->getNumParams(); 5803 bool Invalid = false; 5804 size_t ArgIx = 0; 5805 // Continue to check argument types (even if we have too few/many args). 5806 for (unsigned i = FirstParam; i < NumParams; i++) { 5807 QualType ProtoArgType = Proto->getParamType(i); 5808 5809 Expr *Arg; 5810 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5811 if (ArgIx < Args.size()) { 5812 Arg = Args[ArgIx++]; 5813 5814 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5815 diag::err_call_incomplete_argument, Arg)) 5816 return true; 5817 5818 // Strip the unbridged-cast placeholder expression off, if applicable. 5819 bool CFAudited = false; 5820 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5821 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5822 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5823 Arg = stripARCUnbridgedCast(Arg); 5824 else if (getLangOpts().ObjCAutoRefCount && 5825 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5826 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5827 CFAudited = true; 5828 5829 if (Proto->getExtParameterInfo(i).isNoEscape()) 5830 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5831 BE->getBlockDecl()->setDoesNotEscape(); 5832 5833 InitializedEntity Entity = 5834 Param ? InitializedEntity::InitializeParameter(Context, Param, 5835 ProtoArgType) 5836 : InitializedEntity::InitializeParameter( 5837 Context, ProtoArgType, Proto->isParamConsumed(i)); 5838 5839 // Remember that parameter belongs to a CF audited API. 5840 if (CFAudited) 5841 Entity.setParameterCFAudited(); 5842 5843 ExprResult ArgE = PerformCopyInitialization( 5844 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5845 if (ArgE.isInvalid()) 5846 return true; 5847 5848 Arg = ArgE.getAs<Expr>(); 5849 } else { 5850 assert(Param && "can't use default arguments without a known callee"); 5851 5852 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5853 if (ArgExpr.isInvalid()) 5854 return true; 5855 5856 Arg = ArgExpr.getAs<Expr>(); 5857 } 5858 5859 // Check for array bounds violations for each argument to the call. This 5860 // check only triggers warnings when the argument isn't a more complex Expr 5861 // with its own checking, such as a BinaryOperator. 5862 CheckArrayAccess(Arg); 5863 5864 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5865 CheckStaticArrayArgument(CallLoc, Param, Arg); 5866 5867 AllArgs.push_back(Arg); 5868 } 5869 5870 // If this is a variadic call, handle args passed through "...". 5871 if (CallType != VariadicDoesNotApply) { 5872 // Assume that extern "C" functions with variadic arguments that 5873 // return __unknown_anytype aren't *really* variadic. 5874 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5875 FDecl->isExternC()) { 5876 for (Expr *A : Args.slice(ArgIx)) { 5877 QualType paramType; // ignored 5878 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5879 Invalid |= arg.isInvalid(); 5880 AllArgs.push_back(arg.get()); 5881 } 5882 5883 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5884 } else { 5885 for (Expr *A : Args.slice(ArgIx)) { 5886 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5887 Invalid |= Arg.isInvalid(); 5888 AllArgs.push_back(Arg.get()); 5889 } 5890 } 5891 5892 // Check for array bounds violations. 5893 for (Expr *A : Args.slice(ArgIx)) 5894 CheckArrayAccess(A); 5895 } 5896 return Invalid; 5897 } 5898 5899 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5900 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5901 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5902 TL = DTL.getOriginalLoc(); 5903 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5904 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5905 << ATL.getLocalSourceRange(); 5906 } 5907 5908 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5909 /// array parameter, check that it is non-null, and that if it is formed by 5910 /// array-to-pointer decay, the underlying array is sufficiently large. 5911 /// 5912 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5913 /// array type derivation, then for each call to the function, the value of the 5914 /// corresponding actual argument shall provide access to the first element of 5915 /// an array with at least as many elements as specified by the size expression. 5916 void 5917 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5918 ParmVarDecl *Param, 5919 const Expr *ArgExpr) { 5920 // Static array parameters are not supported in C++. 5921 if (!Param || getLangOpts().CPlusPlus) 5922 return; 5923 5924 QualType OrigTy = Param->getOriginalType(); 5925 5926 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5927 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5928 return; 5929 5930 if (ArgExpr->isNullPointerConstant(Context, 5931 Expr::NPC_NeverValueDependent)) { 5932 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5933 DiagnoseCalleeStaticArrayParam(*this, Param); 5934 return; 5935 } 5936 5937 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5938 if (!CAT) 5939 return; 5940 5941 const ConstantArrayType *ArgCAT = 5942 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5943 if (!ArgCAT) 5944 return; 5945 5946 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5947 ArgCAT->getElementType())) { 5948 if (ArgCAT->getSize().ult(CAT->getSize())) { 5949 Diag(CallLoc, diag::warn_static_array_too_small) 5950 << ArgExpr->getSourceRange() 5951 << (unsigned)ArgCAT->getSize().getZExtValue() 5952 << (unsigned)CAT->getSize().getZExtValue() << 0; 5953 DiagnoseCalleeStaticArrayParam(*this, Param); 5954 } 5955 return; 5956 } 5957 5958 Optional<CharUnits> ArgSize = 5959 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5960 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5961 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5962 Diag(CallLoc, diag::warn_static_array_too_small) 5963 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5964 << (unsigned)ParmSize->getQuantity() << 1; 5965 DiagnoseCalleeStaticArrayParam(*this, Param); 5966 } 5967 } 5968 5969 /// Given a function expression of unknown-any type, try to rebuild it 5970 /// to have a function type. 5971 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5972 5973 /// Is the given type a placeholder that we need to lower out 5974 /// immediately during argument processing? 5975 static bool isPlaceholderToRemoveAsArg(QualType type) { 5976 // Placeholders are never sugared. 5977 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5978 if (!placeholder) return false; 5979 5980 switch (placeholder->getKind()) { 5981 // Ignore all the non-placeholder types. 5982 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5983 case BuiltinType::Id: 5984 #include "clang/Basic/OpenCLImageTypes.def" 5985 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5986 case BuiltinType::Id: 5987 #include "clang/Basic/OpenCLExtensionTypes.def" 5988 // In practice we'll never use this, since all SVE types are sugared 5989 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5990 #define SVE_TYPE(Name, Id, SingletonId) \ 5991 case BuiltinType::Id: 5992 #include "clang/Basic/AArch64SVEACLETypes.def" 5993 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5994 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5995 #include "clang/AST/BuiltinTypes.def" 5996 return false; 5997 5998 // We cannot lower out overload sets; they might validly be resolved 5999 // by the call machinery. 6000 case BuiltinType::Overload: 6001 return false; 6002 6003 // Unbridged casts in ARC can be handled in some call positions and 6004 // should be left in place. 6005 case BuiltinType::ARCUnbridgedCast: 6006 return false; 6007 6008 // Pseudo-objects should be converted as soon as possible. 6009 case BuiltinType::PseudoObject: 6010 return true; 6011 6012 // The debugger mode could theoretically but currently does not try 6013 // to resolve unknown-typed arguments based on known parameter types. 6014 case BuiltinType::UnknownAny: 6015 return true; 6016 6017 // These are always invalid as call arguments and should be reported. 6018 case BuiltinType::BoundMember: 6019 case BuiltinType::BuiltinFn: 6020 case BuiltinType::IncompleteMatrixIdx: 6021 case BuiltinType::OMPArraySection: 6022 case BuiltinType::OMPArrayShaping: 6023 case BuiltinType::OMPIterator: 6024 return true; 6025 6026 } 6027 llvm_unreachable("bad builtin type kind"); 6028 } 6029 6030 /// Check an argument list for placeholders that we won't try to 6031 /// handle later. 6032 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6033 // Apply this processing to all the arguments at once instead of 6034 // dying at the first failure. 6035 bool hasInvalid = false; 6036 for (size_t i = 0, e = args.size(); i != e; i++) { 6037 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6038 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6039 if (result.isInvalid()) hasInvalid = true; 6040 else args[i] = result.get(); 6041 } 6042 } 6043 return hasInvalid; 6044 } 6045 6046 /// If a builtin function has a pointer argument with no explicit address 6047 /// space, then it should be able to accept a pointer to any address 6048 /// space as input. In order to do this, we need to replace the 6049 /// standard builtin declaration with one that uses the same address space 6050 /// as the call. 6051 /// 6052 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6053 /// it does not contain any pointer arguments without 6054 /// an address space qualifer. Otherwise the rewritten 6055 /// FunctionDecl is returned. 6056 /// TODO: Handle pointer return types. 6057 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6058 FunctionDecl *FDecl, 6059 MultiExprArg ArgExprs) { 6060 6061 QualType DeclType = FDecl->getType(); 6062 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6063 6064 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6065 ArgExprs.size() < FT->getNumParams()) 6066 return nullptr; 6067 6068 bool NeedsNewDecl = false; 6069 unsigned i = 0; 6070 SmallVector<QualType, 8> OverloadParams; 6071 6072 for (QualType ParamType : FT->param_types()) { 6073 6074 // Convert array arguments to pointer to simplify type lookup. 6075 ExprResult ArgRes = 6076 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6077 if (ArgRes.isInvalid()) 6078 return nullptr; 6079 Expr *Arg = ArgRes.get(); 6080 QualType ArgType = Arg->getType(); 6081 if (!ParamType->isPointerType() || 6082 ParamType.hasAddressSpace() || 6083 !ArgType->isPointerType() || 6084 !ArgType->getPointeeType().hasAddressSpace()) { 6085 OverloadParams.push_back(ParamType); 6086 continue; 6087 } 6088 6089 QualType PointeeType = ParamType->getPointeeType(); 6090 if (PointeeType.hasAddressSpace()) 6091 continue; 6092 6093 NeedsNewDecl = true; 6094 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6095 6096 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6097 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6098 } 6099 6100 if (!NeedsNewDecl) 6101 return nullptr; 6102 6103 FunctionProtoType::ExtProtoInfo EPI; 6104 EPI.Variadic = FT->isVariadic(); 6105 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6106 OverloadParams, EPI); 6107 DeclContext *Parent = FDecl->getParent(); 6108 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6109 FDecl->getLocation(), 6110 FDecl->getLocation(), 6111 FDecl->getIdentifier(), 6112 OverloadTy, 6113 /*TInfo=*/nullptr, 6114 SC_Extern, false, 6115 /*hasPrototype=*/true); 6116 SmallVector<ParmVarDecl*, 16> Params; 6117 FT = cast<FunctionProtoType>(OverloadTy); 6118 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6119 QualType ParamType = FT->getParamType(i); 6120 ParmVarDecl *Parm = 6121 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6122 SourceLocation(), nullptr, ParamType, 6123 /*TInfo=*/nullptr, SC_None, nullptr); 6124 Parm->setScopeInfo(0, i); 6125 Params.push_back(Parm); 6126 } 6127 OverloadDecl->setParams(Params); 6128 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6129 return OverloadDecl; 6130 } 6131 6132 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6133 FunctionDecl *Callee, 6134 MultiExprArg ArgExprs) { 6135 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6136 // similar attributes) really don't like it when functions are called with an 6137 // invalid number of args. 6138 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6139 /*PartialOverloading=*/false) && 6140 !Callee->isVariadic()) 6141 return; 6142 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6143 return; 6144 6145 if (const EnableIfAttr *Attr = 6146 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6147 S.Diag(Fn->getBeginLoc(), 6148 isa<CXXMethodDecl>(Callee) 6149 ? diag::err_ovl_no_viable_member_function_in_call 6150 : diag::err_ovl_no_viable_function_in_call) 6151 << Callee << Callee->getSourceRange(); 6152 S.Diag(Callee->getLocation(), 6153 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6154 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6155 return; 6156 } 6157 } 6158 6159 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6160 const UnresolvedMemberExpr *const UME, Sema &S) { 6161 6162 const auto GetFunctionLevelDCIfCXXClass = 6163 [](Sema &S) -> const CXXRecordDecl * { 6164 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6165 if (!DC || !DC->getParent()) 6166 return nullptr; 6167 6168 // If the call to some member function was made from within a member 6169 // function body 'M' return return 'M's parent. 6170 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6171 return MD->getParent()->getCanonicalDecl(); 6172 // else the call was made from within a default member initializer of a 6173 // class, so return the class. 6174 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6175 return RD->getCanonicalDecl(); 6176 return nullptr; 6177 }; 6178 // If our DeclContext is neither a member function nor a class (in the 6179 // case of a lambda in a default member initializer), we can't have an 6180 // enclosing 'this'. 6181 6182 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6183 if (!CurParentClass) 6184 return false; 6185 6186 // The naming class for implicit member functions call is the class in which 6187 // name lookup starts. 6188 const CXXRecordDecl *const NamingClass = 6189 UME->getNamingClass()->getCanonicalDecl(); 6190 assert(NamingClass && "Must have naming class even for implicit access"); 6191 6192 // If the unresolved member functions were found in a 'naming class' that is 6193 // related (either the same or derived from) to the class that contains the 6194 // member function that itself contained the implicit member access. 6195 6196 return CurParentClass == NamingClass || 6197 CurParentClass->isDerivedFrom(NamingClass); 6198 } 6199 6200 static void 6201 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6202 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6203 6204 if (!UME) 6205 return; 6206 6207 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6208 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6209 // already been captured, or if this is an implicit member function call (if 6210 // it isn't, an attempt to capture 'this' should already have been made). 6211 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6212 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6213 return; 6214 6215 // Check if the naming class in which the unresolved members were found is 6216 // related (same as or is a base of) to the enclosing class. 6217 6218 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6219 return; 6220 6221 6222 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6223 // If the enclosing function is not dependent, then this lambda is 6224 // capture ready, so if we can capture this, do so. 6225 if (!EnclosingFunctionCtx->isDependentContext()) { 6226 // If the current lambda and all enclosing lambdas can capture 'this' - 6227 // then go ahead and capture 'this' (since our unresolved overload set 6228 // contains at least one non-static member function). 6229 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6230 S.CheckCXXThisCapture(CallLoc); 6231 } else if (S.CurContext->isDependentContext()) { 6232 // ... since this is an implicit member reference, that might potentially 6233 // involve a 'this' capture, mark 'this' for potential capture in 6234 // enclosing lambdas. 6235 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6236 CurLSI->addPotentialThisCapture(CallLoc); 6237 } 6238 } 6239 6240 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6241 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6242 Expr *ExecConfig) { 6243 ExprResult Call = 6244 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6245 if (Call.isInvalid()) 6246 return Call; 6247 6248 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6249 // language modes. 6250 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6251 if (ULE->hasExplicitTemplateArgs() && 6252 ULE->decls_begin() == ULE->decls_end()) { 6253 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6254 ? diag::warn_cxx17_compat_adl_only_template_id 6255 : diag::ext_adl_only_template_id) 6256 << ULE->getName(); 6257 } 6258 } 6259 6260 if (LangOpts.OpenMP) 6261 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6262 ExecConfig); 6263 6264 return Call; 6265 } 6266 6267 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6268 /// This provides the location of the left/right parens and a list of comma 6269 /// locations. 6270 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6271 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6272 Expr *ExecConfig, bool IsExecConfig) { 6273 // Since this might be a postfix expression, get rid of ParenListExprs. 6274 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6275 if (Result.isInvalid()) return ExprError(); 6276 Fn = Result.get(); 6277 6278 if (checkArgsForPlaceholders(*this, ArgExprs)) 6279 return ExprError(); 6280 6281 if (getLangOpts().CPlusPlus) { 6282 // If this is a pseudo-destructor expression, build the call immediately. 6283 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6284 if (!ArgExprs.empty()) { 6285 // Pseudo-destructor calls should not have any arguments. 6286 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6287 << FixItHint::CreateRemoval( 6288 SourceRange(ArgExprs.front()->getBeginLoc(), 6289 ArgExprs.back()->getEndLoc())); 6290 } 6291 6292 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6293 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6294 } 6295 if (Fn->getType() == Context.PseudoObjectTy) { 6296 ExprResult result = CheckPlaceholderExpr(Fn); 6297 if (result.isInvalid()) return ExprError(); 6298 Fn = result.get(); 6299 } 6300 6301 // Determine whether this is a dependent call inside a C++ template, 6302 // in which case we won't do any semantic analysis now. 6303 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6304 if (ExecConfig) { 6305 return CUDAKernelCallExpr::Create( 6306 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6307 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6308 } else { 6309 6310 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6311 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6312 Fn->getBeginLoc()); 6313 6314 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6315 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6316 } 6317 } 6318 6319 // Determine whether this is a call to an object (C++ [over.call.object]). 6320 if (Fn->getType()->isRecordType()) 6321 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6322 RParenLoc); 6323 6324 if (Fn->getType() == Context.UnknownAnyTy) { 6325 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6326 if (result.isInvalid()) return ExprError(); 6327 Fn = result.get(); 6328 } 6329 6330 if (Fn->getType() == Context.BoundMemberTy) { 6331 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6332 RParenLoc); 6333 } 6334 } 6335 6336 // Check for overloaded calls. This can happen even in C due to extensions. 6337 if (Fn->getType() == Context.OverloadTy) { 6338 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6339 6340 // We aren't supposed to apply this logic if there's an '&' involved. 6341 if (!find.HasFormOfMemberPointer) { 6342 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6343 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6344 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6345 OverloadExpr *ovl = find.Expression; 6346 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6347 return BuildOverloadedCallExpr( 6348 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6349 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6350 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6351 RParenLoc); 6352 } 6353 } 6354 6355 // If we're directly calling a function, get the appropriate declaration. 6356 if (Fn->getType() == Context.UnknownAnyTy) { 6357 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6358 if (result.isInvalid()) return ExprError(); 6359 Fn = result.get(); 6360 } 6361 6362 Expr *NakedFn = Fn->IgnoreParens(); 6363 6364 bool CallingNDeclIndirectly = false; 6365 NamedDecl *NDecl = nullptr; 6366 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6367 if (UnOp->getOpcode() == UO_AddrOf) { 6368 CallingNDeclIndirectly = true; 6369 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6370 } 6371 } 6372 6373 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6374 NDecl = DRE->getDecl(); 6375 6376 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6377 if (FDecl && FDecl->getBuiltinID()) { 6378 // Rewrite the function decl for this builtin by replacing parameters 6379 // with no explicit address space with the address space of the arguments 6380 // in ArgExprs. 6381 if ((FDecl = 6382 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6383 NDecl = FDecl; 6384 Fn = DeclRefExpr::Create( 6385 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6386 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6387 nullptr, DRE->isNonOdrUse()); 6388 } 6389 } 6390 } else if (isa<MemberExpr>(NakedFn)) 6391 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6392 6393 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6394 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6395 FD, /*Complain=*/true, Fn->getBeginLoc())) 6396 return ExprError(); 6397 6398 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6399 return ExprError(); 6400 6401 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6402 } 6403 6404 if (Context.isDependenceAllowed() && 6405 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6406 assert(!getLangOpts().CPlusPlus); 6407 assert((Fn->containsErrors() || 6408 llvm::any_of(ArgExprs, 6409 [](clang::Expr *E) { return E->containsErrors(); })) && 6410 "should only occur in error-recovery path."); 6411 QualType ReturnType = 6412 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6413 ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType() 6414 : Context.DependentTy; 6415 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6416 Expr::getValueKindForType(ReturnType), RParenLoc, 6417 CurFPFeatureOverrides()); 6418 } 6419 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6420 ExecConfig, IsExecConfig); 6421 } 6422 6423 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6424 /// 6425 /// __builtin_astype( value, dst type ) 6426 /// 6427 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6428 SourceLocation BuiltinLoc, 6429 SourceLocation RParenLoc) { 6430 ExprValueKind VK = VK_RValue; 6431 ExprObjectKind OK = OK_Ordinary; 6432 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6433 QualType SrcTy = E->getType(); 6434 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6435 return ExprError(Diag(BuiltinLoc, 6436 diag::err_invalid_astype_of_different_size) 6437 << DstTy 6438 << SrcTy 6439 << E->getSourceRange()); 6440 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6441 } 6442 6443 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6444 /// provided arguments. 6445 /// 6446 /// __builtin_convertvector( value, dst type ) 6447 /// 6448 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6449 SourceLocation BuiltinLoc, 6450 SourceLocation RParenLoc) { 6451 TypeSourceInfo *TInfo; 6452 GetTypeFromParser(ParsedDestTy, &TInfo); 6453 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6454 } 6455 6456 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6457 /// i.e. an expression not of \p OverloadTy. The expression should 6458 /// unary-convert to an expression of function-pointer or 6459 /// block-pointer type. 6460 /// 6461 /// \param NDecl the declaration being called, if available 6462 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6463 SourceLocation LParenLoc, 6464 ArrayRef<Expr *> Args, 6465 SourceLocation RParenLoc, Expr *Config, 6466 bool IsExecConfig, ADLCallKind UsesADL) { 6467 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6468 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6469 6470 // Functions with 'interrupt' attribute cannot be called directly. 6471 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6472 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6473 return ExprError(); 6474 } 6475 6476 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6477 // so there's some risk when calling out to non-interrupt handler functions 6478 // that the callee might not preserve them. This is easy to diagnose here, 6479 // but can be very challenging to debug. 6480 if (auto *Caller = getCurFunctionDecl()) 6481 if (Caller->hasAttr<ARMInterruptAttr>()) { 6482 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6483 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6484 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6485 } 6486 6487 // Promote the function operand. 6488 // We special-case function promotion here because we only allow promoting 6489 // builtin functions to function pointers in the callee of a call. 6490 ExprResult Result; 6491 QualType ResultTy; 6492 if (BuiltinID && 6493 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6494 // Extract the return type from the (builtin) function pointer type. 6495 // FIXME Several builtins still have setType in 6496 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6497 // Builtins.def to ensure they are correct before removing setType calls. 6498 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6499 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6500 ResultTy = FDecl->getCallResultType(); 6501 } else { 6502 Result = CallExprUnaryConversions(Fn); 6503 ResultTy = Context.BoolTy; 6504 } 6505 if (Result.isInvalid()) 6506 return ExprError(); 6507 Fn = Result.get(); 6508 6509 // Check for a valid function type, but only if it is not a builtin which 6510 // requires custom type checking. These will be handled by 6511 // CheckBuiltinFunctionCall below just after creation of the call expression. 6512 const FunctionType *FuncT = nullptr; 6513 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6514 retry: 6515 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6516 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6517 // have type pointer to function". 6518 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6519 if (!FuncT) 6520 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6521 << Fn->getType() << Fn->getSourceRange()); 6522 } else if (const BlockPointerType *BPT = 6523 Fn->getType()->getAs<BlockPointerType>()) { 6524 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6525 } else { 6526 // Handle calls to expressions of unknown-any type. 6527 if (Fn->getType() == Context.UnknownAnyTy) { 6528 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6529 if (rewrite.isInvalid()) 6530 return ExprError(); 6531 Fn = rewrite.get(); 6532 goto retry; 6533 } 6534 6535 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6536 << Fn->getType() << Fn->getSourceRange()); 6537 } 6538 } 6539 6540 // Get the number of parameters in the function prototype, if any. 6541 // We will allocate space for max(Args.size(), NumParams) arguments 6542 // in the call expression. 6543 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6544 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6545 6546 CallExpr *TheCall; 6547 if (Config) { 6548 assert(UsesADL == ADLCallKind::NotADL && 6549 "CUDAKernelCallExpr should not use ADL"); 6550 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6551 Args, ResultTy, VK_RValue, RParenLoc, 6552 CurFPFeatureOverrides(), NumParams); 6553 } else { 6554 TheCall = 6555 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6556 CurFPFeatureOverrides(), NumParams, UsesADL); 6557 } 6558 6559 if (!Context.isDependenceAllowed()) { 6560 // Forget about the nulled arguments since typo correction 6561 // do not handle them well. 6562 TheCall->shrinkNumArgs(Args.size()); 6563 // C cannot always handle TypoExpr nodes in builtin calls and direct 6564 // function calls as their argument checking don't necessarily handle 6565 // dependent types properly, so make sure any TypoExprs have been 6566 // dealt with. 6567 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6568 if (!Result.isUsable()) return ExprError(); 6569 CallExpr *TheOldCall = TheCall; 6570 TheCall = dyn_cast<CallExpr>(Result.get()); 6571 bool CorrectedTypos = TheCall != TheOldCall; 6572 if (!TheCall) return Result; 6573 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6574 6575 // A new call expression node was created if some typos were corrected. 6576 // However it may not have been constructed with enough storage. In this 6577 // case, rebuild the node with enough storage. The waste of space is 6578 // immaterial since this only happens when some typos were corrected. 6579 if (CorrectedTypos && Args.size() < NumParams) { 6580 if (Config) 6581 TheCall = CUDAKernelCallExpr::Create( 6582 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6583 RParenLoc, CurFPFeatureOverrides(), NumParams); 6584 else 6585 TheCall = 6586 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6587 CurFPFeatureOverrides(), NumParams, UsesADL); 6588 } 6589 // We can now handle the nulled arguments for the default arguments. 6590 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6591 } 6592 6593 // Bail out early if calling a builtin with custom type checking. 6594 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6595 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6596 6597 if (getLangOpts().CUDA) { 6598 if (Config) { 6599 // CUDA: Kernel calls must be to global functions 6600 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6601 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6602 << FDecl << Fn->getSourceRange()); 6603 6604 // CUDA: Kernel function must have 'void' return type 6605 if (!FuncT->getReturnType()->isVoidType() && 6606 !FuncT->getReturnType()->getAs<AutoType>() && 6607 !FuncT->getReturnType()->isInstantiationDependentType()) 6608 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6609 << Fn->getType() << Fn->getSourceRange()); 6610 } else { 6611 // CUDA: Calls to global functions must be configured 6612 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6613 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6614 << FDecl << Fn->getSourceRange()); 6615 } 6616 } 6617 6618 // Check for a valid return type 6619 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6620 FDecl)) 6621 return ExprError(); 6622 6623 // We know the result type of the call, set it. 6624 TheCall->setType(FuncT->getCallResultType(Context)); 6625 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6626 6627 if (Proto) { 6628 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6629 IsExecConfig)) 6630 return ExprError(); 6631 } else { 6632 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6633 6634 if (FDecl) { 6635 // Check if we have too few/too many template arguments, based 6636 // on our knowledge of the function definition. 6637 const FunctionDecl *Def = nullptr; 6638 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6639 Proto = Def->getType()->getAs<FunctionProtoType>(); 6640 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6641 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6642 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6643 } 6644 6645 // If the function we're calling isn't a function prototype, but we have 6646 // a function prototype from a prior declaratiom, use that prototype. 6647 if (!FDecl->hasPrototype()) 6648 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6649 } 6650 6651 // Promote the arguments (C99 6.5.2.2p6). 6652 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6653 Expr *Arg = Args[i]; 6654 6655 if (Proto && i < Proto->getNumParams()) { 6656 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6657 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6658 ExprResult ArgE = 6659 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6660 if (ArgE.isInvalid()) 6661 return true; 6662 6663 Arg = ArgE.getAs<Expr>(); 6664 6665 } else { 6666 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6667 6668 if (ArgE.isInvalid()) 6669 return true; 6670 6671 Arg = ArgE.getAs<Expr>(); 6672 } 6673 6674 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6675 diag::err_call_incomplete_argument, Arg)) 6676 return ExprError(); 6677 6678 TheCall->setArg(i, Arg); 6679 } 6680 } 6681 6682 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6683 if (!Method->isStatic()) 6684 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6685 << Fn->getSourceRange()); 6686 6687 // Check for sentinels 6688 if (NDecl) 6689 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6690 6691 // Warn for unions passing across security boundary (CMSE). 6692 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6693 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6694 if (const auto *RT = 6695 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6696 if (RT->getDecl()->isOrContainsUnion()) 6697 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6698 << 0 << i; 6699 } 6700 } 6701 } 6702 6703 // Do special checking on direct calls to functions. 6704 if (FDecl) { 6705 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6706 return ExprError(); 6707 6708 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6709 6710 if (BuiltinID) 6711 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6712 } else if (NDecl) { 6713 if (CheckPointerCall(NDecl, TheCall, Proto)) 6714 return ExprError(); 6715 } else { 6716 if (CheckOtherCall(TheCall, Proto)) 6717 return ExprError(); 6718 } 6719 6720 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6721 } 6722 6723 ExprResult 6724 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6725 SourceLocation RParenLoc, Expr *InitExpr) { 6726 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6727 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6728 6729 TypeSourceInfo *TInfo; 6730 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6731 if (!TInfo) 6732 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6733 6734 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6735 } 6736 6737 ExprResult 6738 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6739 SourceLocation RParenLoc, Expr *LiteralExpr) { 6740 QualType literalType = TInfo->getType(); 6741 6742 if (literalType->isArrayType()) { 6743 if (RequireCompleteSizedType( 6744 LParenLoc, Context.getBaseElementType(literalType), 6745 diag::err_array_incomplete_or_sizeless_type, 6746 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6747 return ExprError(); 6748 if (literalType->isVariableArrayType()) 6749 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6750 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6751 } else if (!literalType->isDependentType() && 6752 RequireCompleteType(LParenLoc, literalType, 6753 diag::err_typecheck_decl_incomplete_type, 6754 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6755 return ExprError(); 6756 6757 InitializedEntity Entity 6758 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6759 InitializationKind Kind 6760 = InitializationKind::CreateCStyleCast(LParenLoc, 6761 SourceRange(LParenLoc, RParenLoc), 6762 /*InitList=*/true); 6763 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6764 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6765 &literalType); 6766 if (Result.isInvalid()) 6767 return ExprError(); 6768 LiteralExpr = Result.get(); 6769 6770 bool isFileScope = !CurContext->isFunctionOrMethod(); 6771 6772 // In C, compound literals are l-values for some reason. 6773 // For GCC compatibility, in C++, file-scope array compound literals with 6774 // constant initializers are also l-values, and compound literals are 6775 // otherwise prvalues. 6776 // 6777 // (GCC also treats C++ list-initialized file-scope array prvalues with 6778 // constant initializers as l-values, but that's non-conforming, so we don't 6779 // follow it there.) 6780 // 6781 // FIXME: It would be better to handle the lvalue cases as materializing and 6782 // lifetime-extending a temporary object, but our materialized temporaries 6783 // representation only supports lifetime extension from a variable, not "out 6784 // of thin air". 6785 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6786 // is bound to the result of applying array-to-pointer decay to the compound 6787 // literal. 6788 // FIXME: GCC supports compound literals of reference type, which should 6789 // obviously have a value kind derived from the kind of reference involved. 6790 ExprValueKind VK = 6791 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6792 ? VK_RValue 6793 : VK_LValue; 6794 6795 if (isFileScope) 6796 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6797 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6798 Expr *Init = ILE->getInit(i); 6799 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6800 } 6801 6802 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6803 VK, LiteralExpr, isFileScope); 6804 if (isFileScope) { 6805 if (!LiteralExpr->isTypeDependent() && 6806 !LiteralExpr->isValueDependent() && 6807 !literalType->isDependentType()) // C99 6.5.2.5p3 6808 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6809 return ExprError(); 6810 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6811 literalType.getAddressSpace() != LangAS::Default) { 6812 // Embedded-C extensions to C99 6.5.2.5: 6813 // "If the compound literal occurs inside the body of a function, the 6814 // type name shall not be qualified by an address-space qualifier." 6815 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6816 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6817 return ExprError(); 6818 } 6819 6820 if (!isFileScope && !getLangOpts().CPlusPlus) { 6821 // Compound literals that have automatic storage duration are destroyed at 6822 // the end of the scope in C; in C++, they're just temporaries. 6823 6824 // Emit diagnostics if it is or contains a C union type that is non-trivial 6825 // to destruct. 6826 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6827 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6828 NTCUC_CompoundLiteral, NTCUK_Destruct); 6829 6830 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6831 if (literalType.isDestructedType()) { 6832 Cleanup.setExprNeedsCleanups(true); 6833 ExprCleanupObjects.push_back(E); 6834 getCurFunction()->setHasBranchProtectedScope(); 6835 } 6836 } 6837 6838 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6839 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6840 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6841 E->getInitializer()->getExprLoc()); 6842 6843 return MaybeBindToTemporary(E); 6844 } 6845 6846 ExprResult 6847 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6848 SourceLocation RBraceLoc) { 6849 // Only produce each kind of designated initialization diagnostic once. 6850 SourceLocation FirstDesignator; 6851 bool DiagnosedArrayDesignator = false; 6852 bool DiagnosedNestedDesignator = false; 6853 bool DiagnosedMixedDesignator = false; 6854 6855 // Check that any designated initializers are syntactically valid in the 6856 // current language mode. 6857 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6858 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6859 if (FirstDesignator.isInvalid()) 6860 FirstDesignator = DIE->getBeginLoc(); 6861 6862 if (!getLangOpts().CPlusPlus) 6863 break; 6864 6865 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6866 DiagnosedNestedDesignator = true; 6867 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6868 << DIE->getDesignatorsSourceRange(); 6869 } 6870 6871 for (auto &Desig : DIE->designators()) { 6872 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6873 DiagnosedArrayDesignator = true; 6874 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6875 << Desig.getSourceRange(); 6876 } 6877 } 6878 6879 if (!DiagnosedMixedDesignator && 6880 !isa<DesignatedInitExpr>(InitArgList[0])) { 6881 DiagnosedMixedDesignator = true; 6882 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6883 << DIE->getSourceRange(); 6884 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6885 << InitArgList[0]->getSourceRange(); 6886 } 6887 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6888 isa<DesignatedInitExpr>(InitArgList[0])) { 6889 DiagnosedMixedDesignator = true; 6890 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6891 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6892 << DIE->getSourceRange(); 6893 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6894 << InitArgList[I]->getSourceRange(); 6895 } 6896 } 6897 6898 if (FirstDesignator.isValid()) { 6899 // Only diagnose designated initiaization as a C++20 extension if we didn't 6900 // already diagnose use of (non-C++20) C99 designator syntax. 6901 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6902 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6903 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6904 ? diag::warn_cxx17_compat_designated_init 6905 : diag::ext_cxx_designated_init); 6906 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6907 Diag(FirstDesignator, diag::ext_designated_init); 6908 } 6909 } 6910 6911 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6912 } 6913 6914 ExprResult 6915 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6916 SourceLocation RBraceLoc) { 6917 // Semantic analysis for initializers is done by ActOnDeclarator() and 6918 // CheckInitializer() - it requires knowledge of the object being initialized. 6919 6920 // Immediately handle non-overload placeholders. Overloads can be 6921 // resolved contextually, but everything else here can't. 6922 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6923 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6924 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6925 6926 // Ignore failures; dropping the entire initializer list because 6927 // of one failure would be terrible for indexing/etc. 6928 if (result.isInvalid()) continue; 6929 6930 InitArgList[I] = result.get(); 6931 } 6932 } 6933 6934 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6935 RBraceLoc); 6936 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6937 return E; 6938 } 6939 6940 /// Do an explicit extend of the given block pointer if we're in ARC. 6941 void Sema::maybeExtendBlockObject(ExprResult &E) { 6942 assert(E.get()->getType()->isBlockPointerType()); 6943 assert(E.get()->isRValue()); 6944 6945 // Only do this in an r-value context. 6946 if (!getLangOpts().ObjCAutoRefCount) return; 6947 6948 E = ImplicitCastExpr::Create( 6949 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 6950 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 6951 Cleanup.setExprNeedsCleanups(true); 6952 } 6953 6954 /// Prepare a conversion of the given expression to an ObjC object 6955 /// pointer type. 6956 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6957 QualType type = E.get()->getType(); 6958 if (type->isObjCObjectPointerType()) { 6959 return CK_BitCast; 6960 } else if (type->isBlockPointerType()) { 6961 maybeExtendBlockObject(E); 6962 return CK_BlockPointerToObjCPointerCast; 6963 } else { 6964 assert(type->isPointerType()); 6965 return CK_CPointerToObjCPointerCast; 6966 } 6967 } 6968 6969 /// Prepares for a scalar cast, performing all the necessary stages 6970 /// except the final cast and returning the kind required. 6971 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6972 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6973 // Also, callers should have filtered out the invalid cases with 6974 // pointers. Everything else should be possible. 6975 6976 QualType SrcTy = Src.get()->getType(); 6977 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6978 return CK_NoOp; 6979 6980 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6981 case Type::STK_MemberPointer: 6982 llvm_unreachable("member pointer type in C"); 6983 6984 case Type::STK_CPointer: 6985 case Type::STK_BlockPointer: 6986 case Type::STK_ObjCObjectPointer: 6987 switch (DestTy->getScalarTypeKind()) { 6988 case Type::STK_CPointer: { 6989 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6990 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6991 if (SrcAS != DestAS) 6992 return CK_AddressSpaceConversion; 6993 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6994 return CK_NoOp; 6995 return CK_BitCast; 6996 } 6997 case Type::STK_BlockPointer: 6998 return (SrcKind == Type::STK_BlockPointer 6999 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7000 case Type::STK_ObjCObjectPointer: 7001 if (SrcKind == Type::STK_ObjCObjectPointer) 7002 return CK_BitCast; 7003 if (SrcKind == Type::STK_CPointer) 7004 return CK_CPointerToObjCPointerCast; 7005 maybeExtendBlockObject(Src); 7006 return CK_BlockPointerToObjCPointerCast; 7007 case Type::STK_Bool: 7008 return CK_PointerToBoolean; 7009 case Type::STK_Integral: 7010 return CK_PointerToIntegral; 7011 case Type::STK_Floating: 7012 case Type::STK_FloatingComplex: 7013 case Type::STK_IntegralComplex: 7014 case Type::STK_MemberPointer: 7015 case Type::STK_FixedPoint: 7016 llvm_unreachable("illegal cast from pointer"); 7017 } 7018 llvm_unreachable("Should have returned before this"); 7019 7020 case Type::STK_FixedPoint: 7021 switch (DestTy->getScalarTypeKind()) { 7022 case Type::STK_FixedPoint: 7023 return CK_FixedPointCast; 7024 case Type::STK_Bool: 7025 return CK_FixedPointToBoolean; 7026 case Type::STK_Integral: 7027 return CK_FixedPointToIntegral; 7028 case Type::STK_Floating: 7029 return CK_FixedPointToFloating; 7030 case Type::STK_IntegralComplex: 7031 case Type::STK_FloatingComplex: 7032 Diag(Src.get()->getExprLoc(), 7033 diag::err_unimplemented_conversion_with_fixed_point_type) 7034 << DestTy; 7035 return CK_IntegralCast; 7036 case Type::STK_CPointer: 7037 case Type::STK_ObjCObjectPointer: 7038 case Type::STK_BlockPointer: 7039 case Type::STK_MemberPointer: 7040 llvm_unreachable("illegal cast to pointer type"); 7041 } 7042 llvm_unreachable("Should have returned before this"); 7043 7044 case Type::STK_Bool: // casting from bool is like casting from an integer 7045 case Type::STK_Integral: 7046 switch (DestTy->getScalarTypeKind()) { 7047 case Type::STK_CPointer: 7048 case Type::STK_ObjCObjectPointer: 7049 case Type::STK_BlockPointer: 7050 if (Src.get()->isNullPointerConstant(Context, 7051 Expr::NPC_ValueDependentIsNull)) 7052 return CK_NullToPointer; 7053 return CK_IntegralToPointer; 7054 case Type::STK_Bool: 7055 return CK_IntegralToBoolean; 7056 case Type::STK_Integral: 7057 return CK_IntegralCast; 7058 case Type::STK_Floating: 7059 return CK_IntegralToFloating; 7060 case Type::STK_IntegralComplex: 7061 Src = ImpCastExprToType(Src.get(), 7062 DestTy->castAs<ComplexType>()->getElementType(), 7063 CK_IntegralCast); 7064 return CK_IntegralRealToComplex; 7065 case Type::STK_FloatingComplex: 7066 Src = ImpCastExprToType(Src.get(), 7067 DestTy->castAs<ComplexType>()->getElementType(), 7068 CK_IntegralToFloating); 7069 return CK_FloatingRealToComplex; 7070 case Type::STK_MemberPointer: 7071 llvm_unreachable("member pointer type in C"); 7072 case Type::STK_FixedPoint: 7073 return CK_IntegralToFixedPoint; 7074 } 7075 llvm_unreachable("Should have returned before this"); 7076 7077 case Type::STK_Floating: 7078 switch (DestTy->getScalarTypeKind()) { 7079 case Type::STK_Floating: 7080 return CK_FloatingCast; 7081 case Type::STK_Bool: 7082 return CK_FloatingToBoolean; 7083 case Type::STK_Integral: 7084 return CK_FloatingToIntegral; 7085 case Type::STK_FloatingComplex: 7086 Src = ImpCastExprToType(Src.get(), 7087 DestTy->castAs<ComplexType>()->getElementType(), 7088 CK_FloatingCast); 7089 return CK_FloatingRealToComplex; 7090 case Type::STK_IntegralComplex: 7091 Src = ImpCastExprToType(Src.get(), 7092 DestTy->castAs<ComplexType>()->getElementType(), 7093 CK_FloatingToIntegral); 7094 return CK_IntegralRealToComplex; 7095 case Type::STK_CPointer: 7096 case Type::STK_ObjCObjectPointer: 7097 case Type::STK_BlockPointer: 7098 llvm_unreachable("valid float->pointer cast?"); 7099 case Type::STK_MemberPointer: 7100 llvm_unreachable("member pointer type in C"); 7101 case Type::STK_FixedPoint: 7102 return CK_FloatingToFixedPoint; 7103 } 7104 llvm_unreachable("Should have returned before this"); 7105 7106 case Type::STK_FloatingComplex: 7107 switch (DestTy->getScalarTypeKind()) { 7108 case Type::STK_FloatingComplex: 7109 return CK_FloatingComplexCast; 7110 case Type::STK_IntegralComplex: 7111 return CK_FloatingComplexToIntegralComplex; 7112 case Type::STK_Floating: { 7113 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7114 if (Context.hasSameType(ET, DestTy)) 7115 return CK_FloatingComplexToReal; 7116 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7117 return CK_FloatingCast; 7118 } 7119 case Type::STK_Bool: 7120 return CK_FloatingComplexToBoolean; 7121 case Type::STK_Integral: 7122 Src = ImpCastExprToType(Src.get(), 7123 SrcTy->castAs<ComplexType>()->getElementType(), 7124 CK_FloatingComplexToReal); 7125 return CK_FloatingToIntegral; 7126 case Type::STK_CPointer: 7127 case Type::STK_ObjCObjectPointer: 7128 case Type::STK_BlockPointer: 7129 llvm_unreachable("valid complex float->pointer cast?"); 7130 case Type::STK_MemberPointer: 7131 llvm_unreachable("member pointer type in C"); 7132 case Type::STK_FixedPoint: 7133 Diag(Src.get()->getExprLoc(), 7134 diag::err_unimplemented_conversion_with_fixed_point_type) 7135 << SrcTy; 7136 return CK_IntegralCast; 7137 } 7138 llvm_unreachable("Should have returned before this"); 7139 7140 case Type::STK_IntegralComplex: 7141 switch (DestTy->getScalarTypeKind()) { 7142 case Type::STK_FloatingComplex: 7143 return CK_IntegralComplexToFloatingComplex; 7144 case Type::STK_IntegralComplex: 7145 return CK_IntegralComplexCast; 7146 case Type::STK_Integral: { 7147 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7148 if (Context.hasSameType(ET, DestTy)) 7149 return CK_IntegralComplexToReal; 7150 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7151 return CK_IntegralCast; 7152 } 7153 case Type::STK_Bool: 7154 return CK_IntegralComplexToBoolean; 7155 case Type::STK_Floating: 7156 Src = ImpCastExprToType(Src.get(), 7157 SrcTy->castAs<ComplexType>()->getElementType(), 7158 CK_IntegralComplexToReal); 7159 return CK_IntegralToFloating; 7160 case Type::STK_CPointer: 7161 case Type::STK_ObjCObjectPointer: 7162 case Type::STK_BlockPointer: 7163 llvm_unreachable("valid complex int->pointer cast?"); 7164 case Type::STK_MemberPointer: 7165 llvm_unreachable("member pointer type in C"); 7166 case Type::STK_FixedPoint: 7167 Diag(Src.get()->getExprLoc(), 7168 diag::err_unimplemented_conversion_with_fixed_point_type) 7169 << SrcTy; 7170 return CK_IntegralCast; 7171 } 7172 llvm_unreachable("Should have returned before this"); 7173 } 7174 7175 llvm_unreachable("Unhandled scalar cast"); 7176 } 7177 7178 static bool breakDownVectorType(QualType type, uint64_t &len, 7179 QualType &eltType) { 7180 // Vectors are simple. 7181 if (const VectorType *vecType = type->getAs<VectorType>()) { 7182 len = vecType->getNumElements(); 7183 eltType = vecType->getElementType(); 7184 assert(eltType->isScalarType()); 7185 return true; 7186 } 7187 7188 // We allow lax conversion to and from non-vector types, but only if 7189 // they're real types (i.e. non-complex, non-pointer scalar types). 7190 if (!type->isRealType()) return false; 7191 7192 len = 1; 7193 eltType = type; 7194 return true; 7195 } 7196 7197 /// Are the two types lax-compatible vector types? That is, given 7198 /// that one of them is a vector, do they have equal storage sizes, 7199 /// where the storage size is the number of elements times the element 7200 /// size? 7201 /// 7202 /// This will also return false if either of the types is neither a 7203 /// vector nor a real type. 7204 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7205 assert(destTy->isVectorType() || srcTy->isVectorType()); 7206 7207 // Disallow lax conversions between scalars and ExtVectors (these 7208 // conversions are allowed for other vector types because common headers 7209 // depend on them). Most scalar OP ExtVector cases are handled by the 7210 // splat path anyway, which does what we want (convert, not bitcast). 7211 // What this rules out for ExtVectors is crazy things like char4*float. 7212 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7213 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7214 7215 uint64_t srcLen, destLen; 7216 QualType srcEltTy, destEltTy; 7217 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7218 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7219 7220 // ASTContext::getTypeSize will return the size rounded up to a 7221 // power of 2, so instead of using that, we need to use the raw 7222 // element size multiplied by the element count. 7223 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7224 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7225 7226 return (srcLen * srcEltSize == destLen * destEltSize); 7227 } 7228 7229 /// Is this a legal conversion between two types, one of which is 7230 /// known to be a vector type? 7231 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7232 assert(destTy->isVectorType() || srcTy->isVectorType()); 7233 7234 switch (Context.getLangOpts().getLaxVectorConversions()) { 7235 case LangOptions::LaxVectorConversionKind::None: 7236 return false; 7237 7238 case LangOptions::LaxVectorConversionKind::Integer: 7239 if (!srcTy->isIntegralOrEnumerationType()) { 7240 auto *Vec = srcTy->getAs<VectorType>(); 7241 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7242 return false; 7243 } 7244 if (!destTy->isIntegralOrEnumerationType()) { 7245 auto *Vec = destTy->getAs<VectorType>(); 7246 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7247 return false; 7248 } 7249 // OK, integer (vector) -> integer (vector) bitcast. 7250 break; 7251 7252 case LangOptions::LaxVectorConversionKind::All: 7253 break; 7254 } 7255 7256 return areLaxCompatibleVectorTypes(srcTy, destTy); 7257 } 7258 7259 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7260 CastKind &Kind) { 7261 assert(VectorTy->isVectorType() && "Not a vector type!"); 7262 7263 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7264 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7265 return Diag(R.getBegin(), 7266 Ty->isVectorType() ? 7267 diag::err_invalid_conversion_between_vectors : 7268 diag::err_invalid_conversion_between_vector_and_integer) 7269 << VectorTy << Ty << R; 7270 } else 7271 return Diag(R.getBegin(), 7272 diag::err_invalid_conversion_between_vector_and_scalar) 7273 << VectorTy << Ty << R; 7274 7275 Kind = CK_BitCast; 7276 return false; 7277 } 7278 7279 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7280 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7281 7282 if (DestElemTy == SplattedExpr->getType()) 7283 return SplattedExpr; 7284 7285 assert(DestElemTy->isFloatingType() || 7286 DestElemTy->isIntegralOrEnumerationType()); 7287 7288 CastKind CK; 7289 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7290 // OpenCL requires that we convert `true` boolean expressions to -1, but 7291 // only when splatting vectors. 7292 if (DestElemTy->isFloatingType()) { 7293 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7294 // in two steps: boolean to signed integral, then to floating. 7295 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7296 CK_BooleanToSignedIntegral); 7297 SplattedExpr = CastExprRes.get(); 7298 CK = CK_IntegralToFloating; 7299 } else { 7300 CK = CK_BooleanToSignedIntegral; 7301 } 7302 } else { 7303 ExprResult CastExprRes = SplattedExpr; 7304 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7305 if (CastExprRes.isInvalid()) 7306 return ExprError(); 7307 SplattedExpr = CastExprRes.get(); 7308 } 7309 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7310 } 7311 7312 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7313 Expr *CastExpr, CastKind &Kind) { 7314 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7315 7316 QualType SrcTy = CastExpr->getType(); 7317 7318 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7319 // an ExtVectorType. 7320 // In OpenCL, casts between vectors of different types are not allowed. 7321 // (See OpenCL 6.2). 7322 if (SrcTy->isVectorType()) { 7323 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7324 (getLangOpts().OpenCL && 7325 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7326 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7327 << DestTy << SrcTy << R; 7328 return ExprError(); 7329 } 7330 Kind = CK_BitCast; 7331 return CastExpr; 7332 } 7333 7334 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7335 // conversion will take place first from scalar to elt type, and then 7336 // splat from elt type to vector. 7337 if (SrcTy->isPointerType()) 7338 return Diag(R.getBegin(), 7339 diag::err_invalid_conversion_between_vector_and_scalar) 7340 << DestTy << SrcTy << R; 7341 7342 Kind = CK_VectorSplat; 7343 return prepareVectorSplat(DestTy, CastExpr); 7344 } 7345 7346 ExprResult 7347 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7348 Declarator &D, ParsedType &Ty, 7349 SourceLocation RParenLoc, Expr *CastExpr) { 7350 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7351 "ActOnCastExpr(): missing type or expr"); 7352 7353 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7354 if (D.isInvalidType()) 7355 return ExprError(); 7356 7357 if (getLangOpts().CPlusPlus) { 7358 // Check that there are no default arguments (C++ only). 7359 CheckExtraCXXDefaultArguments(D); 7360 } else { 7361 // Make sure any TypoExprs have been dealt with. 7362 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7363 if (!Res.isUsable()) 7364 return ExprError(); 7365 CastExpr = Res.get(); 7366 } 7367 7368 checkUnusedDeclAttributes(D); 7369 7370 QualType castType = castTInfo->getType(); 7371 Ty = CreateParsedType(castType, castTInfo); 7372 7373 bool isVectorLiteral = false; 7374 7375 // Check for an altivec or OpenCL literal, 7376 // i.e. all the elements are integer constants. 7377 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7378 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7379 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7380 && castType->isVectorType() && (PE || PLE)) { 7381 if (PLE && PLE->getNumExprs() == 0) { 7382 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7383 return ExprError(); 7384 } 7385 if (PE || PLE->getNumExprs() == 1) { 7386 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7387 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7388 isVectorLiteral = true; 7389 } 7390 else 7391 isVectorLiteral = true; 7392 } 7393 7394 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7395 // then handle it as such. 7396 if (isVectorLiteral) 7397 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7398 7399 // If the Expr being casted is a ParenListExpr, handle it specially. 7400 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7401 // sequence of BinOp comma operators. 7402 if (isa<ParenListExpr>(CastExpr)) { 7403 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7404 if (Result.isInvalid()) return ExprError(); 7405 CastExpr = Result.get(); 7406 } 7407 7408 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7409 !getSourceManager().isInSystemMacro(LParenLoc)) 7410 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7411 7412 CheckTollFreeBridgeCast(castType, CastExpr); 7413 7414 CheckObjCBridgeRelatedCast(castType, CastExpr); 7415 7416 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7417 7418 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7419 } 7420 7421 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7422 SourceLocation RParenLoc, Expr *E, 7423 TypeSourceInfo *TInfo) { 7424 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7425 "Expected paren or paren list expression"); 7426 7427 Expr **exprs; 7428 unsigned numExprs; 7429 Expr *subExpr; 7430 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7431 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7432 LiteralLParenLoc = PE->getLParenLoc(); 7433 LiteralRParenLoc = PE->getRParenLoc(); 7434 exprs = PE->getExprs(); 7435 numExprs = PE->getNumExprs(); 7436 } else { // isa<ParenExpr> by assertion at function entrance 7437 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7438 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7439 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7440 exprs = &subExpr; 7441 numExprs = 1; 7442 } 7443 7444 QualType Ty = TInfo->getType(); 7445 assert(Ty->isVectorType() && "Expected vector type"); 7446 7447 SmallVector<Expr *, 8> initExprs; 7448 const VectorType *VTy = Ty->castAs<VectorType>(); 7449 unsigned numElems = VTy->getNumElements(); 7450 7451 // '(...)' form of vector initialization in AltiVec: the number of 7452 // initializers must be one or must match the size of the vector. 7453 // If a single value is specified in the initializer then it will be 7454 // replicated to all the components of the vector 7455 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7456 // The number of initializers must be one or must match the size of the 7457 // vector. If a single value is specified in the initializer then it will 7458 // be replicated to all the components of the vector 7459 if (numExprs == 1) { 7460 QualType ElemTy = VTy->getElementType(); 7461 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7462 if (Literal.isInvalid()) 7463 return ExprError(); 7464 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7465 PrepareScalarCast(Literal, ElemTy)); 7466 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7467 } 7468 else if (numExprs < numElems) { 7469 Diag(E->getExprLoc(), 7470 diag::err_incorrect_number_of_vector_initializers); 7471 return ExprError(); 7472 } 7473 else 7474 initExprs.append(exprs, exprs + numExprs); 7475 } 7476 else { 7477 // For OpenCL, when the number of initializers is a single value, 7478 // it will be replicated to all components of the vector. 7479 if (getLangOpts().OpenCL && 7480 VTy->getVectorKind() == VectorType::GenericVector && 7481 numExprs == 1) { 7482 QualType ElemTy = VTy->getElementType(); 7483 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7484 if (Literal.isInvalid()) 7485 return ExprError(); 7486 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7487 PrepareScalarCast(Literal, ElemTy)); 7488 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7489 } 7490 7491 initExprs.append(exprs, exprs + numExprs); 7492 } 7493 // FIXME: This means that pretty-printing the final AST will produce curly 7494 // braces instead of the original commas. 7495 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7496 initExprs, LiteralRParenLoc); 7497 initE->setType(Ty); 7498 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7499 } 7500 7501 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7502 /// the ParenListExpr into a sequence of comma binary operators. 7503 ExprResult 7504 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7505 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7506 if (!E) 7507 return OrigExpr; 7508 7509 ExprResult Result(E->getExpr(0)); 7510 7511 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7512 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7513 E->getExpr(i)); 7514 7515 if (Result.isInvalid()) return ExprError(); 7516 7517 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7518 } 7519 7520 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7521 SourceLocation R, 7522 MultiExprArg Val) { 7523 return ParenListExpr::Create(Context, L, Val, R); 7524 } 7525 7526 /// Emit a specialized diagnostic when one expression is a null pointer 7527 /// constant and the other is not a pointer. Returns true if a diagnostic is 7528 /// emitted. 7529 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7530 SourceLocation QuestionLoc) { 7531 Expr *NullExpr = LHSExpr; 7532 Expr *NonPointerExpr = RHSExpr; 7533 Expr::NullPointerConstantKind NullKind = 7534 NullExpr->isNullPointerConstant(Context, 7535 Expr::NPC_ValueDependentIsNotNull); 7536 7537 if (NullKind == Expr::NPCK_NotNull) { 7538 NullExpr = RHSExpr; 7539 NonPointerExpr = LHSExpr; 7540 NullKind = 7541 NullExpr->isNullPointerConstant(Context, 7542 Expr::NPC_ValueDependentIsNotNull); 7543 } 7544 7545 if (NullKind == Expr::NPCK_NotNull) 7546 return false; 7547 7548 if (NullKind == Expr::NPCK_ZeroExpression) 7549 return false; 7550 7551 if (NullKind == Expr::NPCK_ZeroLiteral) { 7552 // In this case, check to make sure that we got here from a "NULL" 7553 // string in the source code. 7554 NullExpr = NullExpr->IgnoreParenImpCasts(); 7555 SourceLocation loc = NullExpr->getExprLoc(); 7556 if (!findMacroSpelling(loc, "NULL")) 7557 return false; 7558 } 7559 7560 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7561 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7562 << NonPointerExpr->getType() << DiagType 7563 << NonPointerExpr->getSourceRange(); 7564 return true; 7565 } 7566 7567 /// Return false if the condition expression is valid, true otherwise. 7568 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7569 QualType CondTy = Cond->getType(); 7570 7571 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7572 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7573 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7574 << CondTy << Cond->getSourceRange(); 7575 return true; 7576 } 7577 7578 // C99 6.5.15p2 7579 if (CondTy->isScalarType()) return false; 7580 7581 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7582 << CondTy << Cond->getSourceRange(); 7583 return true; 7584 } 7585 7586 /// Handle when one or both operands are void type. 7587 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7588 ExprResult &RHS) { 7589 Expr *LHSExpr = LHS.get(); 7590 Expr *RHSExpr = RHS.get(); 7591 7592 if (!LHSExpr->getType()->isVoidType()) 7593 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7594 << RHSExpr->getSourceRange(); 7595 if (!RHSExpr->getType()->isVoidType()) 7596 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7597 << LHSExpr->getSourceRange(); 7598 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7599 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7600 return S.Context.VoidTy; 7601 } 7602 7603 /// Return false if the NullExpr can be promoted to PointerTy, 7604 /// true otherwise. 7605 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7606 QualType PointerTy) { 7607 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7608 !NullExpr.get()->isNullPointerConstant(S.Context, 7609 Expr::NPC_ValueDependentIsNull)) 7610 return true; 7611 7612 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7613 return false; 7614 } 7615 7616 /// Checks compatibility between two pointers and return the resulting 7617 /// type. 7618 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7619 ExprResult &RHS, 7620 SourceLocation Loc) { 7621 QualType LHSTy = LHS.get()->getType(); 7622 QualType RHSTy = RHS.get()->getType(); 7623 7624 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7625 // Two identical pointers types are always compatible. 7626 return LHSTy; 7627 } 7628 7629 QualType lhptee, rhptee; 7630 7631 // Get the pointee types. 7632 bool IsBlockPointer = false; 7633 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7634 lhptee = LHSBTy->getPointeeType(); 7635 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7636 IsBlockPointer = true; 7637 } else { 7638 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7639 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7640 } 7641 7642 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7643 // differently qualified versions of compatible types, the result type is 7644 // a pointer to an appropriately qualified version of the composite 7645 // type. 7646 7647 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7648 // clause doesn't make sense for our extensions. E.g. address space 2 should 7649 // be incompatible with address space 3: they may live on different devices or 7650 // anything. 7651 Qualifiers lhQual = lhptee.getQualifiers(); 7652 Qualifiers rhQual = rhptee.getQualifiers(); 7653 7654 LangAS ResultAddrSpace = LangAS::Default; 7655 LangAS LAddrSpace = lhQual.getAddressSpace(); 7656 LangAS RAddrSpace = rhQual.getAddressSpace(); 7657 7658 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7659 // spaces is disallowed. 7660 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7661 ResultAddrSpace = LAddrSpace; 7662 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7663 ResultAddrSpace = RAddrSpace; 7664 else { 7665 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7666 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7667 << RHS.get()->getSourceRange(); 7668 return QualType(); 7669 } 7670 7671 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7672 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7673 lhQual.removeCVRQualifiers(); 7674 rhQual.removeCVRQualifiers(); 7675 7676 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7677 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7678 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7679 // qual types are compatible iff 7680 // * corresponded types are compatible 7681 // * CVR qualifiers are equal 7682 // * address spaces are equal 7683 // Thus for conditional operator we merge CVR and address space unqualified 7684 // pointees and if there is a composite type we return a pointer to it with 7685 // merged qualifiers. 7686 LHSCastKind = 7687 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7688 RHSCastKind = 7689 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7690 lhQual.removeAddressSpace(); 7691 rhQual.removeAddressSpace(); 7692 7693 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7694 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7695 7696 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7697 7698 if (CompositeTy.isNull()) { 7699 // In this situation, we assume void* type. No especially good 7700 // reason, but this is what gcc does, and we do have to pick 7701 // to get a consistent AST. 7702 QualType incompatTy; 7703 incompatTy = S.Context.getPointerType( 7704 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7705 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7706 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7707 7708 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7709 // for casts between types with incompatible address space qualifiers. 7710 // For the following code the compiler produces casts between global and 7711 // local address spaces of the corresponded innermost pointees: 7712 // local int *global *a; 7713 // global int *global *b; 7714 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7715 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7716 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7717 << RHS.get()->getSourceRange(); 7718 7719 return incompatTy; 7720 } 7721 7722 // The pointer types are compatible. 7723 // In case of OpenCL ResultTy should have the address space qualifier 7724 // which is a superset of address spaces of both the 2nd and the 3rd 7725 // operands of the conditional operator. 7726 QualType ResultTy = [&, ResultAddrSpace]() { 7727 if (S.getLangOpts().OpenCL) { 7728 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7729 CompositeQuals.setAddressSpace(ResultAddrSpace); 7730 return S.Context 7731 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7732 .withCVRQualifiers(MergedCVRQual); 7733 } 7734 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7735 }(); 7736 if (IsBlockPointer) 7737 ResultTy = S.Context.getBlockPointerType(ResultTy); 7738 else 7739 ResultTy = S.Context.getPointerType(ResultTy); 7740 7741 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7742 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7743 return ResultTy; 7744 } 7745 7746 /// Return the resulting type when the operands are both block pointers. 7747 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7748 ExprResult &LHS, 7749 ExprResult &RHS, 7750 SourceLocation Loc) { 7751 QualType LHSTy = LHS.get()->getType(); 7752 QualType RHSTy = RHS.get()->getType(); 7753 7754 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7755 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7756 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7757 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7758 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7759 return destType; 7760 } 7761 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7762 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7763 << RHS.get()->getSourceRange(); 7764 return QualType(); 7765 } 7766 7767 // We have 2 block pointer types. 7768 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7769 } 7770 7771 /// Return the resulting type when the operands are both pointers. 7772 static QualType 7773 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7774 ExprResult &RHS, 7775 SourceLocation Loc) { 7776 // get the pointer types 7777 QualType LHSTy = LHS.get()->getType(); 7778 QualType RHSTy = RHS.get()->getType(); 7779 7780 // get the "pointed to" types 7781 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7782 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7783 7784 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7785 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7786 // Figure out necessary qualifiers (C99 6.5.15p6) 7787 QualType destPointee 7788 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7789 QualType destType = S.Context.getPointerType(destPointee); 7790 // Add qualifiers if necessary. 7791 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7792 // Promote to void*. 7793 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7794 return destType; 7795 } 7796 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7797 QualType destPointee 7798 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7799 QualType destType = S.Context.getPointerType(destPointee); 7800 // Add qualifiers if necessary. 7801 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7802 // Promote to void*. 7803 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7804 return destType; 7805 } 7806 7807 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7808 } 7809 7810 /// Return false if the first expression is not an integer and the second 7811 /// expression is not a pointer, true otherwise. 7812 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7813 Expr* PointerExpr, SourceLocation Loc, 7814 bool IsIntFirstExpr) { 7815 if (!PointerExpr->getType()->isPointerType() || 7816 !Int.get()->getType()->isIntegerType()) 7817 return false; 7818 7819 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7820 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7821 7822 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7823 << Expr1->getType() << Expr2->getType() 7824 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7825 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7826 CK_IntegralToPointer); 7827 return true; 7828 } 7829 7830 /// Simple conversion between integer and floating point types. 7831 /// 7832 /// Used when handling the OpenCL conditional operator where the 7833 /// condition is a vector while the other operands are scalar. 7834 /// 7835 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7836 /// types are either integer or floating type. Between the two 7837 /// operands, the type with the higher rank is defined as the "result 7838 /// type". The other operand needs to be promoted to the same type. No 7839 /// other type promotion is allowed. We cannot use 7840 /// UsualArithmeticConversions() for this purpose, since it always 7841 /// promotes promotable types. 7842 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7843 ExprResult &RHS, 7844 SourceLocation QuestionLoc) { 7845 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7846 if (LHS.isInvalid()) 7847 return QualType(); 7848 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7849 if (RHS.isInvalid()) 7850 return QualType(); 7851 7852 // For conversion purposes, we ignore any qualifiers. 7853 // For example, "const float" and "float" are equivalent. 7854 QualType LHSType = 7855 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7856 QualType RHSType = 7857 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7858 7859 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7860 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7861 << LHSType << LHS.get()->getSourceRange(); 7862 return QualType(); 7863 } 7864 7865 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7866 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7867 << RHSType << RHS.get()->getSourceRange(); 7868 return QualType(); 7869 } 7870 7871 // If both types are identical, no conversion is needed. 7872 if (LHSType == RHSType) 7873 return LHSType; 7874 7875 // Now handle "real" floating types (i.e. float, double, long double). 7876 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7877 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7878 /*IsCompAssign = */ false); 7879 7880 // Finally, we have two differing integer types. 7881 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7882 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7883 } 7884 7885 /// Convert scalar operands to a vector that matches the 7886 /// condition in length. 7887 /// 7888 /// Used when handling the OpenCL conditional operator where the 7889 /// condition is a vector while the other operands are scalar. 7890 /// 7891 /// We first compute the "result type" for the scalar operands 7892 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7893 /// into a vector of that type where the length matches the condition 7894 /// vector type. s6.11.6 requires that the element types of the result 7895 /// and the condition must have the same number of bits. 7896 static QualType 7897 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7898 QualType CondTy, SourceLocation QuestionLoc) { 7899 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7900 if (ResTy.isNull()) return QualType(); 7901 7902 const VectorType *CV = CondTy->getAs<VectorType>(); 7903 assert(CV); 7904 7905 // Determine the vector result type 7906 unsigned NumElements = CV->getNumElements(); 7907 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7908 7909 // Ensure that all types have the same number of bits 7910 if (S.Context.getTypeSize(CV->getElementType()) 7911 != S.Context.getTypeSize(ResTy)) { 7912 // Since VectorTy is created internally, it does not pretty print 7913 // with an OpenCL name. Instead, we just print a description. 7914 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7915 SmallString<64> Str; 7916 llvm::raw_svector_ostream OS(Str); 7917 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7918 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7919 << CondTy << OS.str(); 7920 return QualType(); 7921 } 7922 7923 // Convert operands to the vector result type 7924 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7925 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7926 7927 return VectorTy; 7928 } 7929 7930 /// Return false if this is a valid OpenCL condition vector 7931 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7932 SourceLocation QuestionLoc) { 7933 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7934 // integral type. 7935 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7936 assert(CondTy); 7937 QualType EleTy = CondTy->getElementType(); 7938 if (EleTy->isIntegerType()) return false; 7939 7940 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7941 << Cond->getType() << Cond->getSourceRange(); 7942 return true; 7943 } 7944 7945 /// Return false if the vector condition type and the vector 7946 /// result type are compatible. 7947 /// 7948 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7949 /// number of elements, and their element types have the same number 7950 /// of bits. 7951 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7952 SourceLocation QuestionLoc) { 7953 const VectorType *CV = CondTy->getAs<VectorType>(); 7954 const VectorType *RV = VecResTy->getAs<VectorType>(); 7955 assert(CV && RV); 7956 7957 if (CV->getNumElements() != RV->getNumElements()) { 7958 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7959 << CondTy << VecResTy; 7960 return true; 7961 } 7962 7963 QualType CVE = CV->getElementType(); 7964 QualType RVE = RV->getElementType(); 7965 7966 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7967 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7968 << CondTy << VecResTy; 7969 return true; 7970 } 7971 7972 return false; 7973 } 7974 7975 /// Return the resulting type for the conditional operator in 7976 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7977 /// s6.3.i) when the condition is a vector type. 7978 static QualType 7979 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7980 ExprResult &LHS, ExprResult &RHS, 7981 SourceLocation QuestionLoc) { 7982 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7983 if (Cond.isInvalid()) 7984 return QualType(); 7985 QualType CondTy = Cond.get()->getType(); 7986 7987 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7988 return QualType(); 7989 7990 // If either operand is a vector then find the vector type of the 7991 // result as specified in OpenCL v1.1 s6.3.i. 7992 if (LHS.get()->getType()->isVectorType() || 7993 RHS.get()->getType()->isVectorType()) { 7994 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7995 /*isCompAssign*/false, 7996 /*AllowBothBool*/true, 7997 /*AllowBoolConversions*/false); 7998 if (VecResTy.isNull()) return QualType(); 7999 // The result type must match the condition type as specified in 8000 // OpenCL v1.1 s6.11.6. 8001 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8002 return QualType(); 8003 return VecResTy; 8004 } 8005 8006 // Both operands are scalar. 8007 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8008 } 8009 8010 /// Return true if the Expr is block type 8011 static bool checkBlockType(Sema &S, const Expr *E) { 8012 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8013 QualType Ty = CE->getCallee()->getType(); 8014 if (Ty->isBlockPointerType()) { 8015 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8016 return true; 8017 } 8018 } 8019 return false; 8020 } 8021 8022 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8023 /// In that case, LHS = cond. 8024 /// C99 6.5.15 8025 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8026 ExprResult &RHS, ExprValueKind &VK, 8027 ExprObjectKind &OK, 8028 SourceLocation QuestionLoc) { 8029 8030 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8031 if (!LHSResult.isUsable()) return QualType(); 8032 LHS = LHSResult; 8033 8034 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8035 if (!RHSResult.isUsable()) return QualType(); 8036 RHS = RHSResult; 8037 8038 // C++ is sufficiently different to merit its own checker. 8039 if (getLangOpts().CPlusPlus) 8040 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8041 8042 VK = VK_RValue; 8043 OK = OK_Ordinary; 8044 8045 if (Context.isDependenceAllowed() && 8046 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8047 RHS.get()->isTypeDependent())) { 8048 assert(!getLangOpts().CPlusPlus); 8049 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8050 RHS.get()->containsErrors()) && 8051 "should only occur in error-recovery path."); 8052 return Context.DependentTy; 8053 } 8054 8055 // The OpenCL operator with a vector condition is sufficiently 8056 // different to merit its own checker. 8057 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8058 Cond.get()->getType()->isExtVectorType()) 8059 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8060 8061 // First, check the condition. 8062 Cond = UsualUnaryConversions(Cond.get()); 8063 if (Cond.isInvalid()) 8064 return QualType(); 8065 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8066 return QualType(); 8067 8068 // Now check the two expressions. 8069 if (LHS.get()->getType()->isVectorType() || 8070 RHS.get()->getType()->isVectorType()) 8071 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8072 /*AllowBothBool*/true, 8073 /*AllowBoolConversions*/false); 8074 8075 QualType ResTy = 8076 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8077 if (LHS.isInvalid() || RHS.isInvalid()) 8078 return QualType(); 8079 8080 QualType LHSTy = LHS.get()->getType(); 8081 QualType RHSTy = RHS.get()->getType(); 8082 8083 // Diagnose attempts to convert between __float128 and long double where 8084 // such conversions currently can't be handled. 8085 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8086 Diag(QuestionLoc, 8087 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8088 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8089 return QualType(); 8090 } 8091 8092 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8093 // selection operator (?:). 8094 if (getLangOpts().OpenCL && 8095 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8096 return QualType(); 8097 } 8098 8099 // If both operands have arithmetic type, do the usual arithmetic conversions 8100 // to find a common type: C99 6.5.15p3,5. 8101 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8102 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8103 // different sizes, or between ExtInts and other types. 8104 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8105 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8106 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8107 << RHS.get()->getSourceRange(); 8108 return QualType(); 8109 } 8110 8111 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8112 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8113 8114 return ResTy; 8115 } 8116 8117 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8118 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8119 return LHSTy; 8120 } 8121 8122 // If both operands are the same structure or union type, the result is that 8123 // type. 8124 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8125 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8126 if (LHSRT->getDecl() == RHSRT->getDecl()) 8127 // "If both the operands have structure or union type, the result has 8128 // that type." This implies that CV qualifiers are dropped. 8129 return LHSTy.getUnqualifiedType(); 8130 // FIXME: Type of conditional expression must be complete in C mode. 8131 } 8132 8133 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8134 // The following || allows only one side to be void (a GCC-ism). 8135 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8136 return checkConditionalVoidType(*this, LHS, RHS); 8137 } 8138 8139 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8140 // the type of the other operand." 8141 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8142 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8143 8144 // All objective-c pointer type analysis is done here. 8145 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8146 QuestionLoc); 8147 if (LHS.isInvalid() || RHS.isInvalid()) 8148 return QualType(); 8149 if (!compositeType.isNull()) 8150 return compositeType; 8151 8152 8153 // Handle block pointer types. 8154 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8155 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8156 QuestionLoc); 8157 8158 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8159 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8160 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8161 QuestionLoc); 8162 8163 // GCC compatibility: soften pointer/integer mismatch. Note that 8164 // null pointers have been filtered out by this point. 8165 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8166 /*IsIntFirstExpr=*/true)) 8167 return RHSTy; 8168 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8169 /*IsIntFirstExpr=*/false)) 8170 return LHSTy; 8171 8172 // Allow ?: operations in which both operands have the same 8173 // built-in sizeless type. 8174 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8175 return LHSTy; 8176 8177 // Emit a better diagnostic if one of the expressions is a null pointer 8178 // constant and the other is not a pointer type. In this case, the user most 8179 // likely forgot to take the address of the other expression. 8180 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8181 return QualType(); 8182 8183 // Otherwise, the operands are not compatible. 8184 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8185 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8186 << RHS.get()->getSourceRange(); 8187 return QualType(); 8188 } 8189 8190 /// FindCompositeObjCPointerType - Helper method to find composite type of 8191 /// two objective-c pointer types of the two input expressions. 8192 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8193 SourceLocation QuestionLoc) { 8194 QualType LHSTy = LHS.get()->getType(); 8195 QualType RHSTy = RHS.get()->getType(); 8196 8197 // Handle things like Class and struct objc_class*. Here we case the result 8198 // to the pseudo-builtin, because that will be implicitly cast back to the 8199 // redefinition type if an attempt is made to access its fields. 8200 if (LHSTy->isObjCClassType() && 8201 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8202 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8203 return LHSTy; 8204 } 8205 if (RHSTy->isObjCClassType() && 8206 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8207 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8208 return RHSTy; 8209 } 8210 // And the same for struct objc_object* / id 8211 if (LHSTy->isObjCIdType() && 8212 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8213 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8214 return LHSTy; 8215 } 8216 if (RHSTy->isObjCIdType() && 8217 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8218 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8219 return RHSTy; 8220 } 8221 // And the same for struct objc_selector* / SEL 8222 if (Context.isObjCSelType(LHSTy) && 8223 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8224 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8225 return LHSTy; 8226 } 8227 if (Context.isObjCSelType(RHSTy) && 8228 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8229 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8230 return RHSTy; 8231 } 8232 // Check constraints for Objective-C object pointers types. 8233 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8234 8235 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8236 // Two identical object pointer types are always compatible. 8237 return LHSTy; 8238 } 8239 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8240 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8241 QualType compositeType = LHSTy; 8242 8243 // If both operands are interfaces and either operand can be 8244 // assigned to the other, use that type as the composite 8245 // type. This allows 8246 // xxx ? (A*) a : (B*) b 8247 // where B is a subclass of A. 8248 // 8249 // Additionally, as for assignment, if either type is 'id' 8250 // allow silent coercion. Finally, if the types are 8251 // incompatible then make sure to use 'id' as the composite 8252 // type so the result is acceptable for sending messages to. 8253 8254 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8255 // It could return the composite type. 8256 if (!(compositeType = 8257 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8258 // Nothing more to do. 8259 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8260 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8261 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8262 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8263 } else if ((LHSOPT->isObjCQualifiedIdType() || 8264 RHSOPT->isObjCQualifiedIdType()) && 8265 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8266 true)) { 8267 // Need to handle "id<xx>" explicitly. 8268 // GCC allows qualified id and any Objective-C type to devolve to 8269 // id. Currently localizing to here until clear this should be 8270 // part of ObjCQualifiedIdTypesAreCompatible. 8271 compositeType = Context.getObjCIdType(); 8272 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8273 compositeType = Context.getObjCIdType(); 8274 } else { 8275 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8276 << LHSTy << RHSTy 8277 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8278 QualType incompatTy = Context.getObjCIdType(); 8279 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8280 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8281 return incompatTy; 8282 } 8283 // The object pointer types are compatible. 8284 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8285 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8286 return compositeType; 8287 } 8288 // Check Objective-C object pointer types and 'void *' 8289 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8290 if (getLangOpts().ObjCAutoRefCount) { 8291 // ARC forbids the implicit conversion of object pointers to 'void *', 8292 // so these types are not compatible. 8293 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8294 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8295 LHS = RHS = true; 8296 return QualType(); 8297 } 8298 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8299 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8300 QualType destPointee 8301 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8302 QualType destType = Context.getPointerType(destPointee); 8303 // Add qualifiers if necessary. 8304 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8305 // Promote to void*. 8306 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8307 return destType; 8308 } 8309 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8310 if (getLangOpts().ObjCAutoRefCount) { 8311 // ARC forbids the implicit conversion of object pointers to 'void *', 8312 // so these types are not compatible. 8313 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8314 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8315 LHS = RHS = true; 8316 return QualType(); 8317 } 8318 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8319 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8320 QualType destPointee 8321 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8322 QualType destType = Context.getPointerType(destPointee); 8323 // Add qualifiers if necessary. 8324 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8325 // Promote to void*. 8326 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8327 return destType; 8328 } 8329 return QualType(); 8330 } 8331 8332 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8333 /// ParenRange in parentheses. 8334 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8335 const PartialDiagnostic &Note, 8336 SourceRange ParenRange) { 8337 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8338 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8339 EndLoc.isValid()) { 8340 Self.Diag(Loc, Note) 8341 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8342 << FixItHint::CreateInsertion(EndLoc, ")"); 8343 } else { 8344 // We can't display the parentheses, so just show the bare note. 8345 Self.Diag(Loc, Note) << ParenRange; 8346 } 8347 } 8348 8349 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8350 return BinaryOperator::isAdditiveOp(Opc) || 8351 BinaryOperator::isMultiplicativeOp(Opc) || 8352 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8353 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8354 // not any of the logical operators. Bitwise-xor is commonly used as a 8355 // logical-xor because there is no logical-xor operator. The logical 8356 // operators, including uses of xor, have a high false positive rate for 8357 // precedence warnings. 8358 } 8359 8360 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8361 /// expression, either using a built-in or overloaded operator, 8362 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8363 /// expression. 8364 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8365 Expr **RHSExprs) { 8366 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8367 E = E->IgnoreImpCasts(); 8368 E = E->IgnoreConversionOperatorSingleStep(); 8369 E = E->IgnoreImpCasts(); 8370 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8371 E = MTE->getSubExpr(); 8372 E = E->IgnoreImpCasts(); 8373 } 8374 8375 // Built-in binary operator. 8376 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8377 if (IsArithmeticOp(OP->getOpcode())) { 8378 *Opcode = OP->getOpcode(); 8379 *RHSExprs = OP->getRHS(); 8380 return true; 8381 } 8382 } 8383 8384 // Overloaded operator. 8385 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8386 if (Call->getNumArgs() != 2) 8387 return false; 8388 8389 // Make sure this is really a binary operator that is safe to pass into 8390 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8391 OverloadedOperatorKind OO = Call->getOperator(); 8392 if (OO < OO_Plus || OO > OO_Arrow || 8393 OO == OO_PlusPlus || OO == OO_MinusMinus) 8394 return false; 8395 8396 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8397 if (IsArithmeticOp(OpKind)) { 8398 *Opcode = OpKind; 8399 *RHSExprs = Call->getArg(1); 8400 return true; 8401 } 8402 } 8403 8404 return false; 8405 } 8406 8407 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8408 /// or is a logical expression such as (x==y) which has int type, but is 8409 /// commonly interpreted as boolean. 8410 static bool ExprLooksBoolean(Expr *E) { 8411 E = E->IgnoreParenImpCasts(); 8412 8413 if (E->getType()->isBooleanType()) 8414 return true; 8415 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8416 return OP->isComparisonOp() || OP->isLogicalOp(); 8417 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8418 return OP->getOpcode() == UO_LNot; 8419 if (E->getType()->isPointerType()) 8420 return true; 8421 // FIXME: What about overloaded operator calls returning "unspecified boolean 8422 // type"s (commonly pointer-to-members)? 8423 8424 return false; 8425 } 8426 8427 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8428 /// and binary operator are mixed in a way that suggests the programmer assumed 8429 /// the conditional operator has higher precedence, for example: 8430 /// "int x = a + someBinaryCondition ? 1 : 2". 8431 static void DiagnoseConditionalPrecedence(Sema &Self, 8432 SourceLocation OpLoc, 8433 Expr *Condition, 8434 Expr *LHSExpr, 8435 Expr *RHSExpr) { 8436 BinaryOperatorKind CondOpcode; 8437 Expr *CondRHS; 8438 8439 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8440 return; 8441 if (!ExprLooksBoolean(CondRHS)) 8442 return; 8443 8444 // The condition is an arithmetic binary expression, with a right- 8445 // hand side that looks boolean, so warn. 8446 8447 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8448 ? diag::warn_precedence_bitwise_conditional 8449 : diag::warn_precedence_conditional; 8450 8451 Self.Diag(OpLoc, DiagID) 8452 << Condition->getSourceRange() 8453 << BinaryOperator::getOpcodeStr(CondOpcode); 8454 8455 SuggestParentheses( 8456 Self, OpLoc, 8457 Self.PDiag(diag::note_precedence_silence) 8458 << BinaryOperator::getOpcodeStr(CondOpcode), 8459 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8460 8461 SuggestParentheses(Self, OpLoc, 8462 Self.PDiag(diag::note_precedence_conditional_first), 8463 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8464 } 8465 8466 /// Compute the nullability of a conditional expression. 8467 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8468 QualType LHSTy, QualType RHSTy, 8469 ASTContext &Ctx) { 8470 if (!ResTy->isAnyPointerType()) 8471 return ResTy; 8472 8473 auto GetNullability = [&Ctx](QualType Ty) { 8474 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8475 if (Kind) 8476 return *Kind; 8477 return NullabilityKind::Unspecified; 8478 }; 8479 8480 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8481 NullabilityKind MergedKind; 8482 8483 // Compute nullability of a binary conditional expression. 8484 if (IsBin) { 8485 if (LHSKind == NullabilityKind::NonNull) 8486 MergedKind = NullabilityKind::NonNull; 8487 else 8488 MergedKind = RHSKind; 8489 // Compute nullability of a normal conditional expression. 8490 } else { 8491 if (LHSKind == NullabilityKind::Nullable || 8492 RHSKind == NullabilityKind::Nullable) 8493 MergedKind = NullabilityKind::Nullable; 8494 else if (LHSKind == NullabilityKind::NonNull) 8495 MergedKind = RHSKind; 8496 else if (RHSKind == NullabilityKind::NonNull) 8497 MergedKind = LHSKind; 8498 else 8499 MergedKind = NullabilityKind::Unspecified; 8500 } 8501 8502 // Return if ResTy already has the correct nullability. 8503 if (GetNullability(ResTy) == MergedKind) 8504 return ResTy; 8505 8506 // Strip all nullability from ResTy. 8507 while (ResTy->getNullability(Ctx)) 8508 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8509 8510 // Create a new AttributedType with the new nullability kind. 8511 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8512 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8513 } 8514 8515 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8516 /// in the case of a the GNU conditional expr extension. 8517 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8518 SourceLocation ColonLoc, 8519 Expr *CondExpr, Expr *LHSExpr, 8520 Expr *RHSExpr) { 8521 if (!Context.isDependenceAllowed()) { 8522 // C cannot handle TypoExpr nodes in the condition because it 8523 // doesn't handle dependent types properly, so make sure any TypoExprs have 8524 // been dealt with before checking the operands. 8525 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8526 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8527 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8528 8529 if (!CondResult.isUsable()) 8530 return ExprError(); 8531 8532 if (LHSExpr) { 8533 if (!LHSResult.isUsable()) 8534 return ExprError(); 8535 } 8536 8537 if (!RHSResult.isUsable()) 8538 return ExprError(); 8539 8540 CondExpr = CondResult.get(); 8541 LHSExpr = LHSResult.get(); 8542 RHSExpr = RHSResult.get(); 8543 } 8544 8545 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8546 // was the condition. 8547 OpaqueValueExpr *opaqueValue = nullptr; 8548 Expr *commonExpr = nullptr; 8549 if (!LHSExpr) { 8550 commonExpr = CondExpr; 8551 // Lower out placeholder types first. This is important so that we don't 8552 // try to capture a placeholder. This happens in few cases in C++; such 8553 // as Objective-C++'s dictionary subscripting syntax. 8554 if (commonExpr->hasPlaceholderType()) { 8555 ExprResult result = CheckPlaceholderExpr(commonExpr); 8556 if (!result.isUsable()) return ExprError(); 8557 commonExpr = result.get(); 8558 } 8559 // We usually want to apply unary conversions *before* saving, except 8560 // in the special case of a C++ l-value conditional. 8561 if (!(getLangOpts().CPlusPlus 8562 && !commonExpr->isTypeDependent() 8563 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8564 && commonExpr->isGLValue() 8565 && commonExpr->isOrdinaryOrBitFieldObject() 8566 && RHSExpr->isOrdinaryOrBitFieldObject() 8567 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8568 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8569 if (commonRes.isInvalid()) 8570 return ExprError(); 8571 commonExpr = commonRes.get(); 8572 } 8573 8574 // If the common expression is a class or array prvalue, materialize it 8575 // so that we can safely refer to it multiple times. 8576 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8577 commonExpr->getType()->isArrayType())) { 8578 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8579 if (MatExpr.isInvalid()) 8580 return ExprError(); 8581 commonExpr = MatExpr.get(); 8582 } 8583 8584 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8585 commonExpr->getType(), 8586 commonExpr->getValueKind(), 8587 commonExpr->getObjectKind(), 8588 commonExpr); 8589 LHSExpr = CondExpr = opaqueValue; 8590 } 8591 8592 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8593 ExprValueKind VK = VK_RValue; 8594 ExprObjectKind OK = OK_Ordinary; 8595 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8596 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8597 VK, OK, QuestionLoc); 8598 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8599 RHS.isInvalid()) 8600 return ExprError(); 8601 8602 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8603 RHS.get()); 8604 8605 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8606 8607 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8608 Context); 8609 8610 if (!commonExpr) 8611 return new (Context) 8612 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8613 RHS.get(), result, VK, OK); 8614 8615 return new (Context) BinaryConditionalOperator( 8616 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8617 ColonLoc, result, VK, OK); 8618 } 8619 8620 // Check if we have a conversion between incompatible cmse function pointer 8621 // types, that is, a conversion between a function pointer with the 8622 // cmse_nonsecure_call attribute and one without. 8623 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8624 QualType ToType) { 8625 if (const auto *ToFn = 8626 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8627 if (const auto *FromFn = 8628 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8629 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8630 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8631 8632 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8633 } 8634 } 8635 return false; 8636 } 8637 8638 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8639 // being closely modeled after the C99 spec:-). The odd characteristic of this 8640 // routine is it effectively iqnores the qualifiers on the top level pointee. 8641 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8642 // FIXME: add a couple examples in this comment. 8643 static Sema::AssignConvertType 8644 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8645 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8646 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8647 8648 // get the "pointed to" type (ignoring qualifiers at the top level) 8649 const Type *lhptee, *rhptee; 8650 Qualifiers lhq, rhq; 8651 std::tie(lhptee, lhq) = 8652 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8653 std::tie(rhptee, rhq) = 8654 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8655 8656 Sema::AssignConvertType ConvTy = Sema::Compatible; 8657 8658 // C99 6.5.16.1p1: This following citation is common to constraints 8659 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8660 // qualifiers of the type *pointed to* by the right; 8661 8662 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8663 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8664 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8665 // Ignore lifetime for further calculation. 8666 lhq.removeObjCLifetime(); 8667 rhq.removeObjCLifetime(); 8668 } 8669 8670 if (!lhq.compatiblyIncludes(rhq)) { 8671 // Treat address-space mismatches as fatal. 8672 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8673 return Sema::IncompatiblePointerDiscardsQualifiers; 8674 8675 // It's okay to add or remove GC or lifetime qualifiers when converting to 8676 // and from void*. 8677 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8678 .compatiblyIncludes( 8679 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8680 && (lhptee->isVoidType() || rhptee->isVoidType())) 8681 ; // keep old 8682 8683 // Treat lifetime mismatches as fatal. 8684 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8685 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8686 8687 // For GCC/MS compatibility, other qualifier mismatches are treated 8688 // as still compatible in C. 8689 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8690 } 8691 8692 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8693 // incomplete type and the other is a pointer to a qualified or unqualified 8694 // version of void... 8695 if (lhptee->isVoidType()) { 8696 if (rhptee->isIncompleteOrObjectType()) 8697 return ConvTy; 8698 8699 // As an extension, we allow cast to/from void* to function pointer. 8700 assert(rhptee->isFunctionType()); 8701 return Sema::FunctionVoidPointer; 8702 } 8703 8704 if (rhptee->isVoidType()) { 8705 if (lhptee->isIncompleteOrObjectType()) 8706 return ConvTy; 8707 8708 // As an extension, we allow cast to/from void* to function pointer. 8709 assert(lhptee->isFunctionType()); 8710 return Sema::FunctionVoidPointer; 8711 } 8712 8713 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8714 // unqualified versions of compatible types, ... 8715 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8716 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8717 // Check if the pointee types are compatible ignoring the sign. 8718 // We explicitly check for char so that we catch "char" vs 8719 // "unsigned char" on systems where "char" is unsigned. 8720 if (lhptee->isCharType()) 8721 ltrans = S.Context.UnsignedCharTy; 8722 else if (lhptee->hasSignedIntegerRepresentation()) 8723 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8724 8725 if (rhptee->isCharType()) 8726 rtrans = S.Context.UnsignedCharTy; 8727 else if (rhptee->hasSignedIntegerRepresentation()) 8728 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8729 8730 if (ltrans == rtrans) { 8731 // Types are compatible ignoring the sign. Qualifier incompatibility 8732 // takes priority over sign incompatibility because the sign 8733 // warning can be disabled. 8734 if (ConvTy != Sema::Compatible) 8735 return ConvTy; 8736 8737 return Sema::IncompatiblePointerSign; 8738 } 8739 8740 // If we are a multi-level pointer, it's possible that our issue is simply 8741 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8742 // the eventual target type is the same and the pointers have the same 8743 // level of indirection, this must be the issue. 8744 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8745 do { 8746 std::tie(lhptee, lhq) = 8747 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8748 std::tie(rhptee, rhq) = 8749 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8750 8751 // Inconsistent address spaces at this point is invalid, even if the 8752 // address spaces would be compatible. 8753 // FIXME: This doesn't catch address space mismatches for pointers of 8754 // different nesting levels, like: 8755 // __local int *** a; 8756 // int ** b = a; 8757 // It's not clear how to actually determine when such pointers are 8758 // invalidly incompatible. 8759 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8760 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8761 8762 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8763 8764 if (lhptee == rhptee) 8765 return Sema::IncompatibleNestedPointerQualifiers; 8766 } 8767 8768 // General pointer incompatibility takes priority over qualifiers. 8769 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8770 return Sema::IncompatibleFunctionPointer; 8771 return Sema::IncompatiblePointer; 8772 } 8773 if (!S.getLangOpts().CPlusPlus && 8774 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8775 return Sema::IncompatibleFunctionPointer; 8776 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8777 return Sema::IncompatibleFunctionPointer; 8778 return ConvTy; 8779 } 8780 8781 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8782 /// block pointer types are compatible or whether a block and normal pointer 8783 /// are compatible. It is more restrict than comparing two function pointer 8784 // types. 8785 static Sema::AssignConvertType 8786 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8787 QualType RHSType) { 8788 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8789 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8790 8791 QualType lhptee, rhptee; 8792 8793 // get the "pointed to" type (ignoring qualifiers at the top level) 8794 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8795 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8796 8797 // In C++, the types have to match exactly. 8798 if (S.getLangOpts().CPlusPlus) 8799 return Sema::IncompatibleBlockPointer; 8800 8801 Sema::AssignConvertType ConvTy = Sema::Compatible; 8802 8803 // For blocks we enforce that qualifiers are identical. 8804 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8805 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8806 if (S.getLangOpts().OpenCL) { 8807 LQuals.removeAddressSpace(); 8808 RQuals.removeAddressSpace(); 8809 } 8810 if (LQuals != RQuals) 8811 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8812 8813 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8814 // assignment. 8815 // The current behavior is similar to C++ lambdas. A block might be 8816 // assigned to a variable iff its return type and parameters are compatible 8817 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8818 // an assignment. Presumably it should behave in way that a function pointer 8819 // assignment does in C, so for each parameter and return type: 8820 // * CVR and address space of LHS should be a superset of CVR and address 8821 // space of RHS. 8822 // * unqualified types should be compatible. 8823 if (S.getLangOpts().OpenCL) { 8824 if (!S.Context.typesAreBlockPointerCompatible( 8825 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8826 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8827 return Sema::IncompatibleBlockPointer; 8828 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8829 return Sema::IncompatibleBlockPointer; 8830 8831 return ConvTy; 8832 } 8833 8834 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8835 /// for assignment compatibility. 8836 static Sema::AssignConvertType 8837 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8838 QualType RHSType) { 8839 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8840 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8841 8842 if (LHSType->isObjCBuiltinType()) { 8843 // Class is not compatible with ObjC object pointers. 8844 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8845 !RHSType->isObjCQualifiedClassType()) 8846 return Sema::IncompatiblePointer; 8847 return Sema::Compatible; 8848 } 8849 if (RHSType->isObjCBuiltinType()) { 8850 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8851 !LHSType->isObjCQualifiedClassType()) 8852 return Sema::IncompatiblePointer; 8853 return Sema::Compatible; 8854 } 8855 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8856 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8857 8858 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8859 // make an exception for id<P> 8860 !LHSType->isObjCQualifiedIdType()) 8861 return Sema::CompatiblePointerDiscardsQualifiers; 8862 8863 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8864 return Sema::Compatible; 8865 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8866 return Sema::IncompatibleObjCQualifiedId; 8867 return Sema::IncompatiblePointer; 8868 } 8869 8870 Sema::AssignConvertType 8871 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8872 QualType LHSType, QualType RHSType) { 8873 // Fake up an opaque expression. We don't actually care about what 8874 // cast operations are required, so if CheckAssignmentConstraints 8875 // adds casts to this they'll be wasted, but fortunately that doesn't 8876 // usually happen on valid code. 8877 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8878 ExprResult RHSPtr = &RHSExpr; 8879 CastKind K; 8880 8881 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8882 } 8883 8884 /// This helper function returns true if QT is a vector type that has element 8885 /// type ElementType. 8886 static bool isVector(QualType QT, QualType ElementType) { 8887 if (const VectorType *VT = QT->getAs<VectorType>()) 8888 return VT->getElementType().getCanonicalType() == ElementType; 8889 return false; 8890 } 8891 8892 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8893 /// has code to accommodate several GCC extensions when type checking 8894 /// pointers. Here are some objectionable examples that GCC considers warnings: 8895 /// 8896 /// int a, *pint; 8897 /// short *pshort; 8898 /// struct foo *pfoo; 8899 /// 8900 /// pint = pshort; // warning: assignment from incompatible pointer type 8901 /// a = pint; // warning: assignment makes integer from pointer without a cast 8902 /// pint = a; // warning: assignment makes pointer from integer without a cast 8903 /// pint = pfoo; // warning: assignment from incompatible pointer type 8904 /// 8905 /// As a result, the code for dealing with pointers is more complex than the 8906 /// C99 spec dictates. 8907 /// 8908 /// Sets 'Kind' for any result kind except Incompatible. 8909 Sema::AssignConvertType 8910 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8911 CastKind &Kind, bool ConvertRHS) { 8912 QualType RHSType = RHS.get()->getType(); 8913 QualType OrigLHSType = LHSType; 8914 8915 // Get canonical types. We're not formatting these types, just comparing 8916 // them. 8917 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8918 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8919 8920 // Common case: no conversion required. 8921 if (LHSType == RHSType) { 8922 Kind = CK_NoOp; 8923 return Compatible; 8924 } 8925 8926 // If we have an atomic type, try a non-atomic assignment, then just add an 8927 // atomic qualification step. 8928 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8929 Sema::AssignConvertType result = 8930 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8931 if (result != Compatible) 8932 return result; 8933 if (Kind != CK_NoOp && ConvertRHS) 8934 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8935 Kind = CK_NonAtomicToAtomic; 8936 return Compatible; 8937 } 8938 8939 // If the left-hand side is a reference type, then we are in a 8940 // (rare!) case where we've allowed the use of references in C, 8941 // e.g., as a parameter type in a built-in function. In this case, 8942 // just make sure that the type referenced is compatible with the 8943 // right-hand side type. The caller is responsible for adjusting 8944 // LHSType so that the resulting expression does not have reference 8945 // type. 8946 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8947 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8948 Kind = CK_LValueBitCast; 8949 return Compatible; 8950 } 8951 return Incompatible; 8952 } 8953 8954 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8955 // to the same ExtVector type. 8956 if (LHSType->isExtVectorType()) { 8957 if (RHSType->isExtVectorType()) 8958 return Incompatible; 8959 if (RHSType->isArithmeticType()) { 8960 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8961 if (ConvertRHS) 8962 RHS = prepareVectorSplat(LHSType, RHS.get()); 8963 Kind = CK_VectorSplat; 8964 return Compatible; 8965 } 8966 } 8967 8968 // Conversions to or from vector type. 8969 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8970 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8971 // Allow assignments of an AltiVec vector type to an equivalent GCC 8972 // vector type and vice versa 8973 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8974 Kind = CK_BitCast; 8975 return Compatible; 8976 } 8977 8978 // If we are allowing lax vector conversions, and LHS and RHS are both 8979 // vectors, the total size only needs to be the same. This is a bitcast; 8980 // no bits are changed but the result type is different. 8981 if (isLaxVectorConversion(RHSType, LHSType)) { 8982 Kind = CK_BitCast; 8983 return IncompatibleVectors; 8984 } 8985 } 8986 8987 // When the RHS comes from another lax conversion (e.g. binops between 8988 // scalars and vectors) the result is canonicalized as a vector. When the 8989 // LHS is also a vector, the lax is allowed by the condition above. Handle 8990 // the case where LHS is a scalar. 8991 if (LHSType->isScalarType()) { 8992 const VectorType *VecType = RHSType->getAs<VectorType>(); 8993 if (VecType && VecType->getNumElements() == 1 && 8994 isLaxVectorConversion(RHSType, LHSType)) { 8995 ExprResult *VecExpr = &RHS; 8996 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8997 Kind = CK_BitCast; 8998 return Compatible; 8999 } 9000 } 9001 9002 // Allow assignments between fixed-length and sizeless SVE vectors. 9003 if (((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9004 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) && 9005 Context.areCompatibleSveTypes(LHSType, RHSType)) { 9006 Kind = CK_BitCast; 9007 return Compatible; 9008 } 9009 9010 return Incompatible; 9011 } 9012 9013 // Diagnose attempts to convert between __float128 and long double where 9014 // such conversions currently can't be handled. 9015 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9016 return Incompatible; 9017 9018 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9019 // discards the imaginary part. 9020 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9021 !LHSType->getAs<ComplexType>()) 9022 return Incompatible; 9023 9024 // Arithmetic conversions. 9025 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9026 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9027 if (ConvertRHS) 9028 Kind = PrepareScalarCast(RHS, LHSType); 9029 return Compatible; 9030 } 9031 9032 // Conversions to normal pointers. 9033 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9034 // U* -> T* 9035 if (isa<PointerType>(RHSType)) { 9036 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9037 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9038 if (AddrSpaceL != AddrSpaceR) 9039 Kind = CK_AddressSpaceConversion; 9040 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9041 Kind = CK_NoOp; 9042 else 9043 Kind = CK_BitCast; 9044 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9045 } 9046 9047 // int -> T* 9048 if (RHSType->isIntegerType()) { 9049 Kind = CK_IntegralToPointer; // FIXME: null? 9050 return IntToPointer; 9051 } 9052 9053 // C pointers are not compatible with ObjC object pointers, 9054 // with two exceptions: 9055 if (isa<ObjCObjectPointerType>(RHSType)) { 9056 // - conversions to void* 9057 if (LHSPointer->getPointeeType()->isVoidType()) { 9058 Kind = CK_BitCast; 9059 return Compatible; 9060 } 9061 9062 // - conversions from 'Class' to the redefinition type 9063 if (RHSType->isObjCClassType() && 9064 Context.hasSameType(LHSType, 9065 Context.getObjCClassRedefinitionType())) { 9066 Kind = CK_BitCast; 9067 return Compatible; 9068 } 9069 9070 Kind = CK_BitCast; 9071 return IncompatiblePointer; 9072 } 9073 9074 // U^ -> void* 9075 if (RHSType->getAs<BlockPointerType>()) { 9076 if (LHSPointer->getPointeeType()->isVoidType()) { 9077 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9078 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9079 ->getPointeeType() 9080 .getAddressSpace(); 9081 Kind = 9082 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9083 return Compatible; 9084 } 9085 } 9086 9087 return Incompatible; 9088 } 9089 9090 // Conversions to block pointers. 9091 if (isa<BlockPointerType>(LHSType)) { 9092 // U^ -> T^ 9093 if (RHSType->isBlockPointerType()) { 9094 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9095 ->getPointeeType() 9096 .getAddressSpace(); 9097 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9098 ->getPointeeType() 9099 .getAddressSpace(); 9100 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9101 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9102 } 9103 9104 // int or null -> T^ 9105 if (RHSType->isIntegerType()) { 9106 Kind = CK_IntegralToPointer; // FIXME: null 9107 return IntToBlockPointer; 9108 } 9109 9110 // id -> T^ 9111 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9112 Kind = CK_AnyPointerToBlockPointerCast; 9113 return Compatible; 9114 } 9115 9116 // void* -> T^ 9117 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9118 if (RHSPT->getPointeeType()->isVoidType()) { 9119 Kind = CK_AnyPointerToBlockPointerCast; 9120 return Compatible; 9121 } 9122 9123 return Incompatible; 9124 } 9125 9126 // Conversions to Objective-C pointers. 9127 if (isa<ObjCObjectPointerType>(LHSType)) { 9128 // A* -> B* 9129 if (RHSType->isObjCObjectPointerType()) { 9130 Kind = CK_BitCast; 9131 Sema::AssignConvertType result = 9132 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9133 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9134 result == Compatible && 9135 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9136 result = IncompatibleObjCWeakRef; 9137 return result; 9138 } 9139 9140 // int or null -> A* 9141 if (RHSType->isIntegerType()) { 9142 Kind = CK_IntegralToPointer; // FIXME: null 9143 return IntToPointer; 9144 } 9145 9146 // In general, C pointers are not compatible with ObjC object pointers, 9147 // with two exceptions: 9148 if (isa<PointerType>(RHSType)) { 9149 Kind = CK_CPointerToObjCPointerCast; 9150 9151 // - conversions from 'void*' 9152 if (RHSType->isVoidPointerType()) { 9153 return Compatible; 9154 } 9155 9156 // - conversions to 'Class' from its redefinition type 9157 if (LHSType->isObjCClassType() && 9158 Context.hasSameType(RHSType, 9159 Context.getObjCClassRedefinitionType())) { 9160 return Compatible; 9161 } 9162 9163 return IncompatiblePointer; 9164 } 9165 9166 // Only under strict condition T^ is compatible with an Objective-C pointer. 9167 if (RHSType->isBlockPointerType() && 9168 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9169 if (ConvertRHS) 9170 maybeExtendBlockObject(RHS); 9171 Kind = CK_BlockPointerToObjCPointerCast; 9172 return Compatible; 9173 } 9174 9175 return Incompatible; 9176 } 9177 9178 // Conversions from pointers that are not covered by the above. 9179 if (isa<PointerType>(RHSType)) { 9180 // T* -> _Bool 9181 if (LHSType == Context.BoolTy) { 9182 Kind = CK_PointerToBoolean; 9183 return Compatible; 9184 } 9185 9186 // T* -> int 9187 if (LHSType->isIntegerType()) { 9188 Kind = CK_PointerToIntegral; 9189 return PointerToInt; 9190 } 9191 9192 return Incompatible; 9193 } 9194 9195 // Conversions from Objective-C pointers that are not covered by the above. 9196 if (isa<ObjCObjectPointerType>(RHSType)) { 9197 // T* -> _Bool 9198 if (LHSType == Context.BoolTy) { 9199 Kind = CK_PointerToBoolean; 9200 return Compatible; 9201 } 9202 9203 // T* -> int 9204 if (LHSType->isIntegerType()) { 9205 Kind = CK_PointerToIntegral; 9206 return PointerToInt; 9207 } 9208 9209 return Incompatible; 9210 } 9211 9212 // struct A -> struct B 9213 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9214 if (Context.typesAreCompatible(LHSType, RHSType)) { 9215 Kind = CK_NoOp; 9216 return Compatible; 9217 } 9218 } 9219 9220 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9221 Kind = CK_IntToOCLSampler; 9222 return Compatible; 9223 } 9224 9225 return Incompatible; 9226 } 9227 9228 /// Constructs a transparent union from an expression that is 9229 /// used to initialize the transparent union. 9230 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9231 ExprResult &EResult, QualType UnionType, 9232 FieldDecl *Field) { 9233 // Build an initializer list that designates the appropriate member 9234 // of the transparent union. 9235 Expr *E = EResult.get(); 9236 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9237 E, SourceLocation()); 9238 Initializer->setType(UnionType); 9239 Initializer->setInitializedFieldInUnion(Field); 9240 9241 // Build a compound literal constructing a value of the transparent 9242 // union type from this initializer list. 9243 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9244 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9245 VK_RValue, Initializer, false); 9246 } 9247 9248 Sema::AssignConvertType 9249 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9250 ExprResult &RHS) { 9251 QualType RHSType = RHS.get()->getType(); 9252 9253 // If the ArgType is a Union type, we want to handle a potential 9254 // transparent_union GCC extension. 9255 const RecordType *UT = ArgType->getAsUnionType(); 9256 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9257 return Incompatible; 9258 9259 // The field to initialize within the transparent union. 9260 RecordDecl *UD = UT->getDecl(); 9261 FieldDecl *InitField = nullptr; 9262 // It's compatible if the expression matches any of the fields. 9263 for (auto *it : UD->fields()) { 9264 if (it->getType()->isPointerType()) { 9265 // If the transparent union contains a pointer type, we allow: 9266 // 1) void pointer 9267 // 2) null pointer constant 9268 if (RHSType->isPointerType()) 9269 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9270 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9271 InitField = it; 9272 break; 9273 } 9274 9275 if (RHS.get()->isNullPointerConstant(Context, 9276 Expr::NPC_ValueDependentIsNull)) { 9277 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9278 CK_NullToPointer); 9279 InitField = it; 9280 break; 9281 } 9282 } 9283 9284 CastKind Kind; 9285 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9286 == Compatible) { 9287 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9288 InitField = it; 9289 break; 9290 } 9291 } 9292 9293 if (!InitField) 9294 return Incompatible; 9295 9296 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9297 return Compatible; 9298 } 9299 9300 Sema::AssignConvertType 9301 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9302 bool Diagnose, 9303 bool DiagnoseCFAudited, 9304 bool ConvertRHS) { 9305 // We need to be able to tell the caller whether we diagnosed a problem, if 9306 // they ask us to issue diagnostics. 9307 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9308 9309 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9310 // we can't avoid *all* modifications at the moment, so we need some somewhere 9311 // to put the updated value. 9312 ExprResult LocalRHS = CallerRHS; 9313 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9314 9315 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9316 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9317 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9318 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9319 Diag(RHS.get()->getExprLoc(), 9320 diag::warn_noderef_to_dereferenceable_pointer) 9321 << RHS.get()->getSourceRange(); 9322 } 9323 } 9324 } 9325 9326 if (getLangOpts().CPlusPlus) { 9327 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9328 // C++ 5.17p3: If the left operand is not of class type, the 9329 // expression is implicitly converted (C++ 4) to the 9330 // cv-unqualified type of the left operand. 9331 QualType RHSType = RHS.get()->getType(); 9332 if (Diagnose) { 9333 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9334 AA_Assigning); 9335 } else { 9336 ImplicitConversionSequence ICS = 9337 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9338 /*SuppressUserConversions=*/false, 9339 AllowedExplicit::None, 9340 /*InOverloadResolution=*/false, 9341 /*CStyle=*/false, 9342 /*AllowObjCWritebackConversion=*/false); 9343 if (ICS.isFailure()) 9344 return Incompatible; 9345 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9346 ICS, AA_Assigning); 9347 } 9348 if (RHS.isInvalid()) 9349 return Incompatible; 9350 Sema::AssignConvertType result = Compatible; 9351 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9352 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9353 result = IncompatibleObjCWeakRef; 9354 return result; 9355 } 9356 9357 // FIXME: Currently, we fall through and treat C++ classes like C 9358 // structures. 9359 // FIXME: We also fall through for atomics; not sure what should 9360 // happen there, though. 9361 } else if (RHS.get()->getType() == Context.OverloadTy) { 9362 // As a set of extensions to C, we support overloading on functions. These 9363 // functions need to be resolved here. 9364 DeclAccessPair DAP; 9365 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9366 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9367 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9368 else 9369 return Incompatible; 9370 } 9371 9372 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9373 // a null pointer constant. 9374 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9375 LHSType->isBlockPointerType()) && 9376 RHS.get()->isNullPointerConstant(Context, 9377 Expr::NPC_ValueDependentIsNull)) { 9378 if (Diagnose || ConvertRHS) { 9379 CastKind Kind; 9380 CXXCastPath Path; 9381 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9382 /*IgnoreBaseAccess=*/false, Diagnose); 9383 if (ConvertRHS) 9384 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9385 } 9386 return Compatible; 9387 } 9388 9389 // OpenCL queue_t type assignment. 9390 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9391 Context, Expr::NPC_ValueDependentIsNull)) { 9392 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9393 return Compatible; 9394 } 9395 9396 // This check seems unnatural, however it is necessary to ensure the proper 9397 // conversion of functions/arrays. If the conversion were done for all 9398 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9399 // expressions that suppress this implicit conversion (&, sizeof). 9400 // 9401 // Suppress this for references: C++ 8.5.3p5. 9402 if (!LHSType->isReferenceType()) { 9403 // FIXME: We potentially allocate here even if ConvertRHS is false. 9404 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9405 if (RHS.isInvalid()) 9406 return Incompatible; 9407 } 9408 CastKind Kind; 9409 Sema::AssignConvertType result = 9410 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9411 9412 // C99 6.5.16.1p2: The value of the right operand is converted to the 9413 // type of the assignment expression. 9414 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9415 // so that we can use references in built-in functions even in C. 9416 // The getNonReferenceType() call makes sure that the resulting expression 9417 // does not have reference type. 9418 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9419 QualType Ty = LHSType.getNonLValueExprType(Context); 9420 Expr *E = RHS.get(); 9421 9422 // Check for various Objective-C errors. If we are not reporting 9423 // diagnostics and just checking for errors, e.g., during overload 9424 // resolution, return Incompatible to indicate the failure. 9425 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9426 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9427 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9428 if (!Diagnose) 9429 return Incompatible; 9430 } 9431 if (getLangOpts().ObjC && 9432 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9433 E->getType(), E, Diagnose) || 9434 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9435 if (!Diagnose) 9436 return Incompatible; 9437 // Replace the expression with a corrected version and continue so we 9438 // can find further errors. 9439 RHS = E; 9440 return Compatible; 9441 } 9442 9443 if (ConvertRHS) 9444 RHS = ImpCastExprToType(E, Ty, Kind); 9445 } 9446 9447 return result; 9448 } 9449 9450 namespace { 9451 /// The original operand to an operator, prior to the application of the usual 9452 /// arithmetic conversions and converting the arguments of a builtin operator 9453 /// candidate. 9454 struct OriginalOperand { 9455 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9456 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9457 Op = MTE->getSubExpr(); 9458 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9459 Op = BTE->getSubExpr(); 9460 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9461 Orig = ICE->getSubExprAsWritten(); 9462 Conversion = ICE->getConversionFunction(); 9463 } 9464 } 9465 9466 QualType getType() const { return Orig->getType(); } 9467 9468 Expr *Orig; 9469 NamedDecl *Conversion; 9470 }; 9471 } 9472 9473 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9474 ExprResult &RHS) { 9475 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9476 9477 Diag(Loc, diag::err_typecheck_invalid_operands) 9478 << OrigLHS.getType() << OrigRHS.getType() 9479 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9480 9481 // If a user-defined conversion was applied to either of the operands prior 9482 // to applying the built-in operator rules, tell the user about it. 9483 if (OrigLHS.Conversion) { 9484 Diag(OrigLHS.Conversion->getLocation(), 9485 diag::note_typecheck_invalid_operands_converted) 9486 << 0 << LHS.get()->getType(); 9487 } 9488 if (OrigRHS.Conversion) { 9489 Diag(OrigRHS.Conversion->getLocation(), 9490 diag::note_typecheck_invalid_operands_converted) 9491 << 1 << RHS.get()->getType(); 9492 } 9493 9494 return QualType(); 9495 } 9496 9497 // Diagnose cases where a scalar was implicitly converted to a vector and 9498 // diagnose the underlying types. Otherwise, diagnose the error 9499 // as invalid vector logical operands for non-C++ cases. 9500 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9501 ExprResult &RHS) { 9502 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9503 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9504 9505 bool LHSNatVec = LHSType->isVectorType(); 9506 bool RHSNatVec = RHSType->isVectorType(); 9507 9508 if (!(LHSNatVec && RHSNatVec)) { 9509 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9510 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9511 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9512 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9513 << Vector->getSourceRange(); 9514 return QualType(); 9515 } 9516 9517 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9518 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9519 << RHS.get()->getSourceRange(); 9520 9521 return QualType(); 9522 } 9523 9524 /// Try to convert a value of non-vector type to a vector type by converting 9525 /// the type to the element type of the vector and then performing a splat. 9526 /// If the language is OpenCL, we only use conversions that promote scalar 9527 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9528 /// for float->int. 9529 /// 9530 /// OpenCL V2.0 6.2.6.p2: 9531 /// An error shall occur if any scalar operand type has greater rank 9532 /// than the type of the vector element. 9533 /// 9534 /// \param scalar - if non-null, actually perform the conversions 9535 /// \return true if the operation fails (but without diagnosing the failure) 9536 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9537 QualType scalarTy, 9538 QualType vectorEltTy, 9539 QualType vectorTy, 9540 unsigned &DiagID) { 9541 // The conversion to apply to the scalar before splatting it, 9542 // if necessary. 9543 CastKind scalarCast = CK_NoOp; 9544 9545 if (vectorEltTy->isIntegralType(S.Context)) { 9546 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9547 (scalarTy->isIntegerType() && 9548 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9549 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9550 return true; 9551 } 9552 if (!scalarTy->isIntegralType(S.Context)) 9553 return true; 9554 scalarCast = CK_IntegralCast; 9555 } else if (vectorEltTy->isRealFloatingType()) { 9556 if (scalarTy->isRealFloatingType()) { 9557 if (S.getLangOpts().OpenCL && 9558 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9559 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9560 return true; 9561 } 9562 scalarCast = CK_FloatingCast; 9563 } 9564 else if (scalarTy->isIntegralType(S.Context)) 9565 scalarCast = CK_IntegralToFloating; 9566 else 9567 return true; 9568 } else { 9569 return true; 9570 } 9571 9572 // Adjust scalar if desired. 9573 if (scalar) { 9574 if (scalarCast != CK_NoOp) 9575 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9576 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9577 } 9578 return false; 9579 } 9580 9581 /// Convert vector E to a vector with the same number of elements but different 9582 /// element type. 9583 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9584 const auto *VecTy = E->getType()->getAs<VectorType>(); 9585 assert(VecTy && "Expression E must be a vector"); 9586 QualType NewVecTy = S.Context.getVectorType(ElementType, 9587 VecTy->getNumElements(), 9588 VecTy->getVectorKind()); 9589 9590 // Look through the implicit cast. Return the subexpression if its type is 9591 // NewVecTy. 9592 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9593 if (ICE->getSubExpr()->getType() == NewVecTy) 9594 return ICE->getSubExpr(); 9595 9596 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9597 return S.ImpCastExprToType(E, NewVecTy, Cast); 9598 } 9599 9600 /// Test if a (constant) integer Int can be casted to another integer type 9601 /// IntTy without losing precision. 9602 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9603 QualType OtherIntTy) { 9604 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9605 9606 // Reject cases where the value of the Int is unknown as that would 9607 // possibly cause truncation, but accept cases where the scalar can be 9608 // demoted without loss of precision. 9609 Expr::EvalResult EVResult; 9610 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9611 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9612 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9613 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9614 9615 if (CstInt) { 9616 // If the scalar is constant and is of a higher order and has more active 9617 // bits that the vector element type, reject it. 9618 llvm::APSInt Result = EVResult.Val.getInt(); 9619 unsigned NumBits = IntSigned 9620 ? (Result.isNegative() ? Result.getMinSignedBits() 9621 : Result.getActiveBits()) 9622 : Result.getActiveBits(); 9623 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9624 return true; 9625 9626 // If the signedness of the scalar type and the vector element type 9627 // differs and the number of bits is greater than that of the vector 9628 // element reject it. 9629 return (IntSigned != OtherIntSigned && 9630 NumBits > S.Context.getIntWidth(OtherIntTy)); 9631 } 9632 9633 // Reject cases where the value of the scalar is not constant and it's 9634 // order is greater than that of the vector element type. 9635 return (Order < 0); 9636 } 9637 9638 /// Test if a (constant) integer Int can be casted to floating point type 9639 /// FloatTy without losing precision. 9640 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9641 QualType FloatTy) { 9642 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9643 9644 // Determine if the integer constant can be expressed as a floating point 9645 // number of the appropriate type. 9646 Expr::EvalResult EVResult; 9647 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9648 9649 uint64_t Bits = 0; 9650 if (CstInt) { 9651 // Reject constants that would be truncated if they were converted to 9652 // the floating point type. Test by simple to/from conversion. 9653 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9654 // could be avoided if there was a convertFromAPInt method 9655 // which could signal back if implicit truncation occurred. 9656 llvm::APSInt Result = EVResult.Val.getInt(); 9657 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9658 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9659 llvm::APFloat::rmTowardZero); 9660 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9661 !IntTy->hasSignedIntegerRepresentation()); 9662 bool Ignored = false; 9663 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9664 &Ignored); 9665 if (Result != ConvertBack) 9666 return true; 9667 } else { 9668 // Reject types that cannot be fully encoded into the mantissa of 9669 // the float. 9670 Bits = S.Context.getTypeSize(IntTy); 9671 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9672 S.Context.getFloatTypeSemantics(FloatTy)); 9673 if (Bits > FloatPrec) 9674 return true; 9675 } 9676 9677 return false; 9678 } 9679 9680 /// Attempt to convert and splat Scalar into a vector whose types matches 9681 /// Vector following GCC conversion rules. The rule is that implicit 9682 /// conversion can occur when Scalar can be casted to match Vector's element 9683 /// type without causing truncation of Scalar. 9684 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9685 ExprResult *Vector) { 9686 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9687 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9688 const VectorType *VT = VectorTy->getAs<VectorType>(); 9689 9690 assert(!isa<ExtVectorType>(VT) && 9691 "ExtVectorTypes should not be handled here!"); 9692 9693 QualType VectorEltTy = VT->getElementType(); 9694 9695 // Reject cases where the vector element type or the scalar element type are 9696 // not integral or floating point types. 9697 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9698 return true; 9699 9700 // The conversion to apply to the scalar before splatting it, 9701 // if necessary. 9702 CastKind ScalarCast = CK_NoOp; 9703 9704 // Accept cases where the vector elements are integers and the scalar is 9705 // an integer. 9706 // FIXME: Notionally if the scalar was a floating point value with a precise 9707 // integral representation, we could cast it to an appropriate integer 9708 // type and then perform the rest of the checks here. GCC will perform 9709 // this conversion in some cases as determined by the input language. 9710 // We should accept it on a language independent basis. 9711 if (VectorEltTy->isIntegralType(S.Context) && 9712 ScalarTy->isIntegralType(S.Context) && 9713 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9714 9715 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9716 return true; 9717 9718 ScalarCast = CK_IntegralCast; 9719 } else if (VectorEltTy->isIntegralType(S.Context) && 9720 ScalarTy->isRealFloatingType()) { 9721 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9722 ScalarCast = CK_FloatingToIntegral; 9723 else 9724 return true; 9725 } else if (VectorEltTy->isRealFloatingType()) { 9726 if (ScalarTy->isRealFloatingType()) { 9727 9728 // Reject cases where the scalar type is not a constant and has a higher 9729 // Order than the vector element type. 9730 llvm::APFloat Result(0.0); 9731 9732 // Determine whether this is a constant scalar. In the event that the 9733 // value is dependent (and thus cannot be evaluated by the constant 9734 // evaluator), skip the evaluation. This will then diagnose once the 9735 // expression is instantiated. 9736 bool CstScalar = Scalar->get()->isValueDependent() || 9737 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9738 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9739 if (!CstScalar && Order < 0) 9740 return true; 9741 9742 // If the scalar cannot be safely casted to the vector element type, 9743 // reject it. 9744 if (CstScalar) { 9745 bool Truncated = false; 9746 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9747 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9748 if (Truncated) 9749 return true; 9750 } 9751 9752 ScalarCast = CK_FloatingCast; 9753 } else if (ScalarTy->isIntegralType(S.Context)) { 9754 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9755 return true; 9756 9757 ScalarCast = CK_IntegralToFloating; 9758 } else 9759 return true; 9760 } else if (ScalarTy->isEnumeralType()) 9761 return true; 9762 9763 // Adjust scalar if desired. 9764 if (Scalar) { 9765 if (ScalarCast != CK_NoOp) 9766 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9767 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9768 } 9769 return false; 9770 } 9771 9772 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9773 SourceLocation Loc, bool IsCompAssign, 9774 bool AllowBothBool, 9775 bool AllowBoolConversions) { 9776 if (!IsCompAssign) { 9777 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9778 if (LHS.isInvalid()) 9779 return QualType(); 9780 } 9781 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9782 if (RHS.isInvalid()) 9783 return QualType(); 9784 9785 // For conversion purposes, we ignore any qualifiers. 9786 // For example, "const float" and "float" are equivalent. 9787 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9788 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9789 9790 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9791 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9792 assert(LHSVecType || RHSVecType); 9793 9794 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9795 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9796 return InvalidOperands(Loc, LHS, RHS); 9797 9798 // AltiVec-style "vector bool op vector bool" combinations are allowed 9799 // for some operators but not others. 9800 if (!AllowBothBool && 9801 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9802 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9803 return InvalidOperands(Loc, LHS, RHS); 9804 9805 // If the vector types are identical, return. 9806 if (Context.hasSameType(LHSType, RHSType)) 9807 return LHSType; 9808 9809 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9810 if (LHSVecType && RHSVecType && 9811 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9812 if (isa<ExtVectorType>(LHSVecType)) { 9813 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9814 return LHSType; 9815 } 9816 9817 if (!IsCompAssign) 9818 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9819 return RHSType; 9820 } 9821 9822 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9823 // can be mixed, with the result being the non-bool type. The non-bool 9824 // operand must have integer element type. 9825 if (AllowBoolConversions && LHSVecType && RHSVecType && 9826 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9827 (Context.getTypeSize(LHSVecType->getElementType()) == 9828 Context.getTypeSize(RHSVecType->getElementType()))) { 9829 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9830 LHSVecType->getElementType()->isIntegerType() && 9831 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9832 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9833 return LHSType; 9834 } 9835 if (!IsCompAssign && 9836 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9837 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9838 RHSVecType->getElementType()->isIntegerType()) { 9839 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9840 return RHSType; 9841 } 9842 } 9843 9844 // If there's a vector type and a scalar, try to convert the scalar to 9845 // the vector element type and splat. 9846 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9847 if (!RHSVecType) { 9848 if (isa<ExtVectorType>(LHSVecType)) { 9849 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9850 LHSVecType->getElementType(), LHSType, 9851 DiagID)) 9852 return LHSType; 9853 } else { 9854 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9855 return LHSType; 9856 } 9857 } 9858 if (!LHSVecType) { 9859 if (isa<ExtVectorType>(RHSVecType)) { 9860 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9861 LHSType, RHSVecType->getElementType(), 9862 RHSType, DiagID)) 9863 return RHSType; 9864 } else { 9865 if (LHS.get()->getValueKind() == VK_LValue || 9866 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9867 return RHSType; 9868 } 9869 } 9870 9871 // FIXME: The code below also handles conversion between vectors and 9872 // non-scalars, we should break this down into fine grained specific checks 9873 // and emit proper diagnostics. 9874 QualType VecType = LHSVecType ? LHSType : RHSType; 9875 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9876 QualType OtherType = LHSVecType ? RHSType : LHSType; 9877 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9878 if (isLaxVectorConversion(OtherType, VecType)) { 9879 // If we're allowing lax vector conversions, only the total (data) size 9880 // needs to be the same. For non compound assignment, if one of the types is 9881 // scalar, the result is always the vector type. 9882 if (!IsCompAssign) { 9883 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9884 return VecType; 9885 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9886 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9887 // type. Note that this is already done by non-compound assignments in 9888 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9889 // <1 x T> -> T. The result is also a vector type. 9890 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9891 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9892 ExprResult *RHSExpr = &RHS; 9893 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9894 return VecType; 9895 } 9896 } 9897 9898 // Okay, the expression is invalid. 9899 9900 // Returns true if the operands are SVE VLA and VLS types. 9901 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9902 const VectorType *VecType = SecondType->getAs<VectorType>(); 9903 return FirstType->isSizelessBuiltinType() && VecType && 9904 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9905 VecType->getVectorKind() == 9906 VectorType::SveFixedLengthPredicateVector); 9907 }; 9908 9909 // If there's a sizeless and fixed-length operand, diagnose that. 9910 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9911 Diag(Loc, diag::err_typecheck_vector_not_convertable_sizeless) 9912 << LHSType << RHSType; 9913 return QualType(); 9914 } 9915 9916 // If there's a non-vector, non-real operand, diagnose that. 9917 if ((!RHSVecType && !RHSType->isRealType()) || 9918 (!LHSVecType && !LHSType->isRealType())) { 9919 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9920 << LHSType << RHSType 9921 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9922 return QualType(); 9923 } 9924 9925 // OpenCL V1.1 6.2.6.p1: 9926 // If the operands are of more than one vector type, then an error shall 9927 // occur. Implicit conversions between vector types are not permitted, per 9928 // section 6.2.1. 9929 if (getLangOpts().OpenCL && 9930 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9931 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9932 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9933 << RHSType; 9934 return QualType(); 9935 } 9936 9937 9938 // If there is a vector type that is not a ExtVector and a scalar, we reach 9939 // this point if scalar could not be converted to the vector's element type 9940 // without truncation. 9941 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9942 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9943 QualType Scalar = LHSVecType ? RHSType : LHSType; 9944 QualType Vector = LHSVecType ? LHSType : RHSType; 9945 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9946 Diag(Loc, 9947 diag::err_typecheck_vector_not_convertable_implict_truncation) 9948 << ScalarOrVector << Scalar << Vector; 9949 9950 return QualType(); 9951 } 9952 9953 // Otherwise, use the generic diagnostic. 9954 Diag(Loc, DiagID) 9955 << LHSType << RHSType 9956 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9957 return QualType(); 9958 } 9959 9960 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9961 // expression. These are mainly cases where the null pointer is used as an 9962 // integer instead of a pointer. 9963 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9964 SourceLocation Loc, bool IsCompare) { 9965 // The canonical way to check for a GNU null is with isNullPointerConstant, 9966 // but we use a bit of a hack here for speed; this is a relatively 9967 // hot path, and isNullPointerConstant is slow. 9968 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9969 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9970 9971 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9972 9973 // Avoid analyzing cases where the result will either be invalid (and 9974 // diagnosed as such) or entirely valid and not something to warn about. 9975 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9976 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9977 return; 9978 9979 // Comparison operations would not make sense with a null pointer no matter 9980 // what the other expression is. 9981 if (!IsCompare) { 9982 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9983 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9984 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9985 return; 9986 } 9987 9988 // The rest of the operations only make sense with a null pointer 9989 // if the other expression is a pointer. 9990 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9991 NonNullType->canDecayToPointerType()) 9992 return; 9993 9994 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9995 << LHSNull /* LHS is NULL */ << NonNullType 9996 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9997 } 9998 9999 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10000 SourceLocation Loc) { 10001 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10002 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10003 if (!LUE || !RUE) 10004 return; 10005 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10006 RUE->getKind() != UETT_SizeOf) 10007 return; 10008 10009 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10010 QualType LHSTy = LHSArg->getType(); 10011 QualType RHSTy; 10012 10013 if (RUE->isArgumentType()) 10014 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10015 else 10016 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10017 10018 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10019 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10020 return; 10021 10022 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10023 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10024 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10025 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10026 << LHSArgDecl; 10027 } 10028 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10029 QualType ArrayElemTy = ArrayTy->getElementType(); 10030 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10031 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10032 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10033 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10034 return; 10035 S.Diag(Loc, diag::warn_division_sizeof_array) 10036 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10037 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10038 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10039 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10040 << LHSArgDecl; 10041 } 10042 10043 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10044 } 10045 } 10046 10047 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10048 ExprResult &RHS, 10049 SourceLocation Loc, bool IsDiv) { 10050 // Check for division/remainder by zero. 10051 Expr::EvalResult RHSValue; 10052 if (!RHS.get()->isValueDependent() && 10053 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10054 RHSValue.Val.getInt() == 0) 10055 S.DiagRuntimeBehavior(Loc, RHS.get(), 10056 S.PDiag(diag::warn_remainder_division_by_zero) 10057 << IsDiv << RHS.get()->getSourceRange()); 10058 } 10059 10060 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10061 SourceLocation Loc, 10062 bool IsCompAssign, bool IsDiv) { 10063 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10064 10065 if (LHS.get()->getType()->isVectorType() || 10066 RHS.get()->getType()->isVectorType()) 10067 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10068 /*AllowBothBool*/getLangOpts().AltiVec, 10069 /*AllowBoolConversions*/false); 10070 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10071 RHS.get()->getType()->isConstantMatrixType())) 10072 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10073 10074 QualType compType = UsualArithmeticConversions( 10075 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10076 if (LHS.isInvalid() || RHS.isInvalid()) 10077 return QualType(); 10078 10079 10080 if (compType.isNull() || !compType->isArithmeticType()) 10081 return InvalidOperands(Loc, LHS, RHS); 10082 if (IsDiv) { 10083 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10084 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10085 } 10086 return compType; 10087 } 10088 10089 QualType Sema::CheckRemainderOperands( 10090 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10091 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10092 10093 if (LHS.get()->getType()->isVectorType() || 10094 RHS.get()->getType()->isVectorType()) { 10095 if (LHS.get()->getType()->hasIntegerRepresentation() && 10096 RHS.get()->getType()->hasIntegerRepresentation()) 10097 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10098 /*AllowBothBool*/getLangOpts().AltiVec, 10099 /*AllowBoolConversions*/false); 10100 return InvalidOperands(Loc, LHS, RHS); 10101 } 10102 10103 QualType compType = UsualArithmeticConversions( 10104 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10105 if (LHS.isInvalid() || RHS.isInvalid()) 10106 return QualType(); 10107 10108 if (compType.isNull() || !compType->isIntegerType()) 10109 return InvalidOperands(Loc, LHS, RHS); 10110 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10111 return compType; 10112 } 10113 10114 /// Diagnose invalid arithmetic on two void pointers. 10115 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10116 Expr *LHSExpr, Expr *RHSExpr) { 10117 S.Diag(Loc, S.getLangOpts().CPlusPlus 10118 ? diag::err_typecheck_pointer_arith_void_type 10119 : diag::ext_gnu_void_ptr) 10120 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10121 << RHSExpr->getSourceRange(); 10122 } 10123 10124 /// Diagnose invalid arithmetic on a void pointer. 10125 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10126 Expr *Pointer) { 10127 S.Diag(Loc, S.getLangOpts().CPlusPlus 10128 ? diag::err_typecheck_pointer_arith_void_type 10129 : diag::ext_gnu_void_ptr) 10130 << 0 /* one pointer */ << Pointer->getSourceRange(); 10131 } 10132 10133 /// Diagnose invalid arithmetic on a null pointer. 10134 /// 10135 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10136 /// idiom, which we recognize as a GNU extension. 10137 /// 10138 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10139 Expr *Pointer, bool IsGNUIdiom) { 10140 if (IsGNUIdiom) 10141 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10142 << Pointer->getSourceRange(); 10143 else 10144 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10145 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10146 } 10147 10148 /// Diagnose invalid arithmetic on two function pointers. 10149 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10150 Expr *LHS, Expr *RHS) { 10151 assert(LHS->getType()->isAnyPointerType()); 10152 assert(RHS->getType()->isAnyPointerType()); 10153 S.Diag(Loc, S.getLangOpts().CPlusPlus 10154 ? diag::err_typecheck_pointer_arith_function_type 10155 : diag::ext_gnu_ptr_func_arith) 10156 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10157 // We only show the second type if it differs from the first. 10158 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10159 RHS->getType()) 10160 << RHS->getType()->getPointeeType() 10161 << LHS->getSourceRange() << RHS->getSourceRange(); 10162 } 10163 10164 /// Diagnose invalid arithmetic on a function pointer. 10165 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10166 Expr *Pointer) { 10167 assert(Pointer->getType()->isAnyPointerType()); 10168 S.Diag(Loc, S.getLangOpts().CPlusPlus 10169 ? diag::err_typecheck_pointer_arith_function_type 10170 : diag::ext_gnu_ptr_func_arith) 10171 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10172 << 0 /* one pointer, so only one type */ 10173 << Pointer->getSourceRange(); 10174 } 10175 10176 /// Emit error if Operand is incomplete pointer type 10177 /// 10178 /// \returns True if pointer has incomplete type 10179 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10180 Expr *Operand) { 10181 QualType ResType = Operand->getType(); 10182 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10183 ResType = ResAtomicType->getValueType(); 10184 10185 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10186 QualType PointeeTy = ResType->getPointeeType(); 10187 return S.RequireCompleteSizedType( 10188 Loc, PointeeTy, 10189 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10190 Operand->getSourceRange()); 10191 } 10192 10193 /// Check the validity of an arithmetic pointer operand. 10194 /// 10195 /// If the operand has pointer type, this code will check for pointer types 10196 /// which are invalid in arithmetic operations. These will be diagnosed 10197 /// appropriately, including whether or not the use is supported as an 10198 /// extension. 10199 /// 10200 /// \returns True when the operand is valid to use (even if as an extension). 10201 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10202 Expr *Operand) { 10203 QualType ResType = Operand->getType(); 10204 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10205 ResType = ResAtomicType->getValueType(); 10206 10207 if (!ResType->isAnyPointerType()) return true; 10208 10209 QualType PointeeTy = ResType->getPointeeType(); 10210 if (PointeeTy->isVoidType()) { 10211 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10212 return !S.getLangOpts().CPlusPlus; 10213 } 10214 if (PointeeTy->isFunctionType()) { 10215 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10216 return !S.getLangOpts().CPlusPlus; 10217 } 10218 10219 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10220 10221 return true; 10222 } 10223 10224 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10225 /// operands. 10226 /// 10227 /// This routine will diagnose any invalid arithmetic on pointer operands much 10228 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10229 /// for emitting a single diagnostic even for operations where both LHS and RHS 10230 /// are (potentially problematic) pointers. 10231 /// 10232 /// \returns True when the operand is valid to use (even if as an extension). 10233 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10234 Expr *LHSExpr, Expr *RHSExpr) { 10235 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10236 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10237 if (!isLHSPointer && !isRHSPointer) return true; 10238 10239 QualType LHSPointeeTy, RHSPointeeTy; 10240 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10241 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10242 10243 // if both are pointers check if operation is valid wrt address spaces 10244 if (isLHSPointer && isRHSPointer) { 10245 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10246 S.Diag(Loc, 10247 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10248 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10249 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10250 return false; 10251 } 10252 } 10253 10254 // Check for arithmetic on pointers to incomplete types. 10255 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10256 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10257 if (isLHSVoidPtr || isRHSVoidPtr) { 10258 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10259 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10260 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10261 10262 return !S.getLangOpts().CPlusPlus; 10263 } 10264 10265 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10266 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10267 if (isLHSFuncPtr || isRHSFuncPtr) { 10268 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10269 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10270 RHSExpr); 10271 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10272 10273 return !S.getLangOpts().CPlusPlus; 10274 } 10275 10276 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10277 return false; 10278 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10279 return false; 10280 10281 return true; 10282 } 10283 10284 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10285 /// literal. 10286 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10287 Expr *LHSExpr, Expr *RHSExpr) { 10288 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10289 Expr* IndexExpr = RHSExpr; 10290 if (!StrExpr) { 10291 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10292 IndexExpr = LHSExpr; 10293 } 10294 10295 bool IsStringPlusInt = StrExpr && 10296 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10297 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10298 return; 10299 10300 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10301 Self.Diag(OpLoc, diag::warn_string_plus_int) 10302 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10303 10304 // Only print a fixit for "str" + int, not for int + "str". 10305 if (IndexExpr == RHSExpr) { 10306 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10307 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10308 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10309 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10310 << FixItHint::CreateInsertion(EndLoc, "]"); 10311 } else 10312 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10313 } 10314 10315 /// Emit a warning when adding a char literal to a string. 10316 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10317 Expr *LHSExpr, Expr *RHSExpr) { 10318 const Expr *StringRefExpr = LHSExpr; 10319 const CharacterLiteral *CharExpr = 10320 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10321 10322 if (!CharExpr) { 10323 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10324 StringRefExpr = RHSExpr; 10325 } 10326 10327 if (!CharExpr || !StringRefExpr) 10328 return; 10329 10330 const QualType StringType = StringRefExpr->getType(); 10331 10332 // Return if not a PointerType. 10333 if (!StringType->isAnyPointerType()) 10334 return; 10335 10336 // Return if not a CharacterType. 10337 if (!StringType->getPointeeType()->isAnyCharacterType()) 10338 return; 10339 10340 ASTContext &Ctx = Self.getASTContext(); 10341 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10342 10343 const QualType CharType = CharExpr->getType(); 10344 if (!CharType->isAnyCharacterType() && 10345 CharType->isIntegerType() && 10346 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10347 Self.Diag(OpLoc, diag::warn_string_plus_char) 10348 << DiagRange << Ctx.CharTy; 10349 } else { 10350 Self.Diag(OpLoc, diag::warn_string_plus_char) 10351 << DiagRange << CharExpr->getType(); 10352 } 10353 10354 // Only print a fixit for str + char, not for char + str. 10355 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10356 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10357 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10358 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10359 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10360 << FixItHint::CreateInsertion(EndLoc, "]"); 10361 } else { 10362 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10363 } 10364 } 10365 10366 /// Emit error when two pointers are incompatible. 10367 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10368 Expr *LHSExpr, Expr *RHSExpr) { 10369 assert(LHSExpr->getType()->isAnyPointerType()); 10370 assert(RHSExpr->getType()->isAnyPointerType()); 10371 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10372 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10373 << RHSExpr->getSourceRange(); 10374 } 10375 10376 // C99 6.5.6 10377 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10378 SourceLocation Loc, BinaryOperatorKind Opc, 10379 QualType* CompLHSTy) { 10380 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10381 10382 if (LHS.get()->getType()->isVectorType() || 10383 RHS.get()->getType()->isVectorType()) { 10384 QualType compType = CheckVectorOperands( 10385 LHS, RHS, Loc, CompLHSTy, 10386 /*AllowBothBool*/getLangOpts().AltiVec, 10387 /*AllowBoolConversions*/getLangOpts().ZVector); 10388 if (CompLHSTy) *CompLHSTy = compType; 10389 return compType; 10390 } 10391 10392 if (LHS.get()->getType()->isConstantMatrixType() || 10393 RHS.get()->getType()->isConstantMatrixType()) { 10394 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10395 } 10396 10397 QualType compType = UsualArithmeticConversions( 10398 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10399 if (LHS.isInvalid() || RHS.isInvalid()) 10400 return QualType(); 10401 10402 // Diagnose "string literal" '+' int and string '+' "char literal". 10403 if (Opc == BO_Add) { 10404 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10405 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10406 } 10407 10408 // handle the common case first (both operands are arithmetic). 10409 if (!compType.isNull() && compType->isArithmeticType()) { 10410 if (CompLHSTy) *CompLHSTy = compType; 10411 return compType; 10412 } 10413 10414 // Type-checking. Ultimately the pointer's going to be in PExp; 10415 // note that we bias towards the LHS being the pointer. 10416 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10417 10418 bool isObjCPointer; 10419 if (PExp->getType()->isPointerType()) { 10420 isObjCPointer = false; 10421 } else if (PExp->getType()->isObjCObjectPointerType()) { 10422 isObjCPointer = true; 10423 } else { 10424 std::swap(PExp, IExp); 10425 if (PExp->getType()->isPointerType()) { 10426 isObjCPointer = false; 10427 } else if (PExp->getType()->isObjCObjectPointerType()) { 10428 isObjCPointer = true; 10429 } else { 10430 return InvalidOperands(Loc, LHS, RHS); 10431 } 10432 } 10433 assert(PExp->getType()->isAnyPointerType()); 10434 10435 if (!IExp->getType()->isIntegerType()) 10436 return InvalidOperands(Loc, LHS, RHS); 10437 10438 // Adding to a null pointer results in undefined behavior. 10439 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10440 Context, Expr::NPC_ValueDependentIsNotNull)) { 10441 // In C++ adding zero to a null pointer is defined. 10442 Expr::EvalResult KnownVal; 10443 if (!getLangOpts().CPlusPlus || 10444 (!IExp->isValueDependent() && 10445 (!IExp->EvaluateAsInt(KnownVal, Context) || 10446 KnownVal.Val.getInt() != 0))) { 10447 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10448 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10449 Context, BO_Add, PExp, IExp); 10450 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10451 } 10452 } 10453 10454 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10455 return QualType(); 10456 10457 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10458 return QualType(); 10459 10460 // Check array bounds for pointer arithemtic 10461 CheckArrayAccess(PExp, IExp); 10462 10463 if (CompLHSTy) { 10464 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10465 if (LHSTy.isNull()) { 10466 LHSTy = LHS.get()->getType(); 10467 if (LHSTy->isPromotableIntegerType()) 10468 LHSTy = Context.getPromotedIntegerType(LHSTy); 10469 } 10470 *CompLHSTy = LHSTy; 10471 } 10472 10473 return PExp->getType(); 10474 } 10475 10476 // C99 6.5.6 10477 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10478 SourceLocation Loc, 10479 QualType* CompLHSTy) { 10480 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10481 10482 if (LHS.get()->getType()->isVectorType() || 10483 RHS.get()->getType()->isVectorType()) { 10484 QualType compType = CheckVectorOperands( 10485 LHS, RHS, Loc, CompLHSTy, 10486 /*AllowBothBool*/getLangOpts().AltiVec, 10487 /*AllowBoolConversions*/getLangOpts().ZVector); 10488 if (CompLHSTy) *CompLHSTy = compType; 10489 return compType; 10490 } 10491 10492 if (LHS.get()->getType()->isConstantMatrixType() || 10493 RHS.get()->getType()->isConstantMatrixType()) { 10494 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10495 } 10496 10497 QualType compType = UsualArithmeticConversions( 10498 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10499 if (LHS.isInvalid() || RHS.isInvalid()) 10500 return QualType(); 10501 10502 // Enforce type constraints: C99 6.5.6p3. 10503 10504 // Handle the common case first (both operands are arithmetic). 10505 if (!compType.isNull() && compType->isArithmeticType()) { 10506 if (CompLHSTy) *CompLHSTy = compType; 10507 return compType; 10508 } 10509 10510 // Either ptr - int or ptr - ptr. 10511 if (LHS.get()->getType()->isAnyPointerType()) { 10512 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10513 10514 // Diagnose bad cases where we step over interface counts. 10515 if (LHS.get()->getType()->isObjCObjectPointerType() && 10516 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10517 return QualType(); 10518 10519 // The result type of a pointer-int computation is the pointer type. 10520 if (RHS.get()->getType()->isIntegerType()) { 10521 // Subtracting from a null pointer should produce a warning. 10522 // The last argument to the diagnose call says this doesn't match the 10523 // GNU int-to-pointer idiom. 10524 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10525 Expr::NPC_ValueDependentIsNotNull)) { 10526 // In C++ adding zero to a null pointer is defined. 10527 Expr::EvalResult KnownVal; 10528 if (!getLangOpts().CPlusPlus || 10529 (!RHS.get()->isValueDependent() && 10530 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10531 KnownVal.Val.getInt() != 0))) { 10532 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10533 } 10534 } 10535 10536 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10537 return QualType(); 10538 10539 // Check array bounds for pointer arithemtic 10540 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10541 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10542 10543 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10544 return LHS.get()->getType(); 10545 } 10546 10547 // Handle pointer-pointer subtractions. 10548 if (const PointerType *RHSPTy 10549 = RHS.get()->getType()->getAs<PointerType>()) { 10550 QualType rpointee = RHSPTy->getPointeeType(); 10551 10552 if (getLangOpts().CPlusPlus) { 10553 // Pointee types must be the same: C++ [expr.add] 10554 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10555 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10556 } 10557 } else { 10558 // Pointee types must be compatible C99 6.5.6p3 10559 if (!Context.typesAreCompatible( 10560 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10561 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10562 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10563 return QualType(); 10564 } 10565 } 10566 10567 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10568 LHS.get(), RHS.get())) 10569 return QualType(); 10570 10571 // FIXME: Add warnings for nullptr - ptr. 10572 10573 // The pointee type may have zero size. As an extension, a structure or 10574 // union may have zero size or an array may have zero length. In this 10575 // case subtraction does not make sense. 10576 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10577 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10578 if (ElementSize.isZero()) { 10579 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10580 << rpointee.getUnqualifiedType() 10581 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10582 } 10583 } 10584 10585 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10586 return Context.getPointerDiffType(); 10587 } 10588 } 10589 10590 return InvalidOperands(Loc, LHS, RHS); 10591 } 10592 10593 static bool isScopedEnumerationType(QualType T) { 10594 if (const EnumType *ET = T->getAs<EnumType>()) 10595 return ET->getDecl()->isScoped(); 10596 return false; 10597 } 10598 10599 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10600 SourceLocation Loc, BinaryOperatorKind Opc, 10601 QualType LHSType) { 10602 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10603 // so skip remaining warnings as we don't want to modify values within Sema. 10604 if (S.getLangOpts().OpenCL) 10605 return; 10606 10607 // Check right/shifter operand 10608 Expr::EvalResult RHSResult; 10609 if (RHS.get()->isValueDependent() || 10610 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10611 return; 10612 llvm::APSInt Right = RHSResult.Val.getInt(); 10613 10614 if (Right.isNegative()) { 10615 S.DiagRuntimeBehavior(Loc, RHS.get(), 10616 S.PDiag(diag::warn_shift_negative) 10617 << RHS.get()->getSourceRange()); 10618 return; 10619 } 10620 10621 QualType LHSExprType = LHS.get()->getType(); 10622 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10623 if (LHSExprType->isExtIntType()) 10624 LeftSize = S.Context.getIntWidth(LHSExprType); 10625 else if (LHSExprType->isFixedPointType()) { 10626 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10627 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10628 } 10629 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10630 if (Right.uge(LeftBits)) { 10631 S.DiagRuntimeBehavior(Loc, RHS.get(), 10632 S.PDiag(diag::warn_shift_gt_typewidth) 10633 << RHS.get()->getSourceRange()); 10634 return; 10635 } 10636 10637 // FIXME: We probably need to handle fixed point types specially here. 10638 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10639 return; 10640 10641 // When left shifting an ICE which is signed, we can check for overflow which 10642 // according to C++ standards prior to C++2a has undefined behavior 10643 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10644 // more than the maximum value representable in the result type, so never 10645 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10646 // expression is still probably a bug.) 10647 Expr::EvalResult LHSResult; 10648 if (LHS.get()->isValueDependent() || 10649 LHSType->hasUnsignedIntegerRepresentation() || 10650 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10651 return; 10652 llvm::APSInt Left = LHSResult.Val.getInt(); 10653 10654 // If LHS does not have a signed type and non-negative value 10655 // then, the behavior is undefined before C++2a. Warn about it. 10656 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10657 !S.getLangOpts().CPlusPlus20) { 10658 S.DiagRuntimeBehavior(Loc, LHS.get(), 10659 S.PDiag(diag::warn_shift_lhs_negative) 10660 << LHS.get()->getSourceRange()); 10661 return; 10662 } 10663 10664 llvm::APInt ResultBits = 10665 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10666 if (LeftBits.uge(ResultBits)) 10667 return; 10668 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10669 Result = Result.shl(Right); 10670 10671 // Print the bit representation of the signed integer as an unsigned 10672 // hexadecimal number. 10673 SmallString<40> HexResult; 10674 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10675 10676 // If we are only missing a sign bit, this is less likely to result in actual 10677 // bugs -- if the result is cast back to an unsigned type, it will have the 10678 // expected value. Thus we place this behind a different warning that can be 10679 // turned off separately if needed. 10680 if (LeftBits == ResultBits - 1) { 10681 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10682 << HexResult << LHSType 10683 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10684 return; 10685 } 10686 10687 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10688 << HexResult.str() << Result.getMinSignedBits() << LHSType 10689 << Left.getBitWidth() << LHS.get()->getSourceRange() 10690 << RHS.get()->getSourceRange(); 10691 } 10692 10693 /// Return the resulting type when a vector is shifted 10694 /// by a scalar or vector shift amount. 10695 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10696 SourceLocation Loc, bool IsCompAssign) { 10697 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10698 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10699 !LHS.get()->getType()->isVectorType()) { 10700 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10701 << RHS.get()->getType() << LHS.get()->getType() 10702 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10703 return QualType(); 10704 } 10705 10706 if (!IsCompAssign) { 10707 LHS = S.UsualUnaryConversions(LHS.get()); 10708 if (LHS.isInvalid()) return QualType(); 10709 } 10710 10711 RHS = S.UsualUnaryConversions(RHS.get()); 10712 if (RHS.isInvalid()) return QualType(); 10713 10714 QualType LHSType = LHS.get()->getType(); 10715 // Note that LHS might be a scalar because the routine calls not only in 10716 // OpenCL case. 10717 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10718 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10719 10720 // Note that RHS might not be a vector. 10721 QualType RHSType = RHS.get()->getType(); 10722 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10723 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10724 10725 // The operands need to be integers. 10726 if (!LHSEleType->isIntegerType()) { 10727 S.Diag(Loc, diag::err_typecheck_expect_int) 10728 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10729 return QualType(); 10730 } 10731 10732 if (!RHSEleType->isIntegerType()) { 10733 S.Diag(Loc, diag::err_typecheck_expect_int) 10734 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10735 return QualType(); 10736 } 10737 10738 if (!LHSVecTy) { 10739 assert(RHSVecTy); 10740 if (IsCompAssign) 10741 return RHSType; 10742 if (LHSEleType != RHSEleType) { 10743 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10744 LHSEleType = RHSEleType; 10745 } 10746 QualType VecTy = 10747 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10748 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10749 LHSType = VecTy; 10750 } else if (RHSVecTy) { 10751 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10752 // are applied component-wise. So if RHS is a vector, then ensure 10753 // that the number of elements is the same as LHS... 10754 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10755 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10756 << LHS.get()->getType() << RHS.get()->getType() 10757 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10758 return QualType(); 10759 } 10760 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10761 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10762 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10763 if (LHSBT != RHSBT && 10764 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10765 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10766 << LHS.get()->getType() << RHS.get()->getType() 10767 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10768 } 10769 } 10770 } else { 10771 // ...else expand RHS to match the number of elements in LHS. 10772 QualType VecTy = 10773 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10774 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10775 } 10776 10777 return LHSType; 10778 } 10779 10780 // C99 6.5.7 10781 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10782 SourceLocation Loc, BinaryOperatorKind Opc, 10783 bool IsCompAssign) { 10784 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10785 10786 // Vector shifts promote their scalar inputs to vector type. 10787 if (LHS.get()->getType()->isVectorType() || 10788 RHS.get()->getType()->isVectorType()) { 10789 if (LangOpts.ZVector) { 10790 // The shift operators for the z vector extensions work basically 10791 // like general shifts, except that neither the LHS nor the RHS is 10792 // allowed to be a "vector bool". 10793 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10794 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10795 return InvalidOperands(Loc, LHS, RHS); 10796 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10797 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10798 return InvalidOperands(Loc, LHS, RHS); 10799 } 10800 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10801 } 10802 10803 // Shifts don't perform usual arithmetic conversions, they just do integer 10804 // promotions on each operand. C99 6.5.7p3 10805 10806 // For the LHS, do usual unary conversions, but then reset them away 10807 // if this is a compound assignment. 10808 ExprResult OldLHS = LHS; 10809 LHS = UsualUnaryConversions(LHS.get()); 10810 if (LHS.isInvalid()) 10811 return QualType(); 10812 QualType LHSType = LHS.get()->getType(); 10813 if (IsCompAssign) LHS = OldLHS; 10814 10815 // The RHS is simpler. 10816 RHS = UsualUnaryConversions(RHS.get()); 10817 if (RHS.isInvalid()) 10818 return QualType(); 10819 QualType RHSType = RHS.get()->getType(); 10820 10821 // C99 6.5.7p2: Each of the operands shall have integer type. 10822 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10823 if ((!LHSType->isFixedPointOrIntegerType() && 10824 !LHSType->hasIntegerRepresentation()) || 10825 !RHSType->hasIntegerRepresentation()) 10826 return InvalidOperands(Loc, LHS, RHS); 10827 10828 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10829 // hasIntegerRepresentation() above instead of this. 10830 if (isScopedEnumerationType(LHSType) || 10831 isScopedEnumerationType(RHSType)) { 10832 return InvalidOperands(Loc, LHS, RHS); 10833 } 10834 // Sanity-check shift operands 10835 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10836 10837 // "The type of the result is that of the promoted left operand." 10838 return LHSType; 10839 } 10840 10841 /// Diagnose bad pointer comparisons. 10842 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10843 ExprResult &LHS, ExprResult &RHS, 10844 bool IsError) { 10845 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10846 : diag::ext_typecheck_comparison_of_distinct_pointers) 10847 << LHS.get()->getType() << RHS.get()->getType() 10848 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10849 } 10850 10851 /// Returns false if the pointers are converted to a composite type, 10852 /// true otherwise. 10853 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10854 ExprResult &LHS, ExprResult &RHS) { 10855 // C++ [expr.rel]p2: 10856 // [...] Pointer conversions (4.10) and qualification 10857 // conversions (4.4) are performed on pointer operands (or on 10858 // a pointer operand and a null pointer constant) to bring 10859 // them to their composite pointer type. [...] 10860 // 10861 // C++ [expr.eq]p1 uses the same notion for (in)equality 10862 // comparisons of pointers. 10863 10864 QualType LHSType = LHS.get()->getType(); 10865 QualType RHSType = RHS.get()->getType(); 10866 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10867 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10868 10869 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10870 if (T.isNull()) { 10871 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10872 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10873 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10874 else 10875 S.InvalidOperands(Loc, LHS, RHS); 10876 return true; 10877 } 10878 10879 return false; 10880 } 10881 10882 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10883 ExprResult &LHS, 10884 ExprResult &RHS, 10885 bool IsError) { 10886 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10887 : diag::ext_typecheck_comparison_of_fptr_to_void) 10888 << LHS.get()->getType() << RHS.get()->getType() 10889 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10890 } 10891 10892 static bool isObjCObjectLiteral(ExprResult &E) { 10893 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10894 case Stmt::ObjCArrayLiteralClass: 10895 case Stmt::ObjCDictionaryLiteralClass: 10896 case Stmt::ObjCStringLiteralClass: 10897 case Stmt::ObjCBoxedExprClass: 10898 return true; 10899 default: 10900 // Note that ObjCBoolLiteral is NOT an object literal! 10901 return false; 10902 } 10903 } 10904 10905 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10906 const ObjCObjectPointerType *Type = 10907 LHS->getType()->getAs<ObjCObjectPointerType>(); 10908 10909 // If this is not actually an Objective-C object, bail out. 10910 if (!Type) 10911 return false; 10912 10913 // Get the LHS object's interface type. 10914 QualType InterfaceType = Type->getPointeeType(); 10915 10916 // If the RHS isn't an Objective-C object, bail out. 10917 if (!RHS->getType()->isObjCObjectPointerType()) 10918 return false; 10919 10920 // Try to find the -isEqual: method. 10921 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10922 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10923 InterfaceType, 10924 /*IsInstance=*/true); 10925 if (!Method) { 10926 if (Type->isObjCIdType()) { 10927 // For 'id', just check the global pool. 10928 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10929 /*receiverId=*/true); 10930 } else { 10931 // Check protocols. 10932 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10933 /*IsInstance=*/true); 10934 } 10935 } 10936 10937 if (!Method) 10938 return false; 10939 10940 QualType T = Method->parameters()[0]->getType(); 10941 if (!T->isObjCObjectPointerType()) 10942 return false; 10943 10944 QualType R = Method->getReturnType(); 10945 if (!R->isScalarType()) 10946 return false; 10947 10948 return true; 10949 } 10950 10951 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10952 FromE = FromE->IgnoreParenImpCasts(); 10953 switch (FromE->getStmtClass()) { 10954 default: 10955 break; 10956 case Stmt::ObjCStringLiteralClass: 10957 // "string literal" 10958 return LK_String; 10959 case Stmt::ObjCArrayLiteralClass: 10960 // "array literal" 10961 return LK_Array; 10962 case Stmt::ObjCDictionaryLiteralClass: 10963 // "dictionary literal" 10964 return LK_Dictionary; 10965 case Stmt::BlockExprClass: 10966 return LK_Block; 10967 case Stmt::ObjCBoxedExprClass: { 10968 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10969 switch (Inner->getStmtClass()) { 10970 case Stmt::IntegerLiteralClass: 10971 case Stmt::FloatingLiteralClass: 10972 case Stmt::CharacterLiteralClass: 10973 case Stmt::ObjCBoolLiteralExprClass: 10974 case Stmt::CXXBoolLiteralExprClass: 10975 // "numeric literal" 10976 return LK_Numeric; 10977 case Stmt::ImplicitCastExprClass: { 10978 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10979 // Boolean literals can be represented by implicit casts. 10980 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10981 return LK_Numeric; 10982 break; 10983 } 10984 default: 10985 break; 10986 } 10987 return LK_Boxed; 10988 } 10989 } 10990 return LK_None; 10991 } 10992 10993 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10994 ExprResult &LHS, ExprResult &RHS, 10995 BinaryOperator::Opcode Opc){ 10996 Expr *Literal; 10997 Expr *Other; 10998 if (isObjCObjectLiteral(LHS)) { 10999 Literal = LHS.get(); 11000 Other = RHS.get(); 11001 } else { 11002 Literal = RHS.get(); 11003 Other = LHS.get(); 11004 } 11005 11006 // Don't warn on comparisons against nil. 11007 Other = Other->IgnoreParenCasts(); 11008 if (Other->isNullPointerConstant(S.getASTContext(), 11009 Expr::NPC_ValueDependentIsNotNull)) 11010 return; 11011 11012 // This should be kept in sync with warn_objc_literal_comparison. 11013 // LK_String should always be after the other literals, since it has its own 11014 // warning flag. 11015 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11016 assert(LiteralKind != Sema::LK_Block); 11017 if (LiteralKind == Sema::LK_None) { 11018 llvm_unreachable("Unknown Objective-C object literal kind"); 11019 } 11020 11021 if (LiteralKind == Sema::LK_String) 11022 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11023 << Literal->getSourceRange(); 11024 else 11025 S.Diag(Loc, diag::warn_objc_literal_comparison) 11026 << LiteralKind << Literal->getSourceRange(); 11027 11028 if (BinaryOperator::isEqualityOp(Opc) && 11029 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11030 SourceLocation Start = LHS.get()->getBeginLoc(); 11031 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11032 CharSourceRange OpRange = 11033 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11034 11035 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11036 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11037 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11038 << FixItHint::CreateInsertion(End, "]"); 11039 } 11040 } 11041 11042 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11043 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11044 ExprResult &RHS, SourceLocation Loc, 11045 BinaryOperatorKind Opc) { 11046 // Check that left hand side is !something. 11047 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11048 if (!UO || UO->getOpcode() != UO_LNot) return; 11049 11050 // Only check if the right hand side is non-bool arithmetic type. 11051 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11052 11053 // Make sure that the something in !something is not bool. 11054 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11055 if (SubExpr->isKnownToHaveBooleanValue()) return; 11056 11057 // Emit warning. 11058 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11059 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11060 << Loc << IsBitwiseOp; 11061 11062 // First note suggest !(x < y) 11063 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11064 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11065 FirstClose = S.getLocForEndOfToken(FirstClose); 11066 if (FirstClose.isInvalid()) 11067 FirstOpen = SourceLocation(); 11068 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11069 << IsBitwiseOp 11070 << FixItHint::CreateInsertion(FirstOpen, "(") 11071 << FixItHint::CreateInsertion(FirstClose, ")"); 11072 11073 // Second note suggests (!x) < y 11074 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11075 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11076 SecondClose = S.getLocForEndOfToken(SecondClose); 11077 if (SecondClose.isInvalid()) 11078 SecondOpen = SourceLocation(); 11079 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11080 << FixItHint::CreateInsertion(SecondOpen, "(") 11081 << FixItHint::CreateInsertion(SecondClose, ")"); 11082 } 11083 11084 // Returns true if E refers to a non-weak array. 11085 static bool checkForArray(const Expr *E) { 11086 const ValueDecl *D = nullptr; 11087 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11088 D = DR->getDecl(); 11089 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11090 if (Mem->isImplicitAccess()) 11091 D = Mem->getMemberDecl(); 11092 } 11093 if (!D) 11094 return false; 11095 return D->getType()->isArrayType() && !D->isWeak(); 11096 } 11097 11098 /// Diagnose some forms of syntactically-obvious tautological comparison. 11099 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11100 Expr *LHS, Expr *RHS, 11101 BinaryOperatorKind Opc) { 11102 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11103 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11104 11105 QualType LHSType = LHS->getType(); 11106 QualType RHSType = RHS->getType(); 11107 if (LHSType->hasFloatingRepresentation() || 11108 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11109 S.inTemplateInstantiation()) 11110 return; 11111 11112 // Comparisons between two array types are ill-formed for operator<=>, so 11113 // we shouldn't emit any additional warnings about it. 11114 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11115 return; 11116 11117 // For non-floating point types, check for self-comparisons of the form 11118 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11119 // often indicate logic errors in the program. 11120 // 11121 // NOTE: Don't warn about comparison expressions resulting from macro 11122 // expansion. Also don't warn about comparisons which are only self 11123 // comparisons within a template instantiation. The warnings should catch 11124 // obvious cases in the definition of the template anyways. The idea is to 11125 // warn when the typed comparison operator will always evaluate to the same 11126 // result. 11127 11128 // Used for indexing into %select in warn_comparison_always 11129 enum { 11130 AlwaysConstant, 11131 AlwaysTrue, 11132 AlwaysFalse, 11133 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11134 }; 11135 11136 // C++2a [depr.array.comp]: 11137 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11138 // operands of array type are deprecated. 11139 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11140 RHSStripped->getType()->isArrayType()) { 11141 S.Diag(Loc, diag::warn_depr_array_comparison) 11142 << LHS->getSourceRange() << RHS->getSourceRange() 11143 << LHSStripped->getType() << RHSStripped->getType(); 11144 // Carry on to produce the tautological comparison warning, if this 11145 // expression is potentially-evaluated, we can resolve the array to a 11146 // non-weak declaration, and so on. 11147 } 11148 11149 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11150 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11151 unsigned Result; 11152 switch (Opc) { 11153 case BO_EQ: 11154 case BO_LE: 11155 case BO_GE: 11156 Result = AlwaysTrue; 11157 break; 11158 case BO_NE: 11159 case BO_LT: 11160 case BO_GT: 11161 Result = AlwaysFalse; 11162 break; 11163 case BO_Cmp: 11164 Result = AlwaysEqual; 11165 break; 11166 default: 11167 Result = AlwaysConstant; 11168 break; 11169 } 11170 S.DiagRuntimeBehavior(Loc, nullptr, 11171 S.PDiag(diag::warn_comparison_always) 11172 << 0 /*self-comparison*/ 11173 << Result); 11174 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11175 // What is it always going to evaluate to? 11176 unsigned Result; 11177 switch (Opc) { 11178 case BO_EQ: // e.g. array1 == array2 11179 Result = AlwaysFalse; 11180 break; 11181 case BO_NE: // e.g. array1 != array2 11182 Result = AlwaysTrue; 11183 break; 11184 default: // e.g. array1 <= array2 11185 // The best we can say is 'a constant' 11186 Result = AlwaysConstant; 11187 break; 11188 } 11189 S.DiagRuntimeBehavior(Loc, nullptr, 11190 S.PDiag(diag::warn_comparison_always) 11191 << 1 /*array comparison*/ 11192 << Result); 11193 } 11194 } 11195 11196 if (isa<CastExpr>(LHSStripped)) 11197 LHSStripped = LHSStripped->IgnoreParenCasts(); 11198 if (isa<CastExpr>(RHSStripped)) 11199 RHSStripped = RHSStripped->IgnoreParenCasts(); 11200 11201 // Warn about comparisons against a string constant (unless the other 11202 // operand is null); the user probably wants string comparison function. 11203 Expr *LiteralString = nullptr; 11204 Expr *LiteralStringStripped = nullptr; 11205 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11206 !RHSStripped->isNullPointerConstant(S.Context, 11207 Expr::NPC_ValueDependentIsNull)) { 11208 LiteralString = LHS; 11209 LiteralStringStripped = LHSStripped; 11210 } else if ((isa<StringLiteral>(RHSStripped) || 11211 isa<ObjCEncodeExpr>(RHSStripped)) && 11212 !LHSStripped->isNullPointerConstant(S.Context, 11213 Expr::NPC_ValueDependentIsNull)) { 11214 LiteralString = RHS; 11215 LiteralStringStripped = RHSStripped; 11216 } 11217 11218 if (LiteralString) { 11219 S.DiagRuntimeBehavior(Loc, nullptr, 11220 S.PDiag(diag::warn_stringcompare) 11221 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11222 << LiteralString->getSourceRange()); 11223 } 11224 } 11225 11226 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11227 switch (CK) { 11228 default: { 11229 #ifndef NDEBUG 11230 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11231 << "\n"; 11232 #endif 11233 llvm_unreachable("unhandled cast kind"); 11234 } 11235 case CK_UserDefinedConversion: 11236 return ICK_Identity; 11237 case CK_LValueToRValue: 11238 return ICK_Lvalue_To_Rvalue; 11239 case CK_ArrayToPointerDecay: 11240 return ICK_Array_To_Pointer; 11241 case CK_FunctionToPointerDecay: 11242 return ICK_Function_To_Pointer; 11243 case CK_IntegralCast: 11244 return ICK_Integral_Conversion; 11245 case CK_FloatingCast: 11246 return ICK_Floating_Conversion; 11247 case CK_IntegralToFloating: 11248 case CK_FloatingToIntegral: 11249 return ICK_Floating_Integral; 11250 case CK_IntegralComplexCast: 11251 case CK_FloatingComplexCast: 11252 case CK_FloatingComplexToIntegralComplex: 11253 case CK_IntegralComplexToFloatingComplex: 11254 return ICK_Complex_Conversion; 11255 case CK_FloatingComplexToReal: 11256 case CK_FloatingRealToComplex: 11257 case CK_IntegralComplexToReal: 11258 case CK_IntegralRealToComplex: 11259 return ICK_Complex_Real; 11260 } 11261 } 11262 11263 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11264 QualType FromType, 11265 SourceLocation Loc) { 11266 // Check for a narrowing implicit conversion. 11267 StandardConversionSequence SCS; 11268 SCS.setAsIdentityConversion(); 11269 SCS.setToType(0, FromType); 11270 SCS.setToType(1, ToType); 11271 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11272 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11273 11274 APValue PreNarrowingValue; 11275 QualType PreNarrowingType; 11276 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11277 PreNarrowingType, 11278 /*IgnoreFloatToIntegralConversion*/ true)) { 11279 case NK_Dependent_Narrowing: 11280 // Implicit conversion to a narrower type, but the expression is 11281 // value-dependent so we can't tell whether it's actually narrowing. 11282 case NK_Not_Narrowing: 11283 return false; 11284 11285 case NK_Constant_Narrowing: 11286 // Implicit conversion to a narrower type, and the value is not a constant 11287 // expression. 11288 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11289 << /*Constant*/ 1 11290 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11291 return true; 11292 11293 case NK_Variable_Narrowing: 11294 // Implicit conversion to a narrower type, and the value is not a constant 11295 // expression. 11296 case NK_Type_Narrowing: 11297 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11298 << /*Constant*/ 0 << FromType << ToType; 11299 // TODO: It's not a constant expression, but what if the user intended it 11300 // to be? Can we produce notes to help them figure out why it isn't? 11301 return true; 11302 } 11303 llvm_unreachable("unhandled case in switch"); 11304 } 11305 11306 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11307 ExprResult &LHS, 11308 ExprResult &RHS, 11309 SourceLocation Loc) { 11310 QualType LHSType = LHS.get()->getType(); 11311 QualType RHSType = RHS.get()->getType(); 11312 // Dig out the original argument type and expression before implicit casts 11313 // were applied. These are the types/expressions we need to check the 11314 // [expr.spaceship] requirements against. 11315 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11316 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11317 QualType LHSStrippedType = LHSStripped.get()->getType(); 11318 QualType RHSStrippedType = RHSStripped.get()->getType(); 11319 11320 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11321 // other is not, the program is ill-formed. 11322 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11323 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11324 return QualType(); 11325 } 11326 11327 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11328 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11329 RHSStrippedType->isEnumeralType(); 11330 if (NumEnumArgs == 1) { 11331 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11332 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11333 if (OtherTy->hasFloatingRepresentation()) { 11334 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11335 return QualType(); 11336 } 11337 } 11338 if (NumEnumArgs == 2) { 11339 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11340 // type E, the operator yields the result of converting the operands 11341 // to the underlying type of E and applying <=> to the converted operands. 11342 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11343 S.InvalidOperands(Loc, LHS, RHS); 11344 return QualType(); 11345 } 11346 QualType IntType = 11347 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11348 assert(IntType->isArithmeticType()); 11349 11350 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11351 // promote the boolean type, and all other promotable integer types, to 11352 // avoid this. 11353 if (IntType->isPromotableIntegerType()) 11354 IntType = S.Context.getPromotedIntegerType(IntType); 11355 11356 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11357 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11358 LHSType = RHSType = IntType; 11359 } 11360 11361 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11362 // usual arithmetic conversions are applied to the operands. 11363 QualType Type = 11364 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11365 if (LHS.isInvalid() || RHS.isInvalid()) 11366 return QualType(); 11367 if (Type.isNull()) 11368 return S.InvalidOperands(Loc, LHS, RHS); 11369 11370 Optional<ComparisonCategoryType> CCT = 11371 getComparisonCategoryForBuiltinCmp(Type); 11372 if (!CCT) 11373 return S.InvalidOperands(Loc, LHS, RHS); 11374 11375 bool HasNarrowing = checkThreeWayNarrowingConversion( 11376 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11377 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11378 RHS.get()->getBeginLoc()); 11379 if (HasNarrowing) 11380 return QualType(); 11381 11382 assert(!Type.isNull() && "composite type for <=> has not been set"); 11383 11384 return S.CheckComparisonCategoryType( 11385 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11386 } 11387 11388 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11389 ExprResult &RHS, 11390 SourceLocation Loc, 11391 BinaryOperatorKind Opc) { 11392 if (Opc == BO_Cmp) 11393 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11394 11395 // C99 6.5.8p3 / C99 6.5.9p4 11396 QualType Type = 11397 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11398 if (LHS.isInvalid() || RHS.isInvalid()) 11399 return QualType(); 11400 if (Type.isNull()) 11401 return S.InvalidOperands(Loc, LHS, RHS); 11402 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11403 11404 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11405 return S.InvalidOperands(Loc, LHS, RHS); 11406 11407 // Check for comparisons of floating point operands using != and ==. 11408 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11409 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11410 11411 // The result of comparisons is 'bool' in C++, 'int' in C. 11412 return S.Context.getLogicalOperationType(); 11413 } 11414 11415 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11416 if (!NullE.get()->getType()->isAnyPointerType()) 11417 return; 11418 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11419 if (!E.get()->getType()->isAnyPointerType() && 11420 E.get()->isNullPointerConstant(Context, 11421 Expr::NPC_ValueDependentIsNotNull) == 11422 Expr::NPCK_ZeroExpression) { 11423 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11424 if (CL->getValue() == 0) 11425 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11426 << NullValue 11427 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11428 NullValue ? "NULL" : "(void *)0"); 11429 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11430 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11431 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11432 if (T == Context.CharTy) 11433 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11434 << NullValue 11435 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11436 NullValue ? "NULL" : "(void *)0"); 11437 } 11438 } 11439 } 11440 11441 // C99 6.5.8, C++ [expr.rel] 11442 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11443 SourceLocation Loc, 11444 BinaryOperatorKind Opc) { 11445 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11446 bool IsThreeWay = Opc == BO_Cmp; 11447 bool IsOrdered = IsRelational || IsThreeWay; 11448 auto IsAnyPointerType = [](ExprResult E) { 11449 QualType Ty = E.get()->getType(); 11450 return Ty->isPointerType() || Ty->isMemberPointerType(); 11451 }; 11452 11453 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11454 // type, array-to-pointer, ..., conversions are performed on both operands to 11455 // bring them to their composite type. 11456 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11457 // any type-related checks. 11458 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11459 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11460 if (LHS.isInvalid()) 11461 return QualType(); 11462 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11463 if (RHS.isInvalid()) 11464 return QualType(); 11465 } else { 11466 LHS = DefaultLvalueConversion(LHS.get()); 11467 if (LHS.isInvalid()) 11468 return QualType(); 11469 RHS = DefaultLvalueConversion(RHS.get()); 11470 if (RHS.isInvalid()) 11471 return QualType(); 11472 } 11473 11474 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11475 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11476 CheckPtrComparisonWithNullChar(LHS, RHS); 11477 CheckPtrComparisonWithNullChar(RHS, LHS); 11478 } 11479 11480 // Handle vector comparisons separately. 11481 if (LHS.get()->getType()->isVectorType() || 11482 RHS.get()->getType()->isVectorType()) 11483 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11484 11485 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11486 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11487 11488 QualType LHSType = LHS.get()->getType(); 11489 QualType RHSType = RHS.get()->getType(); 11490 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11491 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11492 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11493 11494 const Expr::NullPointerConstantKind LHSNullKind = 11495 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11496 const Expr::NullPointerConstantKind RHSNullKind = 11497 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11498 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11499 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11500 11501 auto computeResultTy = [&]() { 11502 if (Opc != BO_Cmp) 11503 return Context.getLogicalOperationType(); 11504 assert(getLangOpts().CPlusPlus); 11505 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11506 11507 QualType CompositeTy = LHS.get()->getType(); 11508 assert(!CompositeTy->isReferenceType()); 11509 11510 Optional<ComparisonCategoryType> CCT = 11511 getComparisonCategoryForBuiltinCmp(CompositeTy); 11512 if (!CCT) 11513 return InvalidOperands(Loc, LHS, RHS); 11514 11515 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11516 // P0946R0: Comparisons between a null pointer constant and an object 11517 // pointer result in std::strong_equality, which is ill-formed under 11518 // P1959R0. 11519 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11520 << (LHSIsNull ? LHS.get()->getSourceRange() 11521 : RHS.get()->getSourceRange()); 11522 return QualType(); 11523 } 11524 11525 return CheckComparisonCategoryType( 11526 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11527 }; 11528 11529 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11530 bool IsEquality = Opc == BO_EQ; 11531 if (RHSIsNull) 11532 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11533 RHS.get()->getSourceRange()); 11534 else 11535 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11536 LHS.get()->getSourceRange()); 11537 } 11538 11539 if ((LHSType->isIntegerType() && !LHSIsNull) || 11540 (RHSType->isIntegerType() && !RHSIsNull)) { 11541 // Skip normal pointer conversion checks in this case; we have better 11542 // diagnostics for this below. 11543 } else if (getLangOpts().CPlusPlus) { 11544 // Equality comparison of a function pointer to a void pointer is invalid, 11545 // but we allow it as an extension. 11546 // FIXME: If we really want to allow this, should it be part of composite 11547 // pointer type computation so it works in conditionals too? 11548 if (!IsOrdered && 11549 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11550 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11551 // This is a gcc extension compatibility comparison. 11552 // In a SFINAE context, we treat this as a hard error to maintain 11553 // conformance with the C++ standard. 11554 diagnoseFunctionPointerToVoidComparison( 11555 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11556 11557 if (isSFINAEContext()) 11558 return QualType(); 11559 11560 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11561 return computeResultTy(); 11562 } 11563 11564 // C++ [expr.eq]p2: 11565 // If at least one operand is a pointer [...] bring them to their 11566 // composite pointer type. 11567 // C++ [expr.spaceship]p6 11568 // If at least one of the operands is of pointer type, [...] bring them 11569 // to their composite pointer type. 11570 // C++ [expr.rel]p2: 11571 // If both operands are pointers, [...] bring them to their composite 11572 // pointer type. 11573 // For <=>, the only valid non-pointer types are arrays and functions, and 11574 // we already decayed those, so this is really the same as the relational 11575 // comparison rule. 11576 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11577 (IsOrdered ? 2 : 1) && 11578 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11579 RHSType->isObjCObjectPointerType()))) { 11580 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11581 return QualType(); 11582 return computeResultTy(); 11583 } 11584 } else if (LHSType->isPointerType() && 11585 RHSType->isPointerType()) { // C99 6.5.8p2 11586 // All of the following pointer-related warnings are GCC extensions, except 11587 // when handling null pointer constants. 11588 QualType LCanPointeeTy = 11589 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11590 QualType RCanPointeeTy = 11591 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11592 11593 // C99 6.5.9p2 and C99 6.5.8p2 11594 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11595 RCanPointeeTy.getUnqualifiedType())) { 11596 if (IsRelational) { 11597 // Pointers both need to point to complete or incomplete types 11598 if ((LCanPointeeTy->isIncompleteType() != 11599 RCanPointeeTy->isIncompleteType()) && 11600 !getLangOpts().C11) { 11601 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11602 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11603 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11604 << RCanPointeeTy->isIncompleteType(); 11605 } 11606 if (LCanPointeeTy->isFunctionType()) { 11607 // Valid unless a relational comparison of function pointers 11608 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11609 << LHSType << RHSType << LHS.get()->getSourceRange() 11610 << RHS.get()->getSourceRange(); 11611 } 11612 } 11613 } else if (!IsRelational && 11614 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11615 // Valid unless comparison between non-null pointer and function pointer 11616 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11617 && !LHSIsNull && !RHSIsNull) 11618 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11619 /*isError*/false); 11620 } else { 11621 // Invalid 11622 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11623 } 11624 if (LCanPointeeTy != RCanPointeeTy) { 11625 // Treat NULL constant as a special case in OpenCL. 11626 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11627 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11628 Diag(Loc, 11629 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11630 << LHSType << RHSType << 0 /* comparison */ 11631 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11632 } 11633 } 11634 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11635 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11636 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11637 : CK_BitCast; 11638 if (LHSIsNull && !RHSIsNull) 11639 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11640 else 11641 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11642 } 11643 return computeResultTy(); 11644 } 11645 11646 if (getLangOpts().CPlusPlus) { 11647 // C++ [expr.eq]p4: 11648 // Two operands of type std::nullptr_t or one operand of type 11649 // std::nullptr_t and the other a null pointer constant compare equal. 11650 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11651 if (LHSType->isNullPtrType()) { 11652 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11653 return computeResultTy(); 11654 } 11655 if (RHSType->isNullPtrType()) { 11656 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11657 return computeResultTy(); 11658 } 11659 } 11660 11661 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11662 // These aren't covered by the composite pointer type rules. 11663 if (!IsOrdered && RHSType->isNullPtrType() && 11664 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11665 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11666 return computeResultTy(); 11667 } 11668 if (!IsOrdered && LHSType->isNullPtrType() && 11669 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11670 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11671 return computeResultTy(); 11672 } 11673 11674 if (IsRelational && 11675 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11676 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11677 // HACK: Relational comparison of nullptr_t against a pointer type is 11678 // invalid per DR583, but we allow it within std::less<> and friends, 11679 // since otherwise common uses of it break. 11680 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11681 // friends to have std::nullptr_t overload candidates. 11682 DeclContext *DC = CurContext; 11683 if (isa<FunctionDecl>(DC)) 11684 DC = DC->getParent(); 11685 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11686 if (CTSD->isInStdNamespace() && 11687 llvm::StringSwitch<bool>(CTSD->getName()) 11688 .Cases("less", "less_equal", "greater", "greater_equal", true) 11689 .Default(false)) { 11690 if (RHSType->isNullPtrType()) 11691 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11692 else 11693 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11694 return computeResultTy(); 11695 } 11696 } 11697 } 11698 11699 // C++ [expr.eq]p2: 11700 // If at least one operand is a pointer to member, [...] bring them to 11701 // their composite pointer type. 11702 if (!IsOrdered && 11703 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11704 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11705 return QualType(); 11706 else 11707 return computeResultTy(); 11708 } 11709 } 11710 11711 // Handle block pointer types. 11712 if (!IsOrdered && LHSType->isBlockPointerType() && 11713 RHSType->isBlockPointerType()) { 11714 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11715 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11716 11717 if (!LHSIsNull && !RHSIsNull && 11718 !Context.typesAreCompatible(lpointee, rpointee)) { 11719 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11720 << LHSType << RHSType << LHS.get()->getSourceRange() 11721 << RHS.get()->getSourceRange(); 11722 } 11723 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11724 return computeResultTy(); 11725 } 11726 11727 // Allow block pointers to be compared with null pointer constants. 11728 if (!IsOrdered 11729 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11730 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11731 if (!LHSIsNull && !RHSIsNull) { 11732 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11733 ->getPointeeType()->isVoidType()) 11734 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11735 ->getPointeeType()->isVoidType()))) 11736 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11737 << LHSType << RHSType << LHS.get()->getSourceRange() 11738 << RHS.get()->getSourceRange(); 11739 } 11740 if (LHSIsNull && !RHSIsNull) 11741 LHS = ImpCastExprToType(LHS.get(), RHSType, 11742 RHSType->isPointerType() ? CK_BitCast 11743 : CK_AnyPointerToBlockPointerCast); 11744 else 11745 RHS = ImpCastExprToType(RHS.get(), LHSType, 11746 LHSType->isPointerType() ? CK_BitCast 11747 : CK_AnyPointerToBlockPointerCast); 11748 return computeResultTy(); 11749 } 11750 11751 if (LHSType->isObjCObjectPointerType() || 11752 RHSType->isObjCObjectPointerType()) { 11753 const PointerType *LPT = LHSType->getAs<PointerType>(); 11754 const PointerType *RPT = RHSType->getAs<PointerType>(); 11755 if (LPT || RPT) { 11756 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11757 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11758 11759 if (!LPtrToVoid && !RPtrToVoid && 11760 !Context.typesAreCompatible(LHSType, RHSType)) { 11761 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11762 /*isError*/false); 11763 } 11764 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11765 // the RHS, but we have test coverage for this behavior. 11766 // FIXME: Consider using convertPointersToCompositeType in C++. 11767 if (LHSIsNull && !RHSIsNull) { 11768 Expr *E = LHS.get(); 11769 if (getLangOpts().ObjCAutoRefCount) 11770 CheckObjCConversion(SourceRange(), RHSType, E, 11771 CCK_ImplicitConversion); 11772 LHS = ImpCastExprToType(E, RHSType, 11773 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11774 } 11775 else { 11776 Expr *E = RHS.get(); 11777 if (getLangOpts().ObjCAutoRefCount) 11778 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11779 /*Diagnose=*/true, 11780 /*DiagnoseCFAudited=*/false, Opc); 11781 RHS = ImpCastExprToType(E, LHSType, 11782 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11783 } 11784 return computeResultTy(); 11785 } 11786 if (LHSType->isObjCObjectPointerType() && 11787 RHSType->isObjCObjectPointerType()) { 11788 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11789 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11790 /*isError*/false); 11791 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11792 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11793 11794 if (LHSIsNull && !RHSIsNull) 11795 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11796 else 11797 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11798 return computeResultTy(); 11799 } 11800 11801 if (!IsOrdered && LHSType->isBlockPointerType() && 11802 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11803 LHS = ImpCastExprToType(LHS.get(), RHSType, 11804 CK_BlockPointerToObjCPointerCast); 11805 return computeResultTy(); 11806 } else if (!IsOrdered && 11807 LHSType->isBlockCompatibleObjCPointerType(Context) && 11808 RHSType->isBlockPointerType()) { 11809 RHS = ImpCastExprToType(RHS.get(), LHSType, 11810 CK_BlockPointerToObjCPointerCast); 11811 return computeResultTy(); 11812 } 11813 } 11814 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11815 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11816 unsigned DiagID = 0; 11817 bool isError = false; 11818 if (LangOpts.DebuggerSupport) { 11819 // Under a debugger, allow the comparison of pointers to integers, 11820 // since users tend to want to compare addresses. 11821 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11822 (RHSIsNull && RHSType->isIntegerType())) { 11823 if (IsOrdered) { 11824 isError = getLangOpts().CPlusPlus; 11825 DiagID = 11826 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11827 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11828 } 11829 } else if (getLangOpts().CPlusPlus) { 11830 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11831 isError = true; 11832 } else if (IsOrdered) 11833 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11834 else 11835 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11836 11837 if (DiagID) { 11838 Diag(Loc, DiagID) 11839 << LHSType << RHSType << LHS.get()->getSourceRange() 11840 << RHS.get()->getSourceRange(); 11841 if (isError) 11842 return QualType(); 11843 } 11844 11845 if (LHSType->isIntegerType()) 11846 LHS = ImpCastExprToType(LHS.get(), RHSType, 11847 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11848 else 11849 RHS = ImpCastExprToType(RHS.get(), LHSType, 11850 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11851 return computeResultTy(); 11852 } 11853 11854 // Handle block pointers. 11855 if (!IsOrdered && RHSIsNull 11856 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11857 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11858 return computeResultTy(); 11859 } 11860 if (!IsOrdered && LHSIsNull 11861 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11862 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11863 return computeResultTy(); 11864 } 11865 11866 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11867 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11868 return computeResultTy(); 11869 } 11870 11871 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11872 return computeResultTy(); 11873 } 11874 11875 if (LHSIsNull && RHSType->isQueueT()) { 11876 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11877 return computeResultTy(); 11878 } 11879 11880 if (LHSType->isQueueT() && RHSIsNull) { 11881 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11882 return computeResultTy(); 11883 } 11884 } 11885 11886 return InvalidOperands(Loc, LHS, RHS); 11887 } 11888 11889 // Return a signed ext_vector_type that is of identical size and number of 11890 // elements. For floating point vectors, return an integer type of identical 11891 // size and number of elements. In the non ext_vector_type case, search from 11892 // the largest type to the smallest type to avoid cases where long long == long, 11893 // where long gets picked over long long. 11894 QualType Sema::GetSignedVectorType(QualType V) { 11895 const VectorType *VTy = V->castAs<VectorType>(); 11896 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11897 11898 if (isa<ExtVectorType>(VTy)) { 11899 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11900 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11901 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11902 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11903 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11904 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11905 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11906 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11907 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11908 "Unhandled vector element size in vector compare"); 11909 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11910 } 11911 11912 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11913 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11914 VectorType::GenericVector); 11915 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11916 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11917 VectorType::GenericVector); 11918 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11919 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11920 VectorType::GenericVector); 11921 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11922 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11923 VectorType::GenericVector); 11924 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11925 "Unhandled vector element size in vector compare"); 11926 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11927 VectorType::GenericVector); 11928 } 11929 11930 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11931 /// operates on extended vector types. Instead of producing an IntTy result, 11932 /// like a scalar comparison, a vector comparison produces a vector of integer 11933 /// types. 11934 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11935 SourceLocation Loc, 11936 BinaryOperatorKind Opc) { 11937 if (Opc == BO_Cmp) { 11938 Diag(Loc, diag::err_three_way_vector_comparison); 11939 return QualType(); 11940 } 11941 11942 // Check to make sure we're operating on vectors of the same type and width, 11943 // Allowing one side to be a scalar of element type. 11944 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11945 /*AllowBothBool*/true, 11946 /*AllowBoolConversions*/getLangOpts().ZVector); 11947 if (vType.isNull()) 11948 return vType; 11949 11950 QualType LHSType = LHS.get()->getType(); 11951 11952 // If AltiVec, the comparison results in a numeric type, i.e. 11953 // bool for C++, int for C 11954 if (getLangOpts().AltiVec && 11955 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11956 return Context.getLogicalOperationType(); 11957 11958 // For non-floating point types, check for self-comparisons of the form 11959 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11960 // often indicate logic errors in the program. 11961 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11962 11963 // Check for comparisons of floating point operands using != and ==. 11964 if (BinaryOperator::isEqualityOp(Opc) && 11965 LHSType->hasFloatingRepresentation()) { 11966 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11967 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11968 } 11969 11970 // Return a signed type for the vector. 11971 return GetSignedVectorType(vType); 11972 } 11973 11974 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11975 const ExprResult &XorRHS, 11976 const SourceLocation Loc) { 11977 // Do not diagnose macros. 11978 if (Loc.isMacroID()) 11979 return; 11980 11981 bool Negative = false; 11982 bool ExplicitPlus = false; 11983 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11984 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11985 11986 if (!LHSInt) 11987 return; 11988 if (!RHSInt) { 11989 // Check negative literals. 11990 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11991 UnaryOperatorKind Opc = UO->getOpcode(); 11992 if (Opc != UO_Minus && Opc != UO_Plus) 11993 return; 11994 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11995 if (!RHSInt) 11996 return; 11997 Negative = (Opc == UO_Minus); 11998 ExplicitPlus = !Negative; 11999 } else { 12000 return; 12001 } 12002 } 12003 12004 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12005 llvm::APInt RightSideValue = RHSInt->getValue(); 12006 if (LeftSideValue != 2 && LeftSideValue != 10) 12007 return; 12008 12009 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12010 return; 12011 12012 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12013 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12014 llvm::StringRef ExprStr = 12015 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12016 12017 CharSourceRange XorRange = 12018 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12019 llvm::StringRef XorStr = 12020 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12021 // Do not diagnose if xor keyword/macro is used. 12022 if (XorStr == "xor") 12023 return; 12024 12025 std::string LHSStr = std::string(Lexer::getSourceText( 12026 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12027 S.getSourceManager(), S.getLangOpts())); 12028 std::string RHSStr = std::string(Lexer::getSourceText( 12029 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12030 S.getSourceManager(), S.getLangOpts())); 12031 12032 if (Negative) { 12033 RightSideValue = -RightSideValue; 12034 RHSStr = "-" + RHSStr; 12035 } else if (ExplicitPlus) { 12036 RHSStr = "+" + RHSStr; 12037 } 12038 12039 StringRef LHSStrRef = LHSStr; 12040 StringRef RHSStrRef = RHSStr; 12041 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12042 // literals. 12043 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12044 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12045 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12046 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12047 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12048 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12049 LHSStrRef.find('\'') != StringRef::npos || 12050 RHSStrRef.find('\'') != StringRef::npos) 12051 return; 12052 12053 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12054 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12055 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12056 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12057 std::string SuggestedExpr = "1 << " + RHSStr; 12058 bool Overflow = false; 12059 llvm::APInt One = (LeftSideValue - 1); 12060 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12061 if (Overflow) { 12062 if (RightSideIntValue < 64) 12063 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12064 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12065 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12066 else if (RightSideIntValue == 64) 12067 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12068 else 12069 return; 12070 } else { 12071 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12072 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12073 << PowValue.toString(10, true) 12074 << FixItHint::CreateReplacement( 12075 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12076 } 12077 12078 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12079 } else if (LeftSideValue == 10) { 12080 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12081 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12082 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12083 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12084 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12085 } 12086 } 12087 12088 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12089 SourceLocation Loc) { 12090 // Ensure that either both operands are of the same vector type, or 12091 // one operand is of a vector type and the other is of its element type. 12092 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12093 /*AllowBothBool*/true, 12094 /*AllowBoolConversions*/false); 12095 if (vType.isNull()) 12096 return InvalidOperands(Loc, LHS, RHS); 12097 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12098 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12099 return InvalidOperands(Loc, LHS, RHS); 12100 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12101 // usage of the logical operators && and || with vectors in C. This 12102 // check could be notionally dropped. 12103 if (!getLangOpts().CPlusPlus && 12104 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12105 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12106 12107 return GetSignedVectorType(LHS.get()->getType()); 12108 } 12109 12110 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12111 SourceLocation Loc, 12112 bool IsCompAssign) { 12113 if (!IsCompAssign) { 12114 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12115 if (LHS.isInvalid()) 12116 return QualType(); 12117 } 12118 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12119 if (RHS.isInvalid()) 12120 return QualType(); 12121 12122 // For conversion purposes, we ignore any qualifiers. 12123 // For example, "const float" and "float" are equivalent. 12124 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12125 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12126 12127 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12128 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12129 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12130 12131 if (Context.hasSameType(LHSType, RHSType)) 12132 return LHSType; 12133 12134 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12135 // case we have to return InvalidOperands. 12136 ExprResult OriginalLHS = LHS; 12137 ExprResult OriginalRHS = RHS; 12138 if (LHSMatType && !RHSMatType) { 12139 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12140 if (!RHS.isInvalid()) 12141 return LHSType; 12142 12143 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12144 } 12145 12146 if (!LHSMatType && RHSMatType) { 12147 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12148 if (!LHS.isInvalid()) 12149 return RHSType; 12150 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12151 } 12152 12153 return InvalidOperands(Loc, LHS, RHS); 12154 } 12155 12156 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12157 SourceLocation Loc, 12158 bool IsCompAssign) { 12159 if (!IsCompAssign) { 12160 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12161 if (LHS.isInvalid()) 12162 return QualType(); 12163 } 12164 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12165 if (RHS.isInvalid()) 12166 return QualType(); 12167 12168 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12169 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12170 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12171 12172 if (LHSMatType && RHSMatType) { 12173 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12174 return InvalidOperands(Loc, LHS, RHS); 12175 12176 if (!Context.hasSameType(LHSMatType->getElementType(), 12177 RHSMatType->getElementType())) 12178 return InvalidOperands(Loc, LHS, RHS); 12179 12180 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12181 LHSMatType->getNumRows(), 12182 RHSMatType->getNumColumns()); 12183 } 12184 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12185 } 12186 12187 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12188 SourceLocation Loc, 12189 BinaryOperatorKind Opc) { 12190 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12191 12192 bool IsCompAssign = 12193 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12194 12195 if (LHS.get()->getType()->isVectorType() || 12196 RHS.get()->getType()->isVectorType()) { 12197 if (LHS.get()->getType()->hasIntegerRepresentation() && 12198 RHS.get()->getType()->hasIntegerRepresentation()) 12199 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12200 /*AllowBothBool*/true, 12201 /*AllowBoolConversions*/getLangOpts().ZVector); 12202 return InvalidOperands(Loc, LHS, RHS); 12203 } 12204 12205 if (Opc == BO_And) 12206 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12207 12208 if (LHS.get()->getType()->hasFloatingRepresentation() || 12209 RHS.get()->getType()->hasFloatingRepresentation()) 12210 return InvalidOperands(Loc, LHS, RHS); 12211 12212 ExprResult LHSResult = LHS, RHSResult = RHS; 12213 QualType compType = UsualArithmeticConversions( 12214 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12215 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12216 return QualType(); 12217 LHS = LHSResult.get(); 12218 RHS = RHSResult.get(); 12219 12220 if (Opc == BO_Xor) 12221 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12222 12223 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12224 return compType; 12225 return InvalidOperands(Loc, LHS, RHS); 12226 } 12227 12228 // C99 6.5.[13,14] 12229 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12230 SourceLocation Loc, 12231 BinaryOperatorKind Opc) { 12232 // Check vector operands differently. 12233 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12234 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12235 12236 bool EnumConstantInBoolContext = false; 12237 for (const ExprResult &HS : {LHS, RHS}) { 12238 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12239 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12240 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12241 EnumConstantInBoolContext = true; 12242 } 12243 } 12244 12245 if (EnumConstantInBoolContext) 12246 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12247 12248 // Diagnose cases where the user write a logical and/or but probably meant a 12249 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12250 // is a constant. 12251 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12252 !LHS.get()->getType()->isBooleanType() && 12253 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12254 // Don't warn in macros or template instantiations. 12255 !Loc.isMacroID() && !inTemplateInstantiation()) { 12256 // If the RHS can be constant folded, and if it constant folds to something 12257 // that isn't 0 or 1 (which indicate a potential logical operation that 12258 // happened to fold to true/false) then warn. 12259 // Parens on the RHS are ignored. 12260 Expr::EvalResult EVResult; 12261 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12262 llvm::APSInt Result = EVResult.Val.getInt(); 12263 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12264 !RHS.get()->getExprLoc().isMacroID()) || 12265 (Result != 0 && Result != 1)) { 12266 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12267 << RHS.get()->getSourceRange() 12268 << (Opc == BO_LAnd ? "&&" : "||"); 12269 // Suggest replacing the logical operator with the bitwise version 12270 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12271 << (Opc == BO_LAnd ? "&" : "|") 12272 << FixItHint::CreateReplacement(SourceRange( 12273 Loc, getLocForEndOfToken(Loc)), 12274 Opc == BO_LAnd ? "&" : "|"); 12275 if (Opc == BO_LAnd) 12276 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12277 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12278 << FixItHint::CreateRemoval( 12279 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12280 RHS.get()->getEndLoc())); 12281 } 12282 } 12283 } 12284 12285 if (!Context.getLangOpts().CPlusPlus) { 12286 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12287 // not operate on the built-in scalar and vector float types. 12288 if (Context.getLangOpts().OpenCL && 12289 Context.getLangOpts().OpenCLVersion < 120) { 12290 if (LHS.get()->getType()->isFloatingType() || 12291 RHS.get()->getType()->isFloatingType()) 12292 return InvalidOperands(Loc, LHS, RHS); 12293 } 12294 12295 LHS = UsualUnaryConversions(LHS.get()); 12296 if (LHS.isInvalid()) 12297 return QualType(); 12298 12299 RHS = UsualUnaryConversions(RHS.get()); 12300 if (RHS.isInvalid()) 12301 return QualType(); 12302 12303 if (!LHS.get()->getType()->isScalarType() || 12304 !RHS.get()->getType()->isScalarType()) 12305 return InvalidOperands(Loc, LHS, RHS); 12306 12307 return Context.IntTy; 12308 } 12309 12310 // The following is safe because we only use this method for 12311 // non-overloadable operands. 12312 12313 // C++ [expr.log.and]p1 12314 // C++ [expr.log.or]p1 12315 // The operands are both contextually converted to type bool. 12316 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12317 if (LHSRes.isInvalid()) 12318 return InvalidOperands(Loc, LHS, RHS); 12319 LHS = LHSRes; 12320 12321 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12322 if (RHSRes.isInvalid()) 12323 return InvalidOperands(Loc, LHS, RHS); 12324 RHS = RHSRes; 12325 12326 // C++ [expr.log.and]p2 12327 // C++ [expr.log.or]p2 12328 // The result is a bool. 12329 return Context.BoolTy; 12330 } 12331 12332 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12333 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12334 if (!ME) return false; 12335 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12336 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12337 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12338 if (!Base) return false; 12339 return Base->getMethodDecl() != nullptr; 12340 } 12341 12342 /// Is the given expression (which must be 'const') a reference to a 12343 /// variable which was originally non-const, but which has become 12344 /// 'const' due to being captured within a block? 12345 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12346 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12347 assert(E->isLValue() && E->getType().isConstQualified()); 12348 E = E->IgnoreParens(); 12349 12350 // Must be a reference to a declaration from an enclosing scope. 12351 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12352 if (!DRE) return NCCK_None; 12353 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12354 12355 // The declaration must be a variable which is not declared 'const'. 12356 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12357 if (!var) return NCCK_None; 12358 if (var->getType().isConstQualified()) return NCCK_None; 12359 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12360 12361 // Decide whether the first capture was for a block or a lambda. 12362 DeclContext *DC = S.CurContext, *Prev = nullptr; 12363 // Decide whether the first capture was for a block or a lambda. 12364 while (DC) { 12365 // For init-capture, it is possible that the variable belongs to the 12366 // template pattern of the current context. 12367 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12368 if (var->isInitCapture() && 12369 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12370 break; 12371 if (DC == var->getDeclContext()) 12372 break; 12373 Prev = DC; 12374 DC = DC->getParent(); 12375 } 12376 // Unless we have an init-capture, we've gone one step too far. 12377 if (!var->isInitCapture()) 12378 DC = Prev; 12379 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12380 } 12381 12382 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12383 Ty = Ty.getNonReferenceType(); 12384 if (IsDereference && Ty->isPointerType()) 12385 Ty = Ty->getPointeeType(); 12386 return !Ty.isConstQualified(); 12387 } 12388 12389 // Update err_typecheck_assign_const and note_typecheck_assign_const 12390 // when this enum is changed. 12391 enum { 12392 ConstFunction, 12393 ConstVariable, 12394 ConstMember, 12395 ConstMethod, 12396 NestedConstMember, 12397 ConstUnknown, // Keep as last element 12398 }; 12399 12400 /// Emit the "read-only variable not assignable" error and print notes to give 12401 /// more information about why the variable is not assignable, such as pointing 12402 /// to the declaration of a const variable, showing that a method is const, or 12403 /// that the function is returning a const reference. 12404 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12405 SourceLocation Loc) { 12406 SourceRange ExprRange = E->getSourceRange(); 12407 12408 // Only emit one error on the first const found. All other consts will emit 12409 // a note to the error. 12410 bool DiagnosticEmitted = false; 12411 12412 // Track if the current expression is the result of a dereference, and if the 12413 // next checked expression is the result of a dereference. 12414 bool IsDereference = false; 12415 bool NextIsDereference = false; 12416 12417 // Loop to process MemberExpr chains. 12418 while (true) { 12419 IsDereference = NextIsDereference; 12420 12421 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12422 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12423 NextIsDereference = ME->isArrow(); 12424 const ValueDecl *VD = ME->getMemberDecl(); 12425 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12426 // Mutable fields can be modified even if the class is const. 12427 if (Field->isMutable()) { 12428 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12429 break; 12430 } 12431 12432 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12433 if (!DiagnosticEmitted) { 12434 S.Diag(Loc, diag::err_typecheck_assign_const) 12435 << ExprRange << ConstMember << false /*static*/ << Field 12436 << Field->getType(); 12437 DiagnosticEmitted = true; 12438 } 12439 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12440 << ConstMember << false /*static*/ << Field << Field->getType() 12441 << Field->getSourceRange(); 12442 } 12443 E = ME->getBase(); 12444 continue; 12445 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12446 if (VDecl->getType().isConstQualified()) { 12447 if (!DiagnosticEmitted) { 12448 S.Diag(Loc, diag::err_typecheck_assign_const) 12449 << ExprRange << ConstMember << true /*static*/ << VDecl 12450 << VDecl->getType(); 12451 DiagnosticEmitted = true; 12452 } 12453 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12454 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12455 << VDecl->getSourceRange(); 12456 } 12457 // Static fields do not inherit constness from parents. 12458 break; 12459 } 12460 break; // End MemberExpr 12461 } else if (const ArraySubscriptExpr *ASE = 12462 dyn_cast<ArraySubscriptExpr>(E)) { 12463 E = ASE->getBase()->IgnoreParenImpCasts(); 12464 continue; 12465 } else if (const ExtVectorElementExpr *EVE = 12466 dyn_cast<ExtVectorElementExpr>(E)) { 12467 E = EVE->getBase()->IgnoreParenImpCasts(); 12468 continue; 12469 } 12470 break; 12471 } 12472 12473 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12474 // Function calls 12475 const FunctionDecl *FD = CE->getDirectCallee(); 12476 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12477 if (!DiagnosticEmitted) { 12478 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12479 << ConstFunction << FD; 12480 DiagnosticEmitted = true; 12481 } 12482 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12483 diag::note_typecheck_assign_const) 12484 << ConstFunction << FD << FD->getReturnType() 12485 << FD->getReturnTypeSourceRange(); 12486 } 12487 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12488 // Point to variable declaration. 12489 if (const ValueDecl *VD = DRE->getDecl()) { 12490 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12491 if (!DiagnosticEmitted) { 12492 S.Diag(Loc, diag::err_typecheck_assign_const) 12493 << ExprRange << ConstVariable << VD << VD->getType(); 12494 DiagnosticEmitted = true; 12495 } 12496 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12497 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12498 } 12499 } 12500 } else if (isa<CXXThisExpr>(E)) { 12501 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12502 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12503 if (MD->isConst()) { 12504 if (!DiagnosticEmitted) { 12505 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12506 << ConstMethod << MD; 12507 DiagnosticEmitted = true; 12508 } 12509 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12510 << ConstMethod << MD << MD->getSourceRange(); 12511 } 12512 } 12513 } 12514 } 12515 12516 if (DiagnosticEmitted) 12517 return; 12518 12519 // Can't determine a more specific message, so display the generic error. 12520 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12521 } 12522 12523 enum OriginalExprKind { 12524 OEK_Variable, 12525 OEK_Member, 12526 OEK_LValue 12527 }; 12528 12529 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12530 const RecordType *Ty, 12531 SourceLocation Loc, SourceRange Range, 12532 OriginalExprKind OEK, 12533 bool &DiagnosticEmitted) { 12534 std::vector<const RecordType *> RecordTypeList; 12535 RecordTypeList.push_back(Ty); 12536 unsigned NextToCheckIndex = 0; 12537 // We walk the record hierarchy breadth-first to ensure that we print 12538 // diagnostics in field nesting order. 12539 while (RecordTypeList.size() > NextToCheckIndex) { 12540 bool IsNested = NextToCheckIndex > 0; 12541 for (const FieldDecl *Field : 12542 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12543 // First, check every field for constness. 12544 QualType FieldTy = Field->getType(); 12545 if (FieldTy.isConstQualified()) { 12546 if (!DiagnosticEmitted) { 12547 S.Diag(Loc, diag::err_typecheck_assign_const) 12548 << Range << NestedConstMember << OEK << VD 12549 << IsNested << Field; 12550 DiagnosticEmitted = true; 12551 } 12552 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12553 << NestedConstMember << IsNested << Field 12554 << FieldTy << Field->getSourceRange(); 12555 } 12556 12557 // Then we append it to the list to check next in order. 12558 FieldTy = FieldTy.getCanonicalType(); 12559 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12560 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12561 RecordTypeList.push_back(FieldRecTy); 12562 } 12563 } 12564 ++NextToCheckIndex; 12565 } 12566 } 12567 12568 /// Emit an error for the case where a record we are trying to assign to has a 12569 /// const-qualified field somewhere in its hierarchy. 12570 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12571 SourceLocation Loc) { 12572 QualType Ty = E->getType(); 12573 assert(Ty->isRecordType() && "lvalue was not record?"); 12574 SourceRange Range = E->getSourceRange(); 12575 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12576 bool DiagEmitted = false; 12577 12578 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12579 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12580 Range, OEK_Member, DiagEmitted); 12581 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12582 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12583 Range, OEK_Variable, DiagEmitted); 12584 else 12585 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12586 Range, OEK_LValue, DiagEmitted); 12587 if (!DiagEmitted) 12588 DiagnoseConstAssignment(S, E, Loc); 12589 } 12590 12591 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12592 /// emit an error and return true. If so, return false. 12593 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12594 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12595 12596 S.CheckShadowingDeclModification(E, Loc); 12597 12598 SourceLocation OrigLoc = Loc; 12599 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12600 &Loc); 12601 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12602 IsLV = Expr::MLV_InvalidMessageExpression; 12603 if (IsLV == Expr::MLV_Valid) 12604 return false; 12605 12606 unsigned DiagID = 0; 12607 bool NeedType = false; 12608 switch (IsLV) { // C99 6.5.16p2 12609 case Expr::MLV_ConstQualified: 12610 // Use a specialized diagnostic when we're assigning to an object 12611 // from an enclosing function or block. 12612 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12613 if (NCCK == NCCK_Block) 12614 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12615 else 12616 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12617 break; 12618 } 12619 12620 // In ARC, use some specialized diagnostics for occasions where we 12621 // infer 'const'. These are always pseudo-strong variables. 12622 if (S.getLangOpts().ObjCAutoRefCount) { 12623 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12624 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12625 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12626 12627 // Use the normal diagnostic if it's pseudo-__strong but the 12628 // user actually wrote 'const'. 12629 if (var->isARCPseudoStrong() && 12630 (!var->getTypeSourceInfo() || 12631 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12632 // There are three pseudo-strong cases: 12633 // - self 12634 ObjCMethodDecl *method = S.getCurMethodDecl(); 12635 if (method && var == method->getSelfDecl()) { 12636 DiagID = method->isClassMethod() 12637 ? diag::err_typecheck_arc_assign_self_class_method 12638 : diag::err_typecheck_arc_assign_self; 12639 12640 // - Objective-C externally_retained attribute. 12641 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12642 isa<ParmVarDecl>(var)) { 12643 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12644 12645 // - fast enumeration variables 12646 } else { 12647 DiagID = diag::err_typecheck_arr_assign_enumeration; 12648 } 12649 12650 SourceRange Assign; 12651 if (Loc != OrigLoc) 12652 Assign = SourceRange(OrigLoc, OrigLoc); 12653 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12654 // We need to preserve the AST regardless, so migration tool 12655 // can do its job. 12656 return false; 12657 } 12658 } 12659 } 12660 12661 // If none of the special cases above are triggered, then this is a 12662 // simple const assignment. 12663 if (DiagID == 0) { 12664 DiagnoseConstAssignment(S, E, Loc); 12665 return true; 12666 } 12667 12668 break; 12669 case Expr::MLV_ConstAddrSpace: 12670 DiagnoseConstAssignment(S, E, Loc); 12671 return true; 12672 case Expr::MLV_ConstQualifiedField: 12673 DiagnoseRecursiveConstFields(S, E, Loc); 12674 return true; 12675 case Expr::MLV_ArrayType: 12676 case Expr::MLV_ArrayTemporary: 12677 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12678 NeedType = true; 12679 break; 12680 case Expr::MLV_NotObjectType: 12681 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12682 NeedType = true; 12683 break; 12684 case Expr::MLV_LValueCast: 12685 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12686 break; 12687 case Expr::MLV_Valid: 12688 llvm_unreachable("did not take early return for MLV_Valid"); 12689 case Expr::MLV_InvalidExpression: 12690 case Expr::MLV_MemberFunction: 12691 case Expr::MLV_ClassTemporary: 12692 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12693 break; 12694 case Expr::MLV_IncompleteType: 12695 case Expr::MLV_IncompleteVoidType: 12696 return S.RequireCompleteType(Loc, E->getType(), 12697 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12698 case Expr::MLV_DuplicateVectorComponents: 12699 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12700 break; 12701 case Expr::MLV_NoSetterProperty: 12702 llvm_unreachable("readonly properties should be processed differently"); 12703 case Expr::MLV_InvalidMessageExpression: 12704 DiagID = diag::err_readonly_message_assignment; 12705 break; 12706 case Expr::MLV_SubObjCPropertySetting: 12707 DiagID = diag::err_no_subobject_property_setting; 12708 break; 12709 } 12710 12711 SourceRange Assign; 12712 if (Loc != OrigLoc) 12713 Assign = SourceRange(OrigLoc, OrigLoc); 12714 if (NeedType) 12715 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12716 else 12717 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12718 return true; 12719 } 12720 12721 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12722 SourceLocation Loc, 12723 Sema &Sema) { 12724 if (Sema.inTemplateInstantiation()) 12725 return; 12726 if (Sema.isUnevaluatedContext()) 12727 return; 12728 if (Loc.isInvalid() || Loc.isMacroID()) 12729 return; 12730 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12731 return; 12732 12733 // C / C++ fields 12734 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12735 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12736 if (ML && MR) { 12737 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12738 return; 12739 const ValueDecl *LHSDecl = 12740 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12741 const ValueDecl *RHSDecl = 12742 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12743 if (LHSDecl != RHSDecl) 12744 return; 12745 if (LHSDecl->getType().isVolatileQualified()) 12746 return; 12747 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12748 if (RefTy->getPointeeType().isVolatileQualified()) 12749 return; 12750 12751 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12752 } 12753 12754 // Objective-C instance variables 12755 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12756 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12757 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12758 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12759 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12760 if (RL && RR && RL->getDecl() == RR->getDecl()) 12761 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12762 } 12763 } 12764 12765 // C99 6.5.16.1 12766 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12767 SourceLocation Loc, 12768 QualType CompoundType) { 12769 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12770 12771 // Verify that LHS is a modifiable lvalue, and emit error if not. 12772 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12773 return QualType(); 12774 12775 QualType LHSType = LHSExpr->getType(); 12776 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12777 CompoundType; 12778 // OpenCL v1.2 s6.1.1.1 p2: 12779 // The half data type can only be used to declare a pointer to a buffer that 12780 // contains half values 12781 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12782 LHSType->isHalfType()) { 12783 Diag(Loc, diag::err_opencl_half_load_store) << 1 12784 << LHSType.getUnqualifiedType(); 12785 return QualType(); 12786 } 12787 12788 AssignConvertType ConvTy; 12789 if (CompoundType.isNull()) { 12790 Expr *RHSCheck = RHS.get(); 12791 12792 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12793 12794 QualType LHSTy(LHSType); 12795 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12796 if (RHS.isInvalid()) 12797 return QualType(); 12798 // Special case of NSObject attributes on c-style pointer types. 12799 if (ConvTy == IncompatiblePointer && 12800 ((Context.isObjCNSObjectType(LHSType) && 12801 RHSType->isObjCObjectPointerType()) || 12802 (Context.isObjCNSObjectType(RHSType) && 12803 LHSType->isObjCObjectPointerType()))) 12804 ConvTy = Compatible; 12805 12806 if (ConvTy == Compatible && 12807 LHSType->isObjCObjectType()) 12808 Diag(Loc, diag::err_objc_object_assignment) 12809 << LHSType; 12810 12811 // If the RHS is a unary plus or minus, check to see if they = and + are 12812 // right next to each other. If so, the user may have typo'd "x =+ 4" 12813 // instead of "x += 4". 12814 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12815 RHSCheck = ICE->getSubExpr(); 12816 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12817 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12818 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12819 // Only if the two operators are exactly adjacent. 12820 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12821 // And there is a space or other character before the subexpr of the 12822 // unary +/-. We don't want to warn on "x=-1". 12823 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12824 UO->getSubExpr()->getBeginLoc().isFileID()) { 12825 Diag(Loc, diag::warn_not_compound_assign) 12826 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12827 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12828 } 12829 } 12830 12831 if (ConvTy == Compatible) { 12832 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12833 // Warn about retain cycles where a block captures the LHS, but 12834 // not if the LHS is a simple variable into which the block is 12835 // being stored...unless that variable can be captured by reference! 12836 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12837 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12838 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12839 checkRetainCycles(LHSExpr, RHS.get()); 12840 } 12841 12842 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12843 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12844 // It is safe to assign a weak reference into a strong variable. 12845 // Although this code can still have problems: 12846 // id x = self.weakProp; 12847 // id y = self.weakProp; 12848 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12849 // paths through the function. This should be revisited if 12850 // -Wrepeated-use-of-weak is made flow-sensitive. 12851 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12852 // variable, which will be valid for the current autorelease scope. 12853 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12854 RHS.get()->getBeginLoc())) 12855 getCurFunction()->markSafeWeakUse(RHS.get()); 12856 12857 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12858 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12859 } 12860 } 12861 } else { 12862 // Compound assignment "x += y" 12863 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12864 } 12865 12866 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12867 RHS.get(), AA_Assigning)) 12868 return QualType(); 12869 12870 CheckForNullPointerDereference(*this, LHSExpr); 12871 12872 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12873 if (CompoundType.isNull()) { 12874 // C++2a [expr.ass]p5: 12875 // A simple-assignment whose left operand is of a volatile-qualified 12876 // type is deprecated unless the assignment is either a discarded-value 12877 // expression or an unevaluated operand 12878 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12879 } else { 12880 // C++2a [expr.ass]p6: 12881 // [Compound-assignment] expressions are deprecated if E1 has 12882 // volatile-qualified type 12883 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12884 } 12885 } 12886 12887 // C99 6.5.16p3: The type of an assignment expression is the type of the 12888 // left operand unless the left operand has qualified type, in which case 12889 // it is the unqualified version of the type of the left operand. 12890 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12891 // is converted to the type of the assignment expression (above). 12892 // C++ 5.17p1: the type of the assignment expression is that of its left 12893 // operand. 12894 return (getLangOpts().CPlusPlus 12895 ? LHSType : LHSType.getUnqualifiedType()); 12896 } 12897 12898 // Only ignore explicit casts to void. 12899 static bool IgnoreCommaOperand(const Expr *E) { 12900 E = E->IgnoreParens(); 12901 12902 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12903 if (CE->getCastKind() == CK_ToVoid) { 12904 return true; 12905 } 12906 12907 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12908 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12909 CE->getSubExpr()->getType()->isDependentType()) { 12910 return true; 12911 } 12912 } 12913 12914 return false; 12915 } 12916 12917 // Look for instances where it is likely the comma operator is confused with 12918 // another operator. There is an explicit list of acceptable expressions for 12919 // the left hand side of the comma operator, otherwise emit a warning. 12920 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12921 // No warnings in macros 12922 if (Loc.isMacroID()) 12923 return; 12924 12925 // Don't warn in template instantiations. 12926 if (inTemplateInstantiation()) 12927 return; 12928 12929 // Scope isn't fine-grained enough to explicitly list the specific cases, so 12930 // instead, skip more than needed, then call back into here with the 12931 // CommaVisitor in SemaStmt.cpp. 12932 // The listed locations are the initialization and increment portions 12933 // of a for loop. The additional checks are on the condition of 12934 // if statements, do/while loops, and for loops. 12935 // Differences in scope flags for C89 mode requires the extra logic. 12936 const unsigned ForIncrementFlags = 12937 getLangOpts().C99 || getLangOpts().CPlusPlus 12938 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12939 : Scope::ContinueScope | Scope::BreakScope; 12940 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12941 const unsigned ScopeFlags = getCurScope()->getFlags(); 12942 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12943 (ScopeFlags & ForInitFlags) == ForInitFlags) 12944 return; 12945 12946 // If there are multiple comma operators used together, get the RHS of the 12947 // of the comma operator as the LHS. 12948 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12949 if (BO->getOpcode() != BO_Comma) 12950 break; 12951 LHS = BO->getRHS(); 12952 } 12953 12954 // Only allow some expressions on LHS to not warn. 12955 if (IgnoreCommaOperand(LHS)) 12956 return; 12957 12958 Diag(Loc, diag::warn_comma_operator); 12959 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12960 << LHS->getSourceRange() 12961 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12962 LangOpts.CPlusPlus ? "static_cast<void>(" 12963 : "(void)(") 12964 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12965 ")"); 12966 } 12967 12968 // C99 6.5.17 12969 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12970 SourceLocation Loc) { 12971 LHS = S.CheckPlaceholderExpr(LHS.get()); 12972 RHS = S.CheckPlaceholderExpr(RHS.get()); 12973 if (LHS.isInvalid() || RHS.isInvalid()) 12974 return QualType(); 12975 12976 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12977 // operands, but not unary promotions. 12978 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12979 12980 // So we treat the LHS as a ignored value, and in C++ we allow the 12981 // containing site to determine what should be done with the RHS. 12982 LHS = S.IgnoredValueConversions(LHS.get()); 12983 if (LHS.isInvalid()) 12984 return QualType(); 12985 12986 S.DiagnoseUnusedExprResult(LHS.get()); 12987 12988 if (!S.getLangOpts().CPlusPlus) { 12989 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12990 if (RHS.isInvalid()) 12991 return QualType(); 12992 if (!RHS.get()->getType()->isVoidType()) 12993 S.RequireCompleteType(Loc, RHS.get()->getType(), 12994 diag::err_incomplete_type); 12995 } 12996 12997 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12998 S.DiagnoseCommaOperator(LHS.get(), Loc); 12999 13000 return RHS.get()->getType(); 13001 } 13002 13003 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13004 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13005 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13006 ExprValueKind &VK, 13007 ExprObjectKind &OK, 13008 SourceLocation OpLoc, 13009 bool IsInc, bool IsPrefix) { 13010 if (Op->isTypeDependent()) 13011 return S.Context.DependentTy; 13012 13013 QualType ResType = Op->getType(); 13014 // Atomic types can be used for increment / decrement where the non-atomic 13015 // versions can, so ignore the _Atomic() specifier for the purpose of 13016 // checking. 13017 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13018 ResType = ResAtomicType->getValueType(); 13019 13020 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13021 13022 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13023 // Decrement of bool is not allowed. 13024 if (!IsInc) { 13025 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13026 return QualType(); 13027 } 13028 // Increment of bool sets it to true, but is deprecated. 13029 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13030 : diag::warn_increment_bool) 13031 << Op->getSourceRange(); 13032 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13033 // Error on enum increments and decrements in C++ mode 13034 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13035 return QualType(); 13036 } else if (ResType->isRealType()) { 13037 // OK! 13038 } else if (ResType->isPointerType()) { 13039 // C99 6.5.2.4p2, 6.5.6p2 13040 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13041 return QualType(); 13042 } else if (ResType->isObjCObjectPointerType()) { 13043 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13044 // Otherwise, we just need a complete type. 13045 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13046 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13047 return QualType(); 13048 } else if (ResType->isAnyComplexType()) { 13049 // C99 does not support ++/-- on complex types, we allow as an extension. 13050 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13051 << ResType << Op->getSourceRange(); 13052 } else if (ResType->isPlaceholderType()) { 13053 ExprResult PR = S.CheckPlaceholderExpr(Op); 13054 if (PR.isInvalid()) return QualType(); 13055 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13056 IsInc, IsPrefix); 13057 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13058 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13059 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13060 (ResType->castAs<VectorType>()->getVectorKind() != 13061 VectorType::AltiVecBool)) { 13062 // The z vector extensions allow ++ and -- for non-bool vectors. 13063 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13064 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13065 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13066 } else { 13067 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13068 << ResType << int(IsInc) << Op->getSourceRange(); 13069 return QualType(); 13070 } 13071 // At this point, we know we have a real, complex or pointer type. 13072 // Now make sure the operand is a modifiable lvalue. 13073 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13074 return QualType(); 13075 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13076 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13077 // An operand with volatile-qualified type is deprecated 13078 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13079 << IsInc << ResType; 13080 } 13081 // In C++, a prefix increment is the same type as the operand. Otherwise 13082 // (in C or with postfix), the increment is the unqualified type of the 13083 // operand. 13084 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13085 VK = VK_LValue; 13086 OK = Op->getObjectKind(); 13087 return ResType; 13088 } else { 13089 VK = VK_RValue; 13090 return ResType.getUnqualifiedType(); 13091 } 13092 } 13093 13094 13095 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13096 /// This routine allows us to typecheck complex/recursive expressions 13097 /// where the declaration is needed for type checking. We only need to 13098 /// handle cases when the expression references a function designator 13099 /// or is an lvalue. Here are some examples: 13100 /// - &(x) => x 13101 /// - &*****f => f for f a function designator. 13102 /// - &s.xx => s 13103 /// - &s.zz[1].yy -> s, if zz is an array 13104 /// - *(x + 1) -> x, if x is an array 13105 /// - &"123"[2] -> 0 13106 /// - & __real__ x -> x 13107 /// 13108 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13109 /// members. 13110 static ValueDecl *getPrimaryDecl(Expr *E) { 13111 switch (E->getStmtClass()) { 13112 case Stmt::DeclRefExprClass: 13113 return cast<DeclRefExpr>(E)->getDecl(); 13114 case Stmt::MemberExprClass: 13115 // If this is an arrow operator, the address is an offset from 13116 // the base's value, so the object the base refers to is 13117 // irrelevant. 13118 if (cast<MemberExpr>(E)->isArrow()) 13119 return nullptr; 13120 // Otherwise, the expression refers to a part of the base 13121 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13122 case Stmt::ArraySubscriptExprClass: { 13123 // FIXME: This code shouldn't be necessary! We should catch the implicit 13124 // promotion of register arrays earlier. 13125 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13126 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13127 if (ICE->getSubExpr()->getType()->isArrayType()) 13128 return getPrimaryDecl(ICE->getSubExpr()); 13129 } 13130 return nullptr; 13131 } 13132 case Stmt::UnaryOperatorClass: { 13133 UnaryOperator *UO = cast<UnaryOperator>(E); 13134 13135 switch(UO->getOpcode()) { 13136 case UO_Real: 13137 case UO_Imag: 13138 case UO_Extension: 13139 return getPrimaryDecl(UO->getSubExpr()); 13140 default: 13141 return nullptr; 13142 } 13143 } 13144 case Stmt::ParenExprClass: 13145 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13146 case Stmt::ImplicitCastExprClass: 13147 // If the result of an implicit cast is an l-value, we care about 13148 // the sub-expression; otherwise, the result here doesn't matter. 13149 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13150 case Stmt::CXXUuidofExprClass: 13151 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13152 default: 13153 return nullptr; 13154 } 13155 } 13156 13157 namespace { 13158 enum { 13159 AO_Bit_Field = 0, 13160 AO_Vector_Element = 1, 13161 AO_Property_Expansion = 2, 13162 AO_Register_Variable = 3, 13163 AO_Matrix_Element = 4, 13164 AO_No_Error = 5 13165 }; 13166 } 13167 /// Diagnose invalid operand for address of operations. 13168 /// 13169 /// \param Type The type of operand which cannot have its address taken. 13170 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13171 Expr *E, unsigned Type) { 13172 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13173 } 13174 13175 /// CheckAddressOfOperand - The operand of & must be either a function 13176 /// designator or an lvalue designating an object. If it is an lvalue, the 13177 /// object cannot be declared with storage class register or be a bit field. 13178 /// Note: The usual conversions are *not* applied to the operand of the & 13179 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13180 /// In C++, the operand might be an overloaded function name, in which case 13181 /// we allow the '&' but retain the overloaded-function type. 13182 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13183 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13184 if (PTy->getKind() == BuiltinType::Overload) { 13185 Expr *E = OrigOp.get()->IgnoreParens(); 13186 if (!isa<OverloadExpr>(E)) { 13187 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13188 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13189 << OrigOp.get()->getSourceRange(); 13190 return QualType(); 13191 } 13192 13193 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13194 if (isa<UnresolvedMemberExpr>(Ovl)) 13195 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13196 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13197 << OrigOp.get()->getSourceRange(); 13198 return QualType(); 13199 } 13200 13201 return Context.OverloadTy; 13202 } 13203 13204 if (PTy->getKind() == BuiltinType::UnknownAny) 13205 return Context.UnknownAnyTy; 13206 13207 if (PTy->getKind() == BuiltinType::BoundMember) { 13208 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13209 << OrigOp.get()->getSourceRange(); 13210 return QualType(); 13211 } 13212 13213 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13214 if (OrigOp.isInvalid()) return QualType(); 13215 } 13216 13217 if (OrigOp.get()->isTypeDependent()) 13218 return Context.DependentTy; 13219 13220 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13221 13222 // Make sure to ignore parentheses in subsequent checks 13223 Expr *op = OrigOp.get()->IgnoreParens(); 13224 13225 // In OpenCL captures for blocks called as lambda functions 13226 // are located in the private address space. Blocks used in 13227 // enqueue_kernel can be located in a different address space 13228 // depending on a vendor implementation. Thus preventing 13229 // taking an address of the capture to avoid invalid AS casts. 13230 if (LangOpts.OpenCL) { 13231 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13232 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13233 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13234 return QualType(); 13235 } 13236 } 13237 13238 if (getLangOpts().C99) { 13239 // Implement C99-only parts of addressof rules. 13240 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13241 if (uOp->getOpcode() == UO_Deref) 13242 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13243 // (assuming the deref expression is valid). 13244 return uOp->getSubExpr()->getType(); 13245 } 13246 // Technically, there should be a check for array subscript 13247 // expressions here, but the result of one is always an lvalue anyway. 13248 } 13249 ValueDecl *dcl = getPrimaryDecl(op); 13250 13251 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13252 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13253 op->getBeginLoc())) 13254 return QualType(); 13255 13256 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13257 unsigned AddressOfError = AO_No_Error; 13258 13259 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13260 bool sfinae = (bool)isSFINAEContext(); 13261 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13262 : diag::ext_typecheck_addrof_temporary) 13263 << op->getType() << op->getSourceRange(); 13264 if (sfinae) 13265 return QualType(); 13266 // Materialize the temporary as an lvalue so that we can take its address. 13267 OrigOp = op = 13268 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13269 } else if (isa<ObjCSelectorExpr>(op)) { 13270 return Context.getPointerType(op->getType()); 13271 } else if (lval == Expr::LV_MemberFunction) { 13272 // If it's an instance method, make a member pointer. 13273 // The expression must have exactly the form &A::foo. 13274 13275 // If the underlying expression isn't a decl ref, give up. 13276 if (!isa<DeclRefExpr>(op)) { 13277 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13278 << OrigOp.get()->getSourceRange(); 13279 return QualType(); 13280 } 13281 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13282 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13283 13284 // The id-expression was parenthesized. 13285 if (OrigOp.get() != DRE) { 13286 Diag(OpLoc, diag::err_parens_pointer_member_function) 13287 << OrigOp.get()->getSourceRange(); 13288 13289 // The method was named without a qualifier. 13290 } else if (!DRE->getQualifier()) { 13291 if (MD->getParent()->getName().empty()) 13292 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13293 << op->getSourceRange(); 13294 else { 13295 SmallString<32> Str; 13296 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13297 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13298 << op->getSourceRange() 13299 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13300 } 13301 } 13302 13303 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13304 if (isa<CXXDestructorDecl>(MD)) 13305 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13306 13307 QualType MPTy = Context.getMemberPointerType( 13308 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13309 // Under the MS ABI, lock down the inheritance model now. 13310 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13311 (void)isCompleteType(OpLoc, MPTy); 13312 return MPTy; 13313 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13314 // C99 6.5.3.2p1 13315 // The operand must be either an l-value or a function designator 13316 if (!op->getType()->isFunctionType()) { 13317 // Use a special diagnostic for loads from property references. 13318 if (isa<PseudoObjectExpr>(op)) { 13319 AddressOfError = AO_Property_Expansion; 13320 } else { 13321 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13322 << op->getType() << op->getSourceRange(); 13323 return QualType(); 13324 } 13325 } 13326 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13327 // The operand cannot be a bit-field 13328 AddressOfError = AO_Bit_Field; 13329 } else if (op->getObjectKind() == OK_VectorComponent) { 13330 // The operand cannot be an element of a vector 13331 AddressOfError = AO_Vector_Element; 13332 } else if (op->getObjectKind() == OK_MatrixComponent) { 13333 // The operand cannot be an element of a matrix. 13334 AddressOfError = AO_Matrix_Element; 13335 } else if (dcl) { // C99 6.5.3.2p1 13336 // We have an lvalue with a decl. Make sure the decl is not declared 13337 // with the register storage-class specifier. 13338 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13339 // in C++ it is not error to take address of a register 13340 // variable (c++03 7.1.1P3) 13341 if (vd->getStorageClass() == SC_Register && 13342 !getLangOpts().CPlusPlus) { 13343 AddressOfError = AO_Register_Variable; 13344 } 13345 } else if (isa<MSPropertyDecl>(dcl)) { 13346 AddressOfError = AO_Property_Expansion; 13347 } else if (isa<FunctionTemplateDecl>(dcl)) { 13348 return Context.OverloadTy; 13349 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13350 // Okay: we can take the address of a field. 13351 // Could be a pointer to member, though, if there is an explicit 13352 // scope qualifier for the class. 13353 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13354 DeclContext *Ctx = dcl->getDeclContext(); 13355 if (Ctx && Ctx->isRecord()) { 13356 if (dcl->getType()->isReferenceType()) { 13357 Diag(OpLoc, 13358 diag::err_cannot_form_pointer_to_member_of_reference_type) 13359 << dcl->getDeclName() << dcl->getType(); 13360 return QualType(); 13361 } 13362 13363 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13364 Ctx = Ctx->getParent(); 13365 13366 QualType MPTy = Context.getMemberPointerType( 13367 op->getType(), 13368 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13369 // Under the MS ABI, lock down the inheritance model now. 13370 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13371 (void)isCompleteType(OpLoc, MPTy); 13372 return MPTy; 13373 } 13374 } 13375 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13376 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13377 llvm_unreachable("Unknown/unexpected decl type"); 13378 } 13379 13380 if (AddressOfError != AO_No_Error) { 13381 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13382 return QualType(); 13383 } 13384 13385 if (lval == Expr::LV_IncompleteVoidType) { 13386 // Taking the address of a void variable is technically illegal, but we 13387 // allow it in cases which are otherwise valid. 13388 // Example: "extern void x; void* y = &x;". 13389 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13390 } 13391 13392 // If the operand has type "type", the result has type "pointer to type". 13393 if (op->getType()->isObjCObjectType()) 13394 return Context.getObjCObjectPointerType(op->getType()); 13395 13396 CheckAddressOfPackedMember(op); 13397 13398 return Context.getPointerType(op->getType()); 13399 } 13400 13401 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13402 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13403 if (!DRE) 13404 return; 13405 const Decl *D = DRE->getDecl(); 13406 if (!D) 13407 return; 13408 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13409 if (!Param) 13410 return; 13411 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13412 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13413 return; 13414 if (FunctionScopeInfo *FD = S.getCurFunction()) 13415 if (!FD->ModifiedNonNullParams.count(Param)) 13416 FD->ModifiedNonNullParams.insert(Param); 13417 } 13418 13419 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13420 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13421 SourceLocation OpLoc) { 13422 if (Op->isTypeDependent()) 13423 return S.Context.DependentTy; 13424 13425 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13426 if (ConvResult.isInvalid()) 13427 return QualType(); 13428 Op = ConvResult.get(); 13429 QualType OpTy = Op->getType(); 13430 QualType Result; 13431 13432 if (isa<CXXReinterpretCastExpr>(Op)) { 13433 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13434 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13435 Op->getSourceRange()); 13436 } 13437 13438 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13439 { 13440 Result = PT->getPointeeType(); 13441 } 13442 else if (const ObjCObjectPointerType *OPT = 13443 OpTy->getAs<ObjCObjectPointerType>()) 13444 Result = OPT->getPointeeType(); 13445 else { 13446 ExprResult PR = S.CheckPlaceholderExpr(Op); 13447 if (PR.isInvalid()) return QualType(); 13448 if (PR.get() != Op) 13449 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13450 } 13451 13452 if (Result.isNull()) { 13453 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13454 << OpTy << Op->getSourceRange(); 13455 return QualType(); 13456 } 13457 13458 // Note that per both C89 and C99, indirection is always legal, even if Result 13459 // is an incomplete type or void. It would be possible to warn about 13460 // dereferencing a void pointer, but it's completely well-defined, and such a 13461 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13462 // for pointers to 'void' but is fine for any other pointer type: 13463 // 13464 // C++ [expr.unary.op]p1: 13465 // [...] the expression to which [the unary * operator] is applied shall 13466 // be a pointer to an object type, or a pointer to a function type 13467 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13468 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13469 << OpTy << Op->getSourceRange(); 13470 13471 // Dereferences are usually l-values... 13472 VK = VK_LValue; 13473 13474 // ...except that certain expressions are never l-values in C. 13475 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13476 VK = VK_RValue; 13477 13478 return Result; 13479 } 13480 13481 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13482 BinaryOperatorKind Opc; 13483 switch (Kind) { 13484 default: llvm_unreachable("Unknown binop!"); 13485 case tok::periodstar: Opc = BO_PtrMemD; break; 13486 case tok::arrowstar: Opc = BO_PtrMemI; break; 13487 case tok::star: Opc = BO_Mul; break; 13488 case tok::slash: Opc = BO_Div; break; 13489 case tok::percent: Opc = BO_Rem; break; 13490 case tok::plus: Opc = BO_Add; break; 13491 case tok::minus: Opc = BO_Sub; break; 13492 case tok::lessless: Opc = BO_Shl; break; 13493 case tok::greatergreater: Opc = BO_Shr; break; 13494 case tok::lessequal: Opc = BO_LE; break; 13495 case tok::less: Opc = BO_LT; break; 13496 case tok::greaterequal: Opc = BO_GE; break; 13497 case tok::greater: Opc = BO_GT; break; 13498 case tok::exclaimequal: Opc = BO_NE; break; 13499 case tok::equalequal: Opc = BO_EQ; break; 13500 case tok::spaceship: Opc = BO_Cmp; break; 13501 case tok::amp: Opc = BO_And; break; 13502 case tok::caret: Opc = BO_Xor; break; 13503 case tok::pipe: Opc = BO_Or; break; 13504 case tok::ampamp: Opc = BO_LAnd; break; 13505 case tok::pipepipe: Opc = BO_LOr; break; 13506 case tok::equal: Opc = BO_Assign; break; 13507 case tok::starequal: Opc = BO_MulAssign; break; 13508 case tok::slashequal: Opc = BO_DivAssign; break; 13509 case tok::percentequal: Opc = BO_RemAssign; break; 13510 case tok::plusequal: Opc = BO_AddAssign; break; 13511 case tok::minusequal: Opc = BO_SubAssign; break; 13512 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13513 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13514 case tok::ampequal: Opc = BO_AndAssign; break; 13515 case tok::caretequal: Opc = BO_XorAssign; break; 13516 case tok::pipeequal: Opc = BO_OrAssign; break; 13517 case tok::comma: Opc = BO_Comma; break; 13518 } 13519 return Opc; 13520 } 13521 13522 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13523 tok::TokenKind Kind) { 13524 UnaryOperatorKind Opc; 13525 switch (Kind) { 13526 default: llvm_unreachable("Unknown unary op!"); 13527 case tok::plusplus: Opc = UO_PreInc; break; 13528 case tok::minusminus: Opc = UO_PreDec; break; 13529 case tok::amp: Opc = UO_AddrOf; break; 13530 case tok::star: Opc = UO_Deref; break; 13531 case tok::plus: Opc = UO_Plus; break; 13532 case tok::minus: Opc = UO_Minus; break; 13533 case tok::tilde: Opc = UO_Not; break; 13534 case tok::exclaim: Opc = UO_LNot; break; 13535 case tok::kw___real: Opc = UO_Real; break; 13536 case tok::kw___imag: Opc = UO_Imag; break; 13537 case tok::kw___extension__: Opc = UO_Extension; break; 13538 } 13539 return Opc; 13540 } 13541 13542 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13543 /// This warning suppressed in the event of macro expansions. 13544 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13545 SourceLocation OpLoc, bool IsBuiltin) { 13546 if (S.inTemplateInstantiation()) 13547 return; 13548 if (S.isUnevaluatedContext()) 13549 return; 13550 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13551 return; 13552 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13553 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13554 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13555 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13556 if (!LHSDeclRef || !RHSDeclRef || 13557 LHSDeclRef->getLocation().isMacroID() || 13558 RHSDeclRef->getLocation().isMacroID()) 13559 return; 13560 const ValueDecl *LHSDecl = 13561 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13562 const ValueDecl *RHSDecl = 13563 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13564 if (LHSDecl != RHSDecl) 13565 return; 13566 if (LHSDecl->getType().isVolatileQualified()) 13567 return; 13568 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13569 if (RefTy->getPointeeType().isVolatileQualified()) 13570 return; 13571 13572 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13573 : diag::warn_self_assignment_overloaded) 13574 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13575 << RHSExpr->getSourceRange(); 13576 } 13577 13578 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13579 /// is usually indicative of introspection within the Objective-C pointer. 13580 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13581 SourceLocation OpLoc) { 13582 if (!S.getLangOpts().ObjC) 13583 return; 13584 13585 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13586 const Expr *LHS = L.get(); 13587 const Expr *RHS = R.get(); 13588 13589 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13590 ObjCPointerExpr = LHS; 13591 OtherExpr = RHS; 13592 } 13593 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13594 ObjCPointerExpr = RHS; 13595 OtherExpr = LHS; 13596 } 13597 13598 // This warning is deliberately made very specific to reduce false 13599 // positives with logic that uses '&' for hashing. This logic mainly 13600 // looks for code trying to introspect into tagged pointers, which 13601 // code should generally never do. 13602 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13603 unsigned Diag = diag::warn_objc_pointer_masking; 13604 // Determine if we are introspecting the result of performSelectorXXX. 13605 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13606 // Special case messages to -performSelector and friends, which 13607 // can return non-pointer values boxed in a pointer value. 13608 // Some clients may wish to silence warnings in this subcase. 13609 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13610 Selector S = ME->getSelector(); 13611 StringRef SelArg0 = S.getNameForSlot(0); 13612 if (SelArg0.startswith("performSelector")) 13613 Diag = diag::warn_objc_pointer_masking_performSelector; 13614 } 13615 13616 S.Diag(OpLoc, Diag) 13617 << ObjCPointerExpr->getSourceRange(); 13618 } 13619 } 13620 13621 static NamedDecl *getDeclFromExpr(Expr *E) { 13622 if (!E) 13623 return nullptr; 13624 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13625 return DRE->getDecl(); 13626 if (auto *ME = dyn_cast<MemberExpr>(E)) 13627 return ME->getMemberDecl(); 13628 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13629 return IRE->getDecl(); 13630 return nullptr; 13631 } 13632 13633 // This helper function promotes a binary operator's operands (which are of a 13634 // half vector type) to a vector of floats and then truncates the result to 13635 // a vector of either half or short. 13636 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13637 BinaryOperatorKind Opc, QualType ResultTy, 13638 ExprValueKind VK, ExprObjectKind OK, 13639 bool IsCompAssign, SourceLocation OpLoc, 13640 FPOptionsOverride FPFeatures) { 13641 auto &Context = S.getASTContext(); 13642 assert((isVector(ResultTy, Context.HalfTy) || 13643 isVector(ResultTy, Context.ShortTy)) && 13644 "Result must be a vector of half or short"); 13645 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13646 isVector(RHS.get()->getType(), Context.HalfTy) && 13647 "both operands expected to be a half vector"); 13648 13649 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13650 QualType BinOpResTy = RHS.get()->getType(); 13651 13652 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13653 // change BinOpResTy to a vector of ints. 13654 if (isVector(ResultTy, Context.ShortTy)) 13655 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13656 13657 if (IsCompAssign) 13658 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13659 ResultTy, VK, OK, OpLoc, FPFeatures, 13660 BinOpResTy, BinOpResTy); 13661 13662 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13663 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13664 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13665 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13666 } 13667 13668 static std::pair<ExprResult, ExprResult> 13669 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13670 Expr *RHSExpr) { 13671 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13672 if (!S.Context.isDependenceAllowed()) { 13673 // C cannot handle TypoExpr nodes on either side of a binop because it 13674 // doesn't handle dependent types properly, so make sure any TypoExprs have 13675 // been dealt with before checking the operands. 13676 LHS = S.CorrectDelayedTyposInExpr(LHS); 13677 RHS = S.CorrectDelayedTyposInExpr( 13678 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13679 [Opc, LHS](Expr *E) { 13680 if (Opc != BO_Assign) 13681 return ExprResult(E); 13682 // Avoid correcting the RHS to the same Expr as the LHS. 13683 Decl *D = getDeclFromExpr(E); 13684 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13685 }); 13686 } 13687 return std::make_pair(LHS, RHS); 13688 } 13689 13690 /// Returns true if conversion between vectors of halfs and vectors of floats 13691 /// is needed. 13692 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13693 Expr *E0, Expr *E1 = nullptr) { 13694 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13695 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13696 return false; 13697 13698 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13699 QualType Ty = E->IgnoreImplicit()->getType(); 13700 13701 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13702 // to vectors of floats. Although the element type of the vectors is __fp16, 13703 // the vectors shouldn't be treated as storage-only types. See the 13704 // discussion here: https://reviews.llvm.org/rG825235c140e7 13705 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13706 if (VT->getVectorKind() == VectorType::NeonVector) 13707 return false; 13708 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13709 } 13710 return false; 13711 }; 13712 13713 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13714 } 13715 13716 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13717 /// operator @p Opc at location @c TokLoc. This routine only supports 13718 /// built-in operations; ActOnBinOp handles overloaded operators. 13719 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13720 BinaryOperatorKind Opc, 13721 Expr *LHSExpr, Expr *RHSExpr) { 13722 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13723 // The syntax only allows initializer lists on the RHS of assignment, 13724 // so we don't need to worry about accepting invalid code for 13725 // non-assignment operators. 13726 // C++11 5.17p9: 13727 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13728 // of x = {} is x = T(). 13729 InitializationKind Kind = InitializationKind::CreateDirectList( 13730 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13731 InitializedEntity Entity = 13732 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13733 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13734 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13735 if (Init.isInvalid()) 13736 return Init; 13737 RHSExpr = Init.get(); 13738 } 13739 13740 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13741 QualType ResultTy; // Result type of the binary operator. 13742 // The following two variables are used for compound assignment operators 13743 QualType CompLHSTy; // Type of LHS after promotions for computation 13744 QualType CompResultTy; // Type of computation result 13745 ExprValueKind VK = VK_RValue; 13746 ExprObjectKind OK = OK_Ordinary; 13747 bool ConvertHalfVec = false; 13748 13749 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13750 if (!LHS.isUsable() || !RHS.isUsable()) 13751 return ExprError(); 13752 13753 if (getLangOpts().OpenCL) { 13754 QualType LHSTy = LHSExpr->getType(); 13755 QualType RHSTy = RHSExpr->getType(); 13756 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13757 // the ATOMIC_VAR_INIT macro. 13758 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13759 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13760 if (BO_Assign == Opc) 13761 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13762 else 13763 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13764 return ExprError(); 13765 } 13766 13767 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13768 // only with a builtin functions and therefore should be disallowed here. 13769 if (LHSTy->isImageType() || RHSTy->isImageType() || 13770 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13771 LHSTy->isPipeType() || RHSTy->isPipeType() || 13772 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13773 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13774 return ExprError(); 13775 } 13776 } 13777 13778 switch (Opc) { 13779 case BO_Assign: 13780 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13781 if (getLangOpts().CPlusPlus && 13782 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13783 VK = LHS.get()->getValueKind(); 13784 OK = LHS.get()->getObjectKind(); 13785 } 13786 if (!ResultTy.isNull()) { 13787 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13788 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13789 13790 // Avoid copying a block to the heap if the block is assigned to a local 13791 // auto variable that is declared in the same scope as the block. This 13792 // optimization is unsafe if the local variable is declared in an outer 13793 // scope. For example: 13794 // 13795 // BlockTy b; 13796 // { 13797 // b = ^{...}; 13798 // } 13799 // // It is unsafe to invoke the block here if it wasn't copied to the 13800 // // heap. 13801 // b(); 13802 13803 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13804 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13805 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13806 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13807 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13808 13809 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13810 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13811 NTCUC_Assignment, NTCUK_Copy); 13812 } 13813 RecordModifiableNonNullParam(*this, LHS.get()); 13814 break; 13815 case BO_PtrMemD: 13816 case BO_PtrMemI: 13817 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13818 Opc == BO_PtrMemI); 13819 break; 13820 case BO_Mul: 13821 case BO_Div: 13822 ConvertHalfVec = true; 13823 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13824 Opc == BO_Div); 13825 break; 13826 case BO_Rem: 13827 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13828 break; 13829 case BO_Add: 13830 ConvertHalfVec = true; 13831 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13832 break; 13833 case BO_Sub: 13834 ConvertHalfVec = true; 13835 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13836 break; 13837 case BO_Shl: 13838 case BO_Shr: 13839 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13840 break; 13841 case BO_LE: 13842 case BO_LT: 13843 case BO_GE: 13844 case BO_GT: 13845 ConvertHalfVec = true; 13846 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13847 break; 13848 case BO_EQ: 13849 case BO_NE: 13850 ConvertHalfVec = true; 13851 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13852 break; 13853 case BO_Cmp: 13854 ConvertHalfVec = true; 13855 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13856 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13857 break; 13858 case BO_And: 13859 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13860 LLVM_FALLTHROUGH; 13861 case BO_Xor: 13862 case BO_Or: 13863 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13864 break; 13865 case BO_LAnd: 13866 case BO_LOr: 13867 ConvertHalfVec = true; 13868 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13869 break; 13870 case BO_MulAssign: 13871 case BO_DivAssign: 13872 ConvertHalfVec = true; 13873 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13874 Opc == BO_DivAssign); 13875 CompLHSTy = CompResultTy; 13876 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13877 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13878 break; 13879 case BO_RemAssign: 13880 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13881 CompLHSTy = CompResultTy; 13882 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13883 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13884 break; 13885 case BO_AddAssign: 13886 ConvertHalfVec = true; 13887 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13888 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13889 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13890 break; 13891 case BO_SubAssign: 13892 ConvertHalfVec = true; 13893 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13894 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13895 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13896 break; 13897 case BO_ShlAssign: 13898 case BO_ShrAssign: 13899 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13900 CompLHSTy = CompResultTy; 13901 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13902 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13903 break; 13904 case BO_AndAssign: 13905 case BO_OrAssign: // fallthrough 13906 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13907 LLVM_FALLTHROUGH; 13908 case BO_XorAssign: 13909 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13910 CompLHSTy = CompResultTy; 13911 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13912 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13913 break; 13914 case BO_Comma: 13915 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13916 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13917 VK = RHS.get()->getValueKind(); 13918 OK = RHS.get()->getObjectKind(); 13919 } 13920 break; 13921 } 13922 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13923 return ExprError(); 13924 13925 // Some of the binary operations require promoting operands of half vector to 13926 // float vectors and truncating the result back to half vector. For now, we do 13927 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13928 // arm64). 13929 assert( 13930 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 13931 isVector(LHS.get()->getType(), Context.HalfTy)) && 13932 "both sides are half vectors or neither sides are"); 13933 ConvertHalfVec = 13934 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13935 13936 // Check for array bounds violations for both sides of the BinaryOperator 13937 CheckArrayAccess(LHS.get()); 13938 CheckArrayAccess(RHS.get()); 13939 13940 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13941 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13942 &Context.Idents.get("object_setClass"), 13943 SourceLocation(), LookupOrdinaryName); 13944 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13945 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13946 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13947 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13948 "object_setClass(") 13949 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13950 ",") 13951 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13952 } 13953 else 13954 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13955 } 13956 else if (const ObjCIvarRefExpr *OIRE = 13957 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13958 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13959 13960 // Opc is not a compound assignment if CompResultTy is null. 13961 if (CompResultTy.isNull()) { 13962 if (ConvertHalfVec) 13963 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13964 OpLoc, CurFPFeatureOverrides()); 13965 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13966 VK, OK, OpLoc, CurFPFeatureOverrides()); 13967 } 13968 13969 // Handle compound assignments. 13970 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13971 OK_ObjCProperty) { 13972 VK = VK_LValue; 13973 OK = LHS.get()->getObjectKind(); 13974 } 13975 13976 // The LHS is not converted to the result type for fixed-point compound 13977 // assignment as the common type is computed on demand. Reset the CompLHSTy 13978 // to the LHS type we would have gotten after unary conversions. 13979 if (CompResultTy->isFixedPointType()) 13980 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13981 13982 if (ConvertHalfVec) 13983 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13984 OpLoc, CurFPFeatureOverrides()); 13985 13986 return CompoundAssignOperator::Create( 13987 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 13988 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 13989 } 13990 13991 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13992 /// operators are mixed in a way that suggests that the programmer forgot that 13993 /// comparison operators have higher precedence. The most typical example of 13994 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13995 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13996 SourceLocation OpLoc, Expr *LHSExpr, 13997 Expr *RHSExpr) { 13998 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13999 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14000 14001 // Check that one of the sides is a comparison operator and the other isn't. 14002 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14003 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14004 if (isLeftComp == isRightComp) 14005 return; 14006 14007 // Bitwise operations are sometimes used as eager logical ops. 14008 // Don't diagnose this. 14009 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14010 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14011 if (isLeftBitwise || isRightBitwise) 14012 return; 14013 14014 SourceRange DiagRange = isLeftComp 14015 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14016 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14017 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14018 SourceRange ParensRange = 14019 isLeftComp 14020 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14021 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14022 14023 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14024 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14025 SuggestParentheses(Self, OpLoc, 14026 Self.PDiag(diag::note_precedence_silence) << OpStr, 14027 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14028 SuggestParentheses(Self, OpLoc, 14029 Self.PDiag(diag::note_precedence_bitwise_first) 14030 << BinaryOperator::getOpcodeStr(Opc), 14031 ParensRange); 14032 } 14033 14034 /// It accepts a '&&' expr that is inside a '||' one. 14035 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14036 /// in parentheses. 14037 static void 14038 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14039 BinaryOperator *Bop) { 14040 assert(Bop->getOpcode() == BO_LAnd); 14041 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14042 << Bop->getSourceRange() << OpLoc; 14043 SuggestParentheses(Self, Bop->getOperatorLoc(), 14044 Self.PDiag(diag::note_precedence_silence) 14045 << Bop->getOpcodeStr(), 14046 Bop->getSourceRange()); 14047 } 14048 14049 /// Returns true if the given expression can be evaluated as a constant 14050 /// 'true'. 14051 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14052 bool Res; 14053 return !E->isValueDependent() && 14054 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14055 } 14056 14057 /// Returns true if the given expression can be evaluated as a constant 14058 /// 'false'. 14059 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14060 bool Res; 14061 return !E->isValueDependent() && 14062 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14063 } 14064 14065 /// Look for '&&' in the left hand of a '||' expr. 14066 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14067 Expr *LHSExpr, Expr *RHSExpr) { 14068 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14069 if (Bop->getOpcode() == BO_LAnd) { 14070 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14071 if (EvaluatesAsFalse(S, RHSExpr)) 14072 return; 14073 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14074 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14075 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14076 } else if (Bop->getOpcode() == BO_LOr) { 14077 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14078 // If it's "a || b && 1 || c" we didn't warn earlier for 14079 // "a || b && 1", but warn now. 14080 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14081 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14082 } 14083 } 14084 } 14085 } 14086 14087 /// Look for '&&' in the right hand of a '||' expr. 14088 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14089 Expr *LHSExpr, Expr *RHSExpr) { 14090 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14091 if (Bop->getOpcode() == BO_LAnd) { 14092 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14093 if (EvaluatesAsFalse(S, LHSExpr)) 14094 return; 14095 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14096 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14097 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14098 } 14099 } 14100 } 14101 14102 /// Look for bitwise op in the left or right hand of a bitwise op with 14103 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14104 /// the '&' expression in parentheses. 14105 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14106 SourceLocation OpLoc, Expr *SubExpr) { 14107 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14108 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14109 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14110 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14111 << Bop->getSourceRange() << OpLoc; 14112 SuggestParentheses(S, Bop->getOperatorLoc(), 14113 S.PDiag(diag::note_precedence_silence) 14114 << Bop->getOpcodeStr(), 14115 Bop->getSourceRange()); 14116 } 14117 } 14118 } 14119 14120 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14121 Expr *SubExpr, StringRef Shift) { 14122 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14123 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14124 StringRef Op = Bop->getOpcodeStr(); 14125 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14126 << Bop->getSourceRange() << OpLoc << Shift << Op; 14127 SuggestParentheses(S, Bop->getOperatorLoc(), 14128 S.PDiag(diag::note_precedence_silence) << Op, 14129 Bop->getSourceRange()); 14130 } 14131 } 14132 } 14133 14134 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14135 Expr *LHSExpr, Expr *RHSExpr) { 14136 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14137 if (!OCE) 14138 return; 14139 14140 FunctionDecl *FD = OCE->getDirectCallee(); 14141 if (!FD || !FD->isOverloadedOperator()) 14142 return; 14143 14144 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14145 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14146 return; 14147 14148 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14149 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14150 << (Kind == OO_LessLess); 14151 SuggestParentheses(S, OCE->getOperatorLoc(), 14152 S.PDiag(diag::note_precedence_silence) 14153 << (Kind == OO_LessLess ? "<<" : ">>"), 14154 OCE->getSourceRange()); 14155 SuggestParentheses( 14156 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14157 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14158 } 14159 14160 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14161 /// precedence. 14162 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14163 SourceLocation OpLoc, Expr *LHSExpr, 14164 Expr *RHSExpr){ 14165 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14166 if (BinaryOperator::isBitwiseOp(Opc)) 14167 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14168 14169 // Diagnose "arg1 & arg2 | arg3" 14170 if ((Opc == BO_Or || Opc == BO_Xor) && 14171 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14172 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14173 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14174 } 14175 14176 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14177 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14178 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14179 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14180 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14181 } 14182 14183 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14184 || Opc == BO_Shr) { 14185 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14186 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14187 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14188 } 14189 14190 // Warn on overloaded shift operators and comparisons, such as: 14191 // cout << 5 == 4; 14192 if (BinaryOperator::isComparisonOp(Opc)) 14193 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14194 } 14195 14196 // Binary Operators. 'Tok' is the token for the operator. 14197 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14198 tok::TokenKind Kind, 14199 Expr *LHSExpr, Expr *RHSExpr) { 14200 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14201 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14202 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14203 14204 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14205 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14206 14207 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14208 } 14209 14210 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14211 UnresolvedSetImpl &Functions) { 14212 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14213 if (OverOp != OO_None && OverOp != OO_Equal) 14214 LookupOverloadedOperatorName(OverOp, S, Functions); 14215 14216 // In C++20 onwards, we may have a second operator to look up. 14217 if (getLangOpts().CPlusPlus20) { 14218 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14219 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14220 } 14221 } 14222 14223 /// Build an overloaded binary operator expression in the given scope. 14224 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14225 BinaryOperatorKind Opc, 14226 Expr *LHS, Expr *RHS) { 14227 switch (Opc) { 14228 case BO_Assign: 14229 case BO_DivAssign: 14230 case BO_RemAssign: 14231 case BO_SubAssign: 14232 case BO_AndAssign: 14233 case BO_OrAssign: 14234 case BO_XorAssign: 14235 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14236 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14237 break; 14238 default: 14239 break; 14240 } 14241 14242 // Find all of the overloaded operators visible from this point. 14243 UnresolvedSet<16> Functions; 14244 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14245 14246 // Build the (potentially-overloaded, potentially-dependent) 14247 // binary operation. 14248 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14249 } 14250 14251 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14252 BinaryOperatorKind Opc, 14253 Expr *LHSExpr, Expr *RHSExpr) { 14254 ExprResult LHS, RHS; 14255 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14256 if (!LHS.isUsable() || !RHS.isUsable()) 14257 return ExprError(); 14258 LHSExpr = LHS.get(); 14259 RHSExpr = RHS.get(); 14260 14261 // We want to end up calling one of checkPseudoObjectAssignment 14262 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14263 // both expressions are overloadable or either is type-dependent), 14264 // or CreateBuiltinBinOp (in any other case). We also want to get 14265 // any placeholder types out of the way. 14266 14267 // Handle pseudo-objects in the LHS. 14268 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14269 // Assignments with a pseudo-object l-value need special analysis. 14270 if (pty->getKind() == BuiltinType::PseudoObject && 14271 BinaryOperator::isAssignmentOp(Opc)) 14272 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14273 14274 // Don't resolve overloads if the other type is overloadable. 14275 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14276 // We can't actually test that if we still have a placeholder, 14277 // though. Fortunately, none of the exceptions we see in that 14278 // code below are valid when the LHS is an overload set. Note 14279 // that an overload set can be dependently-typed, but it never 14280 // instantiates to having an overloadable type. 14281 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14282 if (resolvedRHS.isInvalid()) return ExprError(); 14283 RHSExpr = resolvedRHS.get(); 14284 14285 if (RHSExpr->isTypeDependent() || 14286 RHSExpr->getType()->isOverloadableType()) 14287 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14288 } 14289 14290 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14291 // template, diagnose the missing 'template' keyword instead of diagnosing 14292 // an invalid use of a bound member function. 14293 // 14294 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14295 // to C++1z [over.over]/1.4, but we already checked for that case above. 14296 if (Opc == BO_LT && inTemplateInstantiation() && 14297 (pty->getKind() == BuiltinType::BoundMember || 14298 pty->getKind() == BuiltinType::Overload)) { 14299 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14300 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14301 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14302 return isa<FunctionTemplateDecl>(ND); 14303 })) { 14304 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14305 : OE->getNameLoc(), 14306 diag::err_template_kw_missing) 14307 << OE->getName().getAsString() << ""; 14308 return ExprError(); 14309 } 14310 } 14311 14312 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14313 if (LHS.isInvalid()) return ExprError(); 14314 LHSExpr = LHS.get(); 14315 } 14316 14317 // Handle pseudo-objects in the RHS. 14318 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14319 // An overload in the RHS can potentially be resolved by the type 14320 // being assigned to. 14321 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14322 if (getLangOpts().CPlusPlus && 14323 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14324 LHSExpr->getType()->isOverloadableType())) 14325 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14326 14327 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14328 } 14329 14330 // Don't resolve overloads if the other type is overloadable. 14331 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14332 LHSExpr->getType()->isOverloadableType()) 14333 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14334 14335 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14336 if (!resolvedRHS.isUsable()) return ExprError(); 14337 RHSExpr = resolvedRHS.get(); 14338 } 14339 14340 if (getLangOpts().CPlusPlus) { 14341 // If either expression is type-dependent, always build an 14342 // overloaded op. 14343 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14344 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14345 14346 // Otherwise, build an overloaded op if either expression has an 14347 // overloadable type. 14348 if (LHSExpr->getType()->isOverloadableType() || 14349 RHSExpr->getType()->isOverloadableType()) 14350 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14351 } 14352 14353 if (getLangOpts().RecoveryAST && 14354 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14355 assert(!getLangOpts().CPlusPlus); 14356 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14357 "Should only occur in error-recovery path."); 14358 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14359 // C [6.15.16] p3: 14360 // An assignment expression has the value of the left operand after the 14361 // assignment, but is not an lvalue. 14362 return CompoundAssignOperator::Create( 14363 Context, LHSExpr, RHSExpr, Opc, 14364 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14365 OpLoc, CurFPFeatureOverrides()); 14366 QualType ResultType; 14367 switch (Opc) { 14368 case BO_Assign: 14369 ResultType = LHSExpr->getType().getUnqualifiedType(); 14370 break; 14371 case BO_LT: 14372 case BO_GT: 14373 case BO_LE: 14374 case BO_GE: 14375 case BO_EQ: 14376 case BO_NE: 14377 case BO_LAnd: 14378 case BO_LOr: 14379 // These operators have a fixed result type regardless of operands. 14380 ResultType = Context.IntTy; 14381 break; 14382 case BO_Comma: 14383 ResultType = RHSExpr->getType(); 14384 break; 14385 default: 14386 ResultType = Context.DependentTy; 14387 break; 14388 } 14389 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14390 VK_RValue, OK_Ordinary, OpLoc, 14391 CurFPFeatureOverrides()); 14392 } 14393 14394 // Build a built-in binary operation. 14395 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14396 } 14397 14398 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14399 if (T.isNull() || T->isDependentType()) 14400 return false; 14401 14402 if (!T->isPromotableIntegerType()) 14403 return true; 14404 14405 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14406 } 14407 14408 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14409 UnaryOperatorKind Opc, 14410 Expr *InputExpr) { 14411 ExprResult Input = InputExpr; 14412 ExprValueKind VK = VK_RValue; 14413 ExprObjectKind OK = OK_Ordinary; 14414 QualType resultType; 14415 bool CanOverflow = false; 14416 14417 bool ConvertHalfVec = false; 14418 if (getLangOpts().OpenCL) { 14419 QualType Ty = InputExpr->getType(); 14420 // The only legal unary operation for atomics is '&'. 14421 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14422 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14423 // only with a builtin functions and therefore should be disallowed here. 14424 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14425 || Ty->isBlockPointerType())) { 14426 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14427 << InputExpr->getType() 14428 << Input.get()->getSourceRange()); 14429 } 14430 } 14431 14432 switch (Opc) { 14433 case UO_PreInc: 14434 case UO_PreDec: 14435 case UO_PostInc: 14436 case UO_PostDec: 14437 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14438 OpLoc, 14439 Opc == UO_PreInc || 14440 Opc == UO_PostInc, 14441 Opc == UO_PreInc || 14442 Opc == UO_PreDec); 14443 CanOverflow = isOverflowingIntegerType(Context, resultType); 14444 break; 14445 case UO_AddrOf: 14446 resultType = CheckAddressOfOperand(Input, OpLoc); 14447 CheckAddressOfNoDeref(InputExpr); 14448 RecordModifiableNonNullParam(*this, InputExpr); 14449 break; 14450 case UO_Deref: { 14451 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14452 if (Input.isInvalid()) return ExprError(); 14453 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14454 break; 14455 } 14456 case UO_Plus: 14457 case UO_Minus: 14458 CanOverflow = Opc == UO_Minus && 14459 isOverflowingIntegerType(Context, Input.get()->getType()); 14460 Input = UsualUnaryConversions(Input.get()); 14461 if (Input.isInvalid()) return ExprError(); 14462 // Unary plus and minus require promoting an operand of half vector to a 14463 // float vector and truncating the result back to a half vector. For now, we 14464 // do this only when HalfArgsAndReturns is set (that is, when the target is 14465 // arm or arm64). 14466 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14467 14468 // If the operand is a half vector, promote it to a float vector. 14469 if (ConvertHalfVec) 14470 Input = convertVector(Input.get(), Context.FloatTy, *this); 14471 resultType = Input.get()->getType(); 14472 if (resultType->isDependentType()) 14473 break; 14474 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14475 break; 14476 else if (resultType->isVectorType() && 14477 // The z vector extensions don't allow + or - with bool vectors. 14478 (!Context.getLangOpts().ZVector || 14479 resultType->castAs<VectorType>()->getVectorKind() != 14480 VectorType::AltiVecBool)) 14481 break; 14482 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14483 Opc == UO_Plus && 14484 resultType->isPointerType()) 14485 break; 14486 14487 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14488 << resultType << Input.get()->getSourceRange()); 14489 14490 case UO_Not: // bitwise complement 14491 Input = UsualUnaryConversions(Input.get()); 14492 if (Input.isInvalid()) 14493 return ExprError(); 14494 resultType = Input.get()->getType(); 14495 if (resultType->isDependentType()) 14496 break; 14497 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14498 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14499 // C99 does not support '~' for complex conjugation. 14500 Diag(OpLoc, diag::ext_integer_complement_complex) 14501 << resultType << Input.get()->getSourceRange(); 14502 else if (resultType->hasIntegerRepresentation()) 14503 break; 14504 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14505 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14506 // on vector float types. 14507 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14508 if (!T->isIntegerType()) 14509 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14510 << resultType << Input.get()->getSourceRange()); 14511 } else { 14512 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14513 << resultType << Input.get()->getSourceRange()); 14514 } 14515 break; 14516 14517 case UO_LNot: // logical negation 14518 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14519 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14520 if (Input.isInvalid()) return ExprError(); 14521 resultType = Input.get()->getType(); 14522 14523 // Though we still have to promote half FP to float... 14524 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14525 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14526 resultType = Context.FloatTy; 14527 } 14528 14529 if (resultType->isDependentType()) 14530 break; 14531 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14532 // C99 6.5.3.3p1: ok, fallthrough; 14533 if (Context.getLangOpts().CPlusPlus) { 14534 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14535 // operand contextually converted to bool. 14536 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14537 ScalarTypeToBooleanCastKind(resultType)); 14538 } else if (Context.getLangOpts().OpenCL && 14539 Context.getLangOpts().OpenCLVersion < 120) { 14540 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14541 // operate on scalar float types. 14542 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14543 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14544 << resultType << Input.get()->getSourceRange()); 14545 } 14546 } else if (resultType->isExtVectorType()) { 14547 if (Context.getLangOpts().OpenCL && 14548 Context.getLangOpts().OpenCLVersion < 120 && 14549 !Context.getLangOpts().OpenCLCPlusPlus) { 14550 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14551 // operate on vector float types. 14552 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14553 if (!T->isIntegerType()) 14554 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14555 << resultType << Input.get()->getSourceRange()); 14556 } 14557 // Vector logical not returns the signed variant of the operand type. 14558 resultType = GetSignedVectorType(resultType); 14559 break; 14560 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14561 const VectorType *VTy = resultType->castAs<VectorType>(); 14562 if (VTy->getVectorKind() != VectorType::GenericVector) 14563 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14564 << resultType << Input.get()->getSourceRange()); 14565 14566 // Vector logical not returns the signed variant of the operand type. 14567 resultType = GetSignedVectorType(resultType); 14568 break; 14569 } else { 14570 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14571 << resultType << Input.get()->getSourceRange()); 14572 } 14573 14574 // LNot always has type int. C99 6.5.3.3p5. 14575 // In C++, it's bool. C++ 5.3.1p8 14576 resultType = Context.getLogicalOperationType(); 14577 break; 14578 case UO_Real: 14579 case UO_Imag: 14580 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14581 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14582 // complex l-values to ordinary l-values and all other values to r-values. 14583 if (Input.isInvalid()) return ExprError(); 14584 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14585 if (Input.get()->getValueKind() != VK_RValue && 14586 Input.get()->getObjectKind() == OK_Ordinary) 14587 VK = Input.get()->getValueKind(); 14588 } else if (!getLangOpts().CPlusPlus) { 14589 // In C, a volatile scalar is read by __imag. In C++, it is not. 14590 Input = DefaultLvalueConversion(Input.get()); 14591 } 14592 break; 14593 case UO_Extension: 14594 resultType = Input.get()->getType(); 14595 VK = Input.get()->getValueKind(); 14596 OK = Input.get()->getObjectKind(); 14597 break; 14598 case UO_Coawait: 14599 // It's unnecessary to represent the pass-through operator co_await in the 14600 // AST; just return the input expression instead. 14601 assert(!Input.get()->getType()->isDependentType() && 14602 "the co_await expression must be non-dependant before " 14603 "building operator co_await"); 14604 return Input; 14605 } 14606 if (resultType.isNull() || Input.isInvalid()) 14607 return ExprError(); 14608 14609 // Check for array bounds violations in the operand of the UnaryOperator, 14610 // except for the '*' and '&' operators that have to be handled specially 14611 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14612 // that are explicitly defined as valid by the standard). 14613 if (Opc != UO_AddrOf && Opc != UO_Deref) 14614 CheckArrayAccess(Input.get()); 14615 14616 auto *UO = 14617 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14618 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14619 14620 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14621 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14622 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14623 14624 // Convert the result back to a half vector. 14625 if (ConvertHalfVec) 14626 return convertVector(UO, Context.HalfTy, *this); 14627 return UO; 14628 } 14629 14630 /// Determine whether the given expression is a qualified member 14631 /// access expression, of a form that could be turned into a pointer to member 14632 /// with the address-of operator. 14633 bool Sema::isQualifiedMemberAccess(Expr *E) { 14634 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14635 if (!DRE->getQualifier()) 14636 return false; 14637 14638 ValueDecl *VD = DRE->getDecl(); 14639 if (!VD->isCXXClassMember()) 14640 return false; 14641 14642 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14643 return true; 14644 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14645 return Method->isInstance(); 14646 14647 return false; 14648 } 14649 14650 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14651 if (!ULE->getQualifier()) 14652 return false; 14653 14654 for (NamedDecl *D : ULE->decls()) { 14655 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14656 if (Method->isInstance()) 14657 return true; 14658 } else { 14659 // Overload set does not contain methods. 14660 break; 14661 } 14662 } 14663 14664 return false; 14665 } 14666 14667 return false; 14668 } 14669 14670 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14671 UnaryOperatorKind Opc, Expr *Input) { 14672 // First things first: handle placeholders so that the 14673 // overloaded-operator check considers the right type. 14674 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14675 // Increment and decrement of pseudo-object references. 14676 if (pty->getKind() == BuiltinType::PseudoObject && 14677 UnaryOperator::isIncrementDecrementOp(Opc)) 14678 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14679 14680 // extension is always a builtin operator. 14681 if (Opc == UO_Extension) 14682 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14683 14684 // & gets special logic for several kinds of placeholder. 14685 // The builtin code knows what to do. 14686 if (Opc == UO_AddrOf && 14687 (pty->getKind() == BuiltinType::Overload || 14688 pty->getKind() == BuiltinType::UnknownAny || 14689 pty->getKind() == BuiltinType::BoundMember)) 14690 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14691 14692 // Anything else needs to be handled now. 14693 ExprResult Result = CheckPlaceholderExpr(Input); 14694 if (Result.isInvalid()) return ExprError(); 14695 Input = Result.get(); 14696 } 14697 14698 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14699 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14700 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14701 // Find all of the overloaded operators visible from this point. 14702 UnresolvedSet<16> Functions; 14703 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14704 if (S && OverOp != OO_None) 14705 LookupOverloadedOperatorName(OverOp, S, Functions); 14706 14707 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14708 } 14709 14710 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14711 } 14712 14713 // Unary Operators. 'Tok' is the token for the operator. 14714 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14715 tok::TokenKind Op, Expr *Input) { 14716 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14717 } 14718 14719 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14720 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14721 LabelDecl *TheDecl) { 14722 TheDecl->markUsed(Context); 14723 // Create the AST node. The address of a label always has type 'void*'. 14724 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14725 Context.getPointerType(Context.VoidTy)); 14726 } 14727 14728 void Sema::ActOnStartStmtExpr() { 14729 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14730 } 14731 14732 void Sema::ActOnStmtExprError() { 14733 // Note that function is also called by TreeTransform when leaving a 14734 // StmtExpr scope without rebuilding anything. 14735 14736 DiscardCleanupsInEvaluationContext(); 14737 PopExpressionEvaluationContext(); 14738 } 14739 14740 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14741 SourceLocation RPLoc) { 14742 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14743 } 14744 14745 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14746 SourceLocation RPLoc, unsigned TemplateDepth) { 14747 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14748 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14749 14750 if (hasAnyUnrecoverableErrorsInThisFunction()) 14751 DiscardCleanupsInEvaluationContext(); 14752 assert(!Cleanup.exprNeedsCleanups() && 14753 "cleanups within StmtExpr not correctly bound!"); 14754 PopExpressionEvaluationContext(); 14755 14756 // FIXME: there are a variety of strange constraints to enforce here, for 14757 // example, it is not possible to goto into a stmt expression apparently. 14758 // More semantic analysis is needed. 14759 14760 // If there are sub-stmts in the compound stmt, take the type of the last one 14761 // as the type of the stmtexpr. 14762 QualType Ty = Context.VoidTy; 14763 bool StmtExprMayBindToTemp = false; 14764 if (!Compound->body_empty()) { 14765 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14766 if (const auto *LastStmt = 14767 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14768 if (const Expr *Value = LastStmt->getExprStmt()) { 14769 StmtExprMayBindToTemp = true; 14770 Ty = Value->getType(); 14771 } 14772 } 14773 } 14774 14775 // FIXME: Check that expression type is complete/non-abstract; statement 14776 // expressions are not lvalues. 14777 Expr *ResStmtExpr = 14778 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14779 if (StmtExprMayBindToTemp) 14780 return MaybeBindToTemporary(ResStmtExpr); 14781 return ResStmtExpr; 14782 } 14783 14784 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14785 if (ER.isInvalid()) 14786 return ExprError(); 14787 14788 // Do function/array conversion on the last expression, but not 14789 // lvalue-to-rvalue. However, initialize an unqualified type. 14790 ER = DefaultFunctionArrayConversion(ER.get()); 14791 if (ER.isInvalid()) 14792 return ExprError(); 14793 Expr *E = ER.get(); 14794 14795 if (E->isTypeDependent()) 14796 return E; 14797 14798 // In ARC, if the final expression ends in a consume, splice 14799 // the consume out and bind it later. In the alternate case 14800 // (when dealing with a retainable type), the result 14801 // initialization will create a produce. In both cases the 14802 // result will be +1, and we'll need to balance that out with 14803 // a bind. 14804 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14805 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14806 return Cast->getSubExpr(); 14807 14808 // FIXME: Provide a better location for the initialization. 14809 return PerformCopyInitialization( 14810 InitializedEntity::InitializeStmtExprResult( 14811 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14812 SourceLocation(), E); 14813 } 14814 14815 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14816 TypeSourceInfo *TInfo, 14817 ArrayRef<OffsetOfComponent> Components, 14818 SourceLocation RParenLoc) { 14819 QualType ArgTy = TInfo->getType(); 14820 bool Dependent = ArgTy->isDependentType(); 14821 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14822 14823 // We must have at least one component that refers to the type, and the first 14824 // one is known to be a field designator. Verify that the ArgTy represents 14825 // a struct/union/class. 14826 if (!Dependent && !ArgTy->isRecordType()) 14827 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14828 << ArgTy << TypeRange); 14829 14830 // Type must be complete per C99 7.17p3 because a declaring a variable 14831 // with an incomplete type would be ill-formed. 14832 if (!Dependent 14833 && RequireCompleteType(BuiltinLoc, ArgTy, 14834 diag::err_offsetof_incomplete_type, TypeRange)) 14835 return ExprError(); 14836 14837 bool DidWarnAboutNonPOD = false; 14838 QualType CurrentType = ArgTy; 14839 SmallVector<OffsetOfNode, 4> Comps; 14840 SmallVector<Expr*, 4> Exprs; 14841 for (const OffsetOfComponent &OC : Components) { 14842 if (OC.isBrackets) { 14843 // Offset of an array sub-field. TODO: Should we allow vector elements? 14844 if (!CurrentType->isDependentType()) { 14845 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14846 if(!AT) 14847 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14848 << CurrentType); 14849 CurrentType = AT->getElementType(); 14850 } else 14851 CurrentType = Context.DependentTy; 14852 14853 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14854 if (IdxRval.isInvalid()) 14855 return ExprError(); 14856 Expr *Idx = IdxRval.get(); 14857 14858 // The expression must be an integral expression. 14859 // FIXME: An integral constant expression? 14860 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14861 !Idx->getType()->isIntegerType()) 14862 return ExprError( 14863 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14864 << Idx->getSourceRange()); 14865 14866 // Record this array index. 14867 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14868 Exprs.push_back(Idx); 14869 continue; 14870 } 14871 14872 // Offset of a field. 14873 if (CurrentType->isDependentType()) { 14874 // We have the offset of a field, but we can't look into the dependent 14875 // type. Just record the identifier of the field. 14876 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14877 CurrentType = Context.DependentTy; 14878 continue; 14879 } 14880 14881 // We need to have a complete type to look into. 14882 if (RequireCompleteType(OC.LocStart, CurrentType, 14883 diag::err_offsetof_incomplete_type)) 14884 return ExprError(); 14885 14886 // Look for the designated field. 14887 const RecordType *RC = CurrentType->getAs<RecordType>(); 14888 if (!RC) 14889 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14890 << CurrentType); 14891 RecordDecl *RD = RC->getDecl(); 14892 14893 // C++ [lib.support.types]p5: 14894 // The macro offsetof accepts a restricted set of type arguments in this 14895 // International Standard. type shall be a POD structure or a POD union 14896 // (clause 9). 14897 // C++11 [support.types]p4: 14898 // If type is not a standard-layout class (Clause 9), the results are 14899 // undefined. 14900 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14901 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14902 unsigned DiagID = 14903 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14904 : diag::ext_offsetof_non_pod_type; 14905 14906 if (!IsSafe && !DidWarnAboutNonPOD && 14907 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14908 PDiag(DiagID) 14909 << SourceRange(Components[0].LocStart, OC.LocEnd) 14910 << CurrentType)) 14911 DidWarnAboutNonPOD = true; 14912 } 14913 14914 // Look for the field. 14915 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14916 LookupQualifiedName(R, RD); 14917 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14918 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14919 if (!MemberDecl) { 14920 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14921 MemberDecl = IndirectMemberDecl->getAnonField(); 14922 } 14923 14924 if (!MemberDecl) 14925 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14926 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14927 OC.LocEnd)); 14928 14929 // C99 7.17p3: 14930 // (If the specified member is a bit-field, the behavior is undefined.) 14931 // 14932 // We diagnose this as an error. 14933 if (MemberDecl->isBitField()) { 14934 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14935 << MemberDecl->getDeclName() 14936 << SourceRange(BuiltinLoc, RParenLoc); 14937 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14938 return ExprError(); 14939 } 14940 14941 RecordDecl *Parent = MemberDecl->getParent(); 14942 if (IndirectMemberDecl) 14943 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14944 14945 // If the member was found in a base class, introduce OffsetOfNodes for 14946 // the base class indirections. 14947 CXXBasePaths Paths; 14948 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14949 Paths)) { 14950 if (Paths.getDetectedVirtual()) { 14951 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14952 << MemberDecl->getDeclName() 14953 << SourceRange(BuiltinLoc, RParenLoc); 14954 return ExprError(); 14955 } 14956 14957 CXXBasePath &Path = Paths.front(); 14958 for (const CXXBasePathElement &B : Path) 14959 Comps.push_back(OffsetOfNode(B.Base)); 14960 } 14961 14962 if (IndirectMemberDecl) { 14963 for (auto *FI : IndirectMemberDecl->chain()) { 14964 assert(isa<FieldDecl>(FI)); 14965 Comps.push_back(OffsetOfNode(OC.LocStart, 14966 cast<FieldDecl>(FI), OC.LocEnd)); 14967 } 14968 } else 14969 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14970 14971 CurrentType = MemberDecl->getType().getNonReferenceType(); 14972 } 14973 14974 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14975 Comps, Exprs, RParenLoc); 14976 } 14977 14978 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14979 SourceLocation BuiltinLoc, 14980 SourceLocation TypeLoc, 14981 ParsedType ParsedArgTy, 14982 ArrayRef<OffsetOfComponent> Components, 14983 SourceLocation RParenLoc) { 14984 14985 TypeSourceInfo *ArgTInfo; 14986 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14987 if (ArgTy.isNull()) 14988 return ExprError(); 14989 14990 if (!ArgTInfo) 14991 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14992 14993 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14994 } 14995 14996 14997 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14998 Expr *CondExpr, 14999 Expr *LHSExpr, Expr *RHSExpr, 15000 SourceLocation RPLoc) { 15001 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15002 15003 ExprValueKind VK = VK_RValue; 15004 ExprObjectKind OK = OK_Ordinary; 15005 QualType resType; 15006 bool CondIsTrue = false; 15007 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15008 resType = Context.DependentTy; 15009 } else { 15010 // The conditional expression is required to be a constant expression. 15011 llvm::APSInt condEval(32); 15012 ExprResult CondICE = VerifyIntegerConstantExpression( 15013 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15014 if (CondICE.isInvalid()) 15015 return ExprError(); 15016 CondExpr = CondICE.get(); 15017 CondIsTrue = condEval.getZExtValue(); 15018 15019 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15020 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15021 15022 resType = ActiveExpr->getType(); 15023 VK = ActiveExpr->getValueKind(); 15024 OK = ActiveExpr->getObjectKind(); 15025 } 15026 15027 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15028 resType, VK, OK, RPLoc, CondIsTrue); 15029 } 15030 15031 //===----------------------------------------------------------------------===// 15032 // Clang Extensions. 15033 //===----------------------------------------------------------------------===// 15034 15035 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15036 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15037 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15038 15039 if (LangOpts.CPlusPlus) { 15040 MangleNumberingContext *MCtx; 15041 Decl *ManglingContextDecl; 15042 std::tie(MCtx, ManglingContextDecl) = 15043 getCurrentMangleNumberContext(Block->getDeclContext()); 15044 if (MCtx) { 15045 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15046 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15047 } 15048 } 15049 15050 PushBlockScope(CurScope, Block); 15051 CurContext->addDecl(Block); 15052 if (CurScope) 15053 PushDeclContext(CurScope, Block); 15054 else 15055 CurContext = Block; 15056 15057 getCurBlock()->HasImplicitReturnType = true; 15058 15059 // Enter a new evaluation context to insulate the block from any 15060 // cleanups from the enclosing full-expression. 15061 PushExpressionEvaluationContext( 15062 ExpressionEvaluationContext::PotentiallyEvaluated); 15063 } 15064 15065 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15066 Scope *CurScope) { 15067 assert(ParamInfo.getIdentifier() == nullptr && 15068 "block-id should have no identifier!"); 15069 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 15070 BlockScopeInfo *CurBlock = getCurBlock(); 15071 15072 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15073 QualType T = Sig->getType(); 15074 15075 // FIXME: We should allow unexpanded parameter packs here, but that would, 15076 // in turn, make the block expression contain unexpanded parameter packs. 15077 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15078 // Drop the parameters. 15079 FunctionProtoType::ExtProtoInfo EPI; 15080 EPI.HasTrailingReturn = false; 15081 EPI.TypeQuals.addConst(); 15082 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15083 Sig = Context.getTrivialTypeSourceInfo(T); 15084 } 15085 15086 // GetTypeForDeclarator always produces a function type for a block 15087 // literal signature. Furthermore, it is always a FunctionProtoType 15088 // unless the function was written with a typedef. 15089 assert(T->isFunctionType() && 15090 "GetTypeForDeclarator made a non-function block signature"); 15091 15092 // Look for an explicit signature in that function type. 15093 FunctionProtoTypeLoc ExplicitSignature; 15094 15095 if ((ExplicitSignature = Sig->getTypeLoc() 15096 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15097 15098 // Check whether that explicit signature was synthesized by 15099 // GetTypeForDeclarator. If so, don't save that as part of the 15100 // written signature. 15101 if (ExplicitSignature.getLocalRangeBegin() == 15102 ExplicitSignature.getLocalRangeEnd()) { 15103 // This would be much cheaper if we stored TypeLocs instead of 15104 // TypeSourceInfos. 15105 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15106 unsigned Size = Result.getFullDataSize(); 15107 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15108 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15109 15110 ExplicitSignature = FunctionProtoTypeLoc(); 15111 } 15112 } 15113 15114 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15115 CurBlock->FunctionType = T; 15116 15117 const FunctionType *Fn = T->getAs<FunctionType>(); 15118 QualType RetTy = Fn->getReturnType(); 15119 bool isVariadic = 15120 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15121 15122 CurBlock->TheDecl->setIsVariadic(isVariadic); 15123 15124 // Context.DependentTy is used as a placeholder for a missing block 15125 // return type. TODO: what should we do with declarators like: 15126 // ^ * { ... } 15127 // If the answer is "apply template argument deduction".... 15128 if (RetTy != Context.DependentTy) { 15129 CurBlock->ReturnType = RetTy; 15130 CurBlock->TheDecl->setBlockMissingReturnType(false); 15131 CurBlock->HasImplicitReturnType = false; 15132 } 15133 15134 // Push block parameters from the declarator if we had them. 15135 SmallVector<ParmVarDecl*, 8> Params; 15136 if (ExplicitSignature) { 15137 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15138 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15139 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15140 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15141 // Diagnose this as an extension in C17 and earlier. 15142 if (!getLangOpts().C2x) 15143 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15144 } 15145 Params.push_back(Param); 15146 } 15147 15148 // Fake up parameter variables if we have a typedef, like 15149 // ^ fntype { ... } 15150 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15151 for (const auto &I : Fn->param_types()) { 15152 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15153 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15154 Params.push_back(Param); 15155 } 15156 } 15157 15158 // Set the parameters on the block decl. 15159 if (!Params.empty()) { 15160 CurBlock->TheDecl->setParams(Params); 15161 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15162 /*CheckParameterNames=*/false); 15163 } 15164 15165 // Finally we can process decl attributes. 15166 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15167 15168 // Put the parameter variables in scope. 15169 for (auto AI : CurBlock->TheDecl->parameters()) { 15170 AI->setOwningFunction(CurBlock->TheDecl); 15171 15172 // If this has an identifier, add it to the scope stack. 15173 if (AI->getIdentifier()) { 15174 CheckShadow(CurBlock->TheScope, AI); 15175 15176 PushOnScopeChains(AI, CurBlock->TheScope); 15177 } 15178 } 15179 } 15180 15181 /// ActOnBlockError - If there is an error parsing a block, this callback 15182 /// is invoked to pop the information about the block from the action impl. 15183 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15184 // Leave the expression-evaluation context. 15185 DiscardCleanupsInEvaluationContext(); 15186 PopExpressionEvaluationContext(); 15187 15188 // Pop off CurBlock, handle nested blocks. 15189 PopDeclContext(); 15190 PopFunctionScopeInfo(); 15191 } 15192 15193 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15194 /// literal was successfully completed. ^(int x){...} 15195 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15196 Stmt *Body, Scope *CurScope) { 15197 // If blocks are disabled, emit an error. 15198 if (!LangOpts.Blocks) 15199 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15200 15201 // Leave the expression-evaluation context. 15202 if (hasAnyUnrecoverableErrorsInThisFunction()) 15203 DiscardCleanupsInEvaluationContext(); 15204 assert(!Cleanup.exprNeedsCleanups() && 15205 "cleanups within block not correctly bound!"); 15206 PopExpressionEvaluationContext(); 15207 15208 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15209 BlockDecl *BD = BSI->TheDecl; 15210 15211 if (BSI->HasImplicitReturnType) 15212 deduceClosureReturnType(*BSI); 15213 15214 QualType RetTy = Context.VoidTy; 15215 if (!BSI->ReturnType.isNull()) 15216 RetTy = BSI->ReturnType; 15217 15218 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15219 QualType BlockTy; 15220 15221 // If the user wrote a function type in some form, try to use that. 15222 if (!BSI->FunctionType.isNull()) { 15223 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15224 15225 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15226 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15227 15228 // Turn protoless block types into nullary block types. 15229 if (isa<FunctionNoProtoType>(FTy)) { 15230 FunctionProtoType::ExtProtoInfo EPI; 15231 EPI.ExtInfo = Ext; 15232 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15233 15234 // Otherwise, if we don't need to change anything about the function type, 15235 // preserve its sugar structure. 15236 } else if (FTy->getReturnType() == RetTy && 15237 (!NoReturn || FTy->getNoReturnAttr())) { 15238 BlockTy = BSI->FunctionType; 15239 15240 // Otherwise, make the minimal modifications to the function type. 15241 } else { 15242 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15243 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15244 EPI.TypeQuals = Qualifiers(); 15245 EPI.ExtInfo = Ext; 15246 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15247 } 15248 15249 // If we don't have a function type, just build one from nothing. 15250 } else { 15251 FunctionProtoType::ExtProtoInfo EPI; 15252 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15253 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15254 } 15255 15256 DiagnoseUnusedParameters(BD->parameters()); 15257 BlockTy = Context.getBlockPointerType(BlockTy); 15258 15259 // If needed, diagnose invalid gotos and switches in the block. 15260 if (getCurFunction()->NeedsScopeChecking() && 15261 !PP.isCodeCompletionEnabled()) 15262 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15263 15264 BD->setBody(cast<CompoundStmt>(Body)); 15265 15266 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15267 DiagnoseUnguardedAvailabilityViolations(BD); 15268 15269 // Try to apply the named return value optimization. We have to check again 15270 // if we can do this, though, because blocks keep return statements around 15271 // to deduce an implicit return type. 15272 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15273 !BD->isDependentContext()) 15274 computeNRVO(Body, BSI); 15275 15276 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15277 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15278 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15279 NTCUK_Destruct|NTCUK_Copy); 15280 15281 PopDeclContext(); 15282 15283 // Pop the block scope now but keep it alive to the end of this function. 15284 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15285 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15286 15287 // Set the captured variables on the block. 15288 SmallVector<BlockDecl::Capture, 4> Captures; 15289 for (Capture &Cap : BSI->Captures) { 15290 if (Cap.isInvalid() || Cap.isThisCapture()) 15291 continue; 15292 15293 VarDecl *Var = Cap.getVariable(); 15294 Expr *CopyExpr = nullptr; 15295 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15296 if (const RecordType *Record = 15297 Cap.getCaptureType()->getAs<RecordType>()) { 15298 // The capture logic needs the destructor, so make sure we mark it. 15299 // Usually this is unnecessary because most local variables have 15300 // their destructors marked at declaration time, but parameters are 15301 // an exception because it's technically only the call site that 15302 // actually requires the destructor. 15303 if (isa<ParmVarDecl>(Var)) 15304 FinalizeVarWithDestructor(Var, Record); 15305 15306 // Enter a separate potentially-evaluated context while building block 15307 // initializers to isolate their cleanups from those of the block 15308 // itself. 15309 // FIXME: Is this appropriate even when the block itself occurs in an 15310 // unevaluated operand? 15311 EnterExpressionEvaluationContext EvalContext( 15312 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15313 15314 SourceLocation Loc = Cap.getLocation(); 15315 15316 ExprResult Result = BuildDeclarationNameExpr( 15317 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15318 15319 // According to the blocks spec, the capture of a variable from 15320 // the stack requires a const copy constructor. This is not true 15321 // of the copy/move done to move a __block variable to the heap. 15322 if (!Result.isInvalid() && 15323 !Result.get()->getType().isConstQualified()) { 15324 Result = ImpCastExprToType(Result.get(), 15325 Result.get()->getType().withConst(), 15326 CK_NoOp, VK_LValue); 15327 } 15328 15329 if (!Result.isInvalid()) { 15330 Result = PerformCopyInitialization( 15331 InitializedEntity::InitializeBlock(Var->getLocation(), 15332 Cap.getCaptureType(), false), 15333 Loc, Result.get()); 15334 } 15335 15336 // Build a full-expression copy expression if initialization 15337 // succeeded and used a non-trivial constructor. Recover from 15338 // errors by pretending that the copy isn't necessary. 15339 if (!Result.isInvalid() && 15340 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15341 ->isTrivial()) { 15342 Result = MaybeCreateExprWithCleanups(Result); 15343 CopyExpr = Result.get(); 15344 } 15345 } 15346 } 15347 15348 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15349 CopyExpr); 15350 Captures.push_back(NewCap); 15351 } 15352 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15353 15354 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15355 15356 // If the block isn't obviously global, i.e. it captures anything at 15357 // all, then we need to do a few things in the surrounding context: 15358 if (Result->getBlockDecl()->hasCaptures()) { 15359 // First, this expression has a new cleanup object. 15360 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15361 Cleanup.setExprNeedsCleanups(true); 15362 15363 // It also gets a branch-protected scope if any of the captured 15364 // variables needs destruction. 15365 for (const auto &CI : Result->getBlockDecl()->captures()) { 15366 const VarDecl *var = CI.getVariable(); 15367 if (var->getType().isDestructedType() != QualType::DK_none) { 15368 setFunctionHasBranchProtectedScope(); 15369 break; 15370 } 15371 } 15372 } 15373 15374 if (getCurFunction()) 15375 getCurFunction()->addBlock(BD); 15376 15377 return Result; 15378 } 15379 15380 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15381 SourceLocation RPLoc) { 15382 TypeSourceInfo *TInfo; 15383 GetTypeFromParser(Ty, &TInfo); 15384 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15385 } 15386 15387 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15388 Expr *E, TypeSourceInfo *TInfo, 15389 SourceLocation RPLoc) { 15390 Expr *OrigExpr = E; 15391 bool IsMS = false; 15392 15393 // CUDA device code does not support varargs. 15394 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15395 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15396 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15397 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15398 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15399 } 15400 } 15401 15402 // NVPTX does not support va_arg expression. 15403 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15404 Context.getTargetInfo().getTriple().isNVPTX()) 15405 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15406 15407 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15408 // as Microsoft ABI on an actual Microsoft platform, where 15409 // __builtin_ms_va_list and __builtin_va_list are the same.) 15410 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15411 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15412 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15413 if (Context.hasSameType(MSVaListType, E->getType())) { 15414 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15415 return ExprError(); 15416 IsMS = true; 15417 } 15418 } 15419 15420 // Get the va_list type 15421 QualType VaListType = Context.getBuiltinVaListType(); 15422 if (!IsMS) { 15423 if (VaListType->isArrayType()) { 15424 // Deal with implicit array decay; for example, on x86-64, 15425 // va_list is an array, but it's supposed to decay to 15426 // a pointer for va_arg. 15427 VaListType = Context.getArrayDecayedType(VaListType); 15428 // Make sure the input expression also decays appropriately. 15429 ExprResult Result = UsualUnaryConversions(E); 15430 if (Result.isInvalid()) 15431 return ExprError(); 15432 E = Result.get(); 15433 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15434 // If va_list is a record type and we are compiling in C++ mode, 15435 // check the argument using reference binding. 15436 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15437 Context, Context.getLValueReferenceType(VaListType), false); 15438 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15439 if (Init.isInvalid()) 15440 return ExprError(); 15441 E = Init.getAs<Expr>(); 15442 } else { 15443 // Otherwise, the va_list argument must be an l-value because 15444 // it is modified by va_arg. 15445 if (!E->isTypeDependent() && 15446 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15447 return ExprError(); 15448 } 15449 } 15450 15451 if (!IsMS && !E->isTypeDependent() && 15452 !Context.hasSameType(VaListType, E->getType())) 15453 return ExprError( 15454 Diag(E->getBeginLoc(), 15455 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15456 << OrigExpr->getType() << E->getSourceRange()); 15457 15458 if (!TInfo->getType()->isDependentType()) { 15459 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15460 diag::err_second_parameter_to_va_arg_incomplete, 15461 TInfo->getTypeLoc())) 15462 return ExprError(); 15463 15464 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15465 TInfo->getType(), 15466 diag::err_second_parameter_to_va_arg_abstract, 15467 TInfo->getTypeLoc())) 15468 return ExprError(); 15469 15470 if (!TInfo->getType().isPODType(Context)) { 15471 Diag(TInfo->getTypeLoc().getBeginLoc(), 15472 TInfo->getType()->isObjCLifetimeType() 15473 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15474 : diag::warn_second_parameter_to_va_arg_not_pod) 15475 << TInfo->getType() 15476 << TInfo->getTypeLoc().getSourceRange(); 15477 } 15478 15479 // Check for va_arg where arguments of the given type will be promoted 15480 // (i.e. this va_arg is guaranteed to have undefined behavior). 15481 QualType PromoteType; 15482 if (TInfo->getType()->isPromotableIntegerType()) { 15483 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15484 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15485 PromoteType = QualType(); 15486 } 15487 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15488 PromoteType = Context.DoubleTy; 15489 if (!PromoteType.isNull()) 15490 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15491 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15492 << TInfo->getType() 15493 << PromoteType 15494 << TInfo->getTypeLoc().getSourceRange()); 15495 } 15496 15497 QualType T = TInfo->getType().getNonLValueExprType(Context); 15498 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15499 } 15500 15501 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15502 // The type of __null will be int or long, depending on the size of 15503 // pointers on the target. 15504 QualType Ty; 15505 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15506 if (pw == Context.getTargetInfo().getIntWidth()) 15507 Ty = Context.IntTy; 15508 else if (pw == Context.getTargetInfo().getLongWidth()) 15509 Ty = Context.LongTy; 15510 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15511 Ty = Context.LongLongTy; 15512 else { 15513 llvm_unreachable("I don't know size of pointer!"); 15514 } 15515 15516 return new (Context) GNUNullExpr(Ty, TokenLoc); 15517 } 15518 15519 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15520 SourceLocation BuiltinLoc, 15521 SourceLocation RPLoc) { 15522 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15523 } 15524 15525 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15526 SourceLocation BuiltinLoc, 15527 SourceLocation RPLoc, 15528 DeclContext *ParentContext) { 15529 return new (Context) 15530 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15531 } 15532 15533 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15534 bool Diagnose) { 15535 if (!getLangOpts().ObjC) 15536 return false; 15537 15538 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15539 if (!PT) 15540 return false; 15541 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15542 15543 // Ignore any parens, implicit casts (should only be 15544 // array-to-pointer decays), and not-so-opaque values. The last is 15545 // important for making this trigger for property assignments. 15546 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15547 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15548 if (OV->getSourceExpr()) 15549 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15550 15551 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15552 if (!PT->isObjCIdType() && 15553 !(ID && ID->getIdentifier()->isStr("NSString"))) 15554 return false; 15555 if (!SL->isAscii()) 15556 return false; 15557 15558 if (Diagnose) { 15559 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15560 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15561 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15562 } 15563 return true; 15564 } 15565 15566 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15567 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15568 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15569 !SrcExpr->isNullPointerConstant( 15570 getASTContext(), Expr::NPC_NeverValueDependent)) { 15571 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15572 return false; 15573 if (Diagnose) { 15574 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15575 << /*number*/1 15576 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15577 Expr *NumLit = 15578 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15579 if (NumLit) 15580 Exp = NumLit; 15581 } 15582 return true; 15583 } 15584 15585 return false; 15586 } 15587 15588 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15589 const Expr *SrcExpr) { 15590 if (!DstType->isFunctionPointerType() || 15591 !SrcExpr->getType()->isFunctionType()) 15592 return false; 15593 15594 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15595 if (!DRE) 15596 return false; 15597 15598 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15599 if (!FD) 15600 return false; 15601 15602 return !S.checkAddressOfFunctionIsAvailable(FD, 15603 /*Complain=*/true, 15604 SrcExpr->getBeginLoc()); 15605 } 15606 15607 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15608 SourceLocation Loc, 15609 QualType DstType, QualType SrcType, 15610 Expr *SrcExpr, AssignmentAction Action, 15611 bool *Complained) { 15612 if (Complained) 15613 *Complained = false; 15614 15615 // Decode the result (notice that AST's are still created for extensions). 15616 bool CheckInferredResultType = false; 15617 bool isInvalid = false; 15618 unsigned DiagKind = 0; 15619 ConversionFixItGenerator ConvHints; 15620 bool MayHaveConvFixit = false; 15621 bool MayHaveFunctionDiff = false; 15622 const ObjCInterfaceDecl *IFace = nullptr; 15623 const ObjCProtocolDecl *PDecl = nullptr; 15624 15625 switch (ConvTy) { 15626 case Compatible: 15627 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15628 return false; 15629 15630 case PointerToInt: 15631 if (getLangOpts().CPlusPlus) { 15632 DiagKind = diag::err_typecheck_convert_pointer_int; 15633 isInvalid = true; 15634 } else { 15635 DiagKind = diag::ext_typecheck_convert_pointer_int; 15636 } 15637 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15638 MayHaveConvFixit = true; 15639 break; 15640 case IntToPointer: 15641 if (getLangOpts().CPlusPlus) { 15642 DiagKind = diag::err_typecheck_convert_int_pointer; 15643 isInvalid = true; 15644 } else { 15645 DiagKind = diag::ext_typecheck_convert_int_pointer; 15646 } 15647 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15648 MayHaveConvFixit = true; 15649 break; 15650 case IncompatibleFunctionPointer: 15651 if (getLangOpts().CPlusPlus) { 15652 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15653 isInvalid = true; 15654 } else { 15655 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15656 } 15657 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15658 MayHaveConvFixit = true; 15659 break; 15660 case IncompatiblePointer: 15661 if (Action == AA_Passing_CFAudited) { 15662 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15663 } else if (getLangOpts().CPlusPlus) { 15664 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15665 isInvalid = true; 15666 } else { 15667 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15668 } 15669 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15670 SrcType->isObjCObjectPointerType(); 15671 if (!CheckInferredResultType) { 15672 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15673 } else if (CheckInferredResultType) { 15674 SrcType = SrcType.getUnqualifiedType(); 15675 DstType = DstType.getUnqualifiedType(); 15676 } 15677 MayHaveConvFixit = true; 15678 break; 15679 case IncompatiblePointerSign: 15680 if (getLangOpts().CPlusPlus) { 15681 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15682 isInvalid = true; 15683 } else { 15684 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15685 } 15686 break; 15687 case FunctionVoidPointer: 15688 if (getLangOpts().CPlusPlus) { 15689 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15690 isInvalid = true; 15691 } else { 15692 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15693 } 15694 break; 15695 case IncompatiblePointerDiscardsQualifiers: { 15696 // Perform array-to-pointer decay if necessary. 15697 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15698 15699 isInvalid = true; 15700 15701 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15702 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15703 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15704 DiagKind = diag::err_typecheck_incompatible_address_space; 15705 break; 15706 15707 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15708 DiagKind = diag::err_typecheck_incompatible_ownership; 15709 break; 15710 } 15711 15712 llvm_unreachable("unknown error case for discarding qualifiers!"); 15713 // fallthrough 15714 } 15715 case CompatiblePointerDiscardsQualifiers: 15716 // If the qualifiers lost were because we were applying the 15717 // (deprecated) C++ conversion from a string literal to a char* 15718 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15719 // Ideally, this check would be performed in 15720 // checkPointerTypesForAssignment. However, that would require a 15721 // bit of refactoring (so that the second argument is an 15722 // expression, rather than a type), which should be done as part 15723 // of a larger effort to fix checkPointerTypesForAssignment for 15724 // C++ semantics. 15725 if (getLangOpts().CPlusPlus && 15726 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15727 return false; 15728 if (getLangOpts().CPlusPlus) { 15729 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15730 isInvalid = true; 15731 } else { 15732 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15733 } 15734 15735 break; 15736 case IncompatibleNestedPointerQualifiers: 15737 if (getLangOpts().CPlusPlus) { 15738 isInvalid = true; 15739 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15740 } else { 15741 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15742 } 15743 break; 15744 case IncompatibleNestedPointerAddressSpaceMismatch: 15745 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15746 isInvalid = true; 15747 break; 15748 case IntToBlockPointer: 15749 DiagKind = diag::err_int_to_block_pointer; 15750 isInvalid = true; 15751 break; 15752 case IncompatibleBlockPointer: 15753 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15754 isInvalid = true; 15755 break; 15756 case IncompatibleObjCQualifiedId: { 15757 if (SrcType->isObjCQualifiedIdType()) { 15758 const ObjCObjectPointerType *srcOPT = 15759 SrcType->castAs<ObjCObjectPointerType>(); 15760 for (auto *srcProto : srcOPT->quals()) { 15761 PDecl = srcProto; 15762 break; 15763 } 15764 if (const ObjCInterfaceType *IFaceT = 15765 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15766 IFace = IFaceT->getDecl(); 15767 } 15768 else if (DstType->isObjCQualifiedIdType()) { 15769 const ObjCObjectPointerType *dstOPT = 15770 DstType->castAs<ObjCObjectPointerType>(); 15771 for (auto *dstProto : dstOPT->quals()) { 15772 PDecl = dstProto; 15773 break; 15774 } 15775 if (const ObjCInterfaceType *IFaceT = 15776 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15777 IFace = IFaceT->getDecl(); 15778 } 15779 if (getLangOpts().CPlusPlus) { 15780 DiagKind = diag::err_incompatible_qualified_id; 15781 isInvalid = true; 15782 } else { 15783 DiagKind = diag::warn_incompatible_qualified_id; 15784 } 15785 break; 15786 } 15787 case IncompatibleVectors: 15788 if (getLangOpts().CPlusPlus) { 15789 DiagKind = diag::err_incompatible_vectors; 15790 isInvalid = true; 15791 } else { 15792 DiagKind = diag::warn_incompatible_vectors; 15793 } 15794 break; 15795 case IncompatibleObjCWeakRef: 15796 DiagKind = diag::err_arc_weak_unavailable_assign; 15797 isInvalid = true; 15798 break; 15799 case Incompatible: 15800 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15801 if (Complained) 15802 *Complained = true; 15803 return true; 15804 } 15805 15806 DiagKind = diag::err_typecheck_convert_incompatible; 15807 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15808 MayHaveConvFixit = true; 15809 isInvalid = true; 15810 MayHaveFunctionDiff = true; 15811 break; 15812 } 15813 15814 QualType FirstType, SecondType; 15815 switch (Action) { 15816 case AA_Assigning: 15817 case AA_Initializing: 15818 // The destination type comes first. 15819 FirstType = DstType; 15820 SecondType = SrcType; 15821 break; 15822 15823 case AA_Returning: 15824 case AA_Passing: 15825 case AA_Passing_CFAudited: 15826 case AA_Converting: 15827 case AA_Sending: 15828 case AA_Casting: 15829 // The source type comes first. 15830 FirstType = SrcType; 15831 SecondType = DstType; 15832 break; 15833 } 15834 15835 PartialDiagnostic FDiag = PDiag(DiagKind); 15836 if (Action == AA_Passing_CFAudited) 15837 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15838 else 15839 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15840 15841 // If we can fix the conversion, suggest the FixIts. 15842 if (!ConvHints.isNull()) { 15843 for (FixItHint &H : ConvHints.Hints) 15844 FDiag << H; 15845 } 15846 15847 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15848 15849 if (MayHaveFunctionDiff) 15850 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15851 15852 Diag(Loc, FDiag); 15853 if ((DiagKind == diag::warn_incompatible_qualified_id || 15854 DiagKind == diag::err_incompatible_qualified_id) && 15855 PDecl && IFace && !IFace->hasDefinition()) 15856 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15857 << IFace << PDecl; 15858 15859 if (SecondType == Context.OverloadTy) 15860 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15861 FirstType, /*TakingAddress=*/true); 15862 15863 if (CheckInferredResultType) 15864 EmitRelatedResultTypeNote(SrcExpr); 15865 15866 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15867 EmitRelatedResultTypeNoteForReturn(DstType); 15868 15869 if (Complained) 15870 *Complained = true; 15871 return isInvalid; 15872 } 15873 15874 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15875 llvm::APSInt *Result, 15876 AllowFoldKind CanFold) { 15877 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15878 public: 15879 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 15880 QualType T) override { 15881 return S.Diag(Loc, diag::err_ice_not_integral) 15882 << T << S.LangOpts.CPlusPlus; 15883 } 15884 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 15885 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 15886 } 15887 } Diagnoser; 15888 15889 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 15890 } 15891 15892 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15893 llvm::APSInt *Result, 15894 unsigned DiagID, 15895 AllowFoldKind CanFold) { 15896 class IDDiagnoser : public VerifyICEDiagnoser { 15897 unsigned DiagID; 15898 15899 public: 15900 IDDiagnoser(unsigned DiagID) 15901 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15902 15903 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 15904 return S.Diag(Loc, DiagID); 15905 } 15906 } Diagnoser(DiagID); 15907 15908 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 15909 } 15910 15911 Sema::SemaDiagnosticBuilder 15912 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 15913 QualType T) { 15914 return diagnoseNotICE(S, Loc); 15915 } 15916 15917 Sema::SemaDiagnosticBuilder 15918 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 15919 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 15920 } 15921 15922 ExprResult 15923 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15924 VerifyICEDiagnoser &Diagnoser, 15925 AllowFoldKind CanFold) { 15926 SourceLocation DiagLoc = E->getBeginLoc(); 15927 15928 if (getLangOpts().CPlusPlus11) { 15929 // C++11 [expr.const]p5: 15930 // If an expression of literal class type is used in a context where an 15931 // integral constant expression is required, then that class type shall 15932 // have a single non-explicit conversion function to an integral or 15933 // unscoped enumeration type 15934 ExprResult Converted; 15935 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15936 VerifyICEDiagnoser &BaseDiagnoser; 15937 public: 15938 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 15939 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 15940 BaseDiagnoser.Suppress, true), 15941 BaseDiagnoser(BaseDiagnoser) {} 15942 15943 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15944 QualType T) override { 15945 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 15946 } 15947 15948 SemaDiagnosticBuilder diagnoseIncomplete( 15949 Sema &S, SourceLocation Loc, QualType T) override { 15950 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15951 } 15952 15953 SemaDiagnosticBuilder diagnoseExplicitConv( 15954 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15955 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15956 } 15957 15958 SemaDiagnosticBuilder noteExplicitConv( 15959 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15960 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15961 << ConvTy->isEnumeralType() << ConvTy; 15962 } 15963 15964 SemaDiagnosticBuilder diagnoseAmbiguous( 15965 Sema &S, SourceLocation Loc, QualType T) override { 15966 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15967 } 15968 15969 SemaDiagnosticBuilder noteAmbiguous( 15970 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15971 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15972 << ConvTy->isEnumeralType() << ConvTy; 15973 } 15974 15975 SemaDiagnosticBuilder diagnoseConversion( 15976 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15977 llvm_unreachable("conversion functions are permitted"); 15978 } 15979 } ConvertDiagnoser(Diagnoser); 15980 15981 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15982 ConvertDiagnoser); 15983 if (Converted.isInvalid()) 15984 return Converted; 15985 E = Converted.get(); 15986 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15987 return ExprError(); 15988 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15989 // An ICE must be of integral or unscoped enumeration type. 15990 if (!Diagnoser.Suppress) 15991 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 15992 << E->getSourceRange(); 15993 return ExprError(); 15994 } 15995 15996 ExprResult RValueExpr = DefaultLvalueConversion(E); 15997 if (RValueExpr.isInvalid()) 15998 return ExprError(); 15999 16000 E = RValueExpr.get(); 16001 16002 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16003 // in the non-ICE case. 16004 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16005 if (Result) 16006 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16007 if (!isa<ConstantExpr>(E)) 16008 E = ConstantExpr::Create(Context, E); 16009 return E; 16010 } 16011 16012 Expr::EvalResult EvalResult; 16013 SmallVector<PartialDiagnosticAt, 8> Notes; 16014 EvalResult.Diag = &Notes; 16015 16016 // Try to evaluate the expression, and produce diagnostics explaining why it's 16017 // not a constant expression as a side-effect. 16018 bool Folded = 16019 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16020 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16021 16022 if (!isa<ConstantExpr>(E)) 16023 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16024 16025 // In C++11, we can rely on diagnostics being produced for any expression 16026 // which is not a constant expression. If no diagnostics were produced, then 16027 // this is a constant expression. 16028 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16029 if (Result) 16030 *Result = EvalResult.Val.getInt(); 16031 return E; 16032 } 16033 16034 // If our only note is the usual "invalid subexpression" note, just point 16035 // the caret at its location rather than producing an essentially 16036 // redundant note. 16037 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16038 diag::note_invalid_subexpr_in_const_expr) { 16039 DiagLoc = Notes[0].first; 16040 Notes.clear(); 16041 } 16042 16043 if (!Folded || !CanFold) { 16044 if (!Diagnoser.Suppress) { 16045 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16046 for (const PartialDiagnosticAt &Note : Notes) 16047 Diag(Note.first, Note.second); 16048 } 16049 16050 return ExprError(); 16051 } 16052 16053 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16054 for (const PartialDiagnosticAt &Note : Notes) 16055 Diag(Note.first, Note.second); 16056 16057 if (Result) 16058 *Result = EvalResult.Val.getInt(); 16059 return E; 16060 } 16061 16062 namespace { 16063 // Handle the case where we conclude a expression which we speculatively 16064 // considered to be unevaluated is actually evaluated. 16065 class TransformToPE : public TreeTransform<TransformToPE> { 16066 typedef TreeTransform<TransformToPE> BaseTransform; 16067 16068 public: 16069 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16070 16071 // Make sure we redo semantic analysis 16072 bool AlwaysRebuild() { return true; } 16073 bool ReplacingOriginal() { return true; } 16074 16075 // We need to special-case DeclRefExprs referring to FieldDecls which 16076 // are not part of a member pointer formation; normal TreeTransforming 16077 // doesn't catch this case because of the way we represent them in the AST. 16078 // FIXME: This is a bit ugly; is it really the best way to handle this 16079 // case? 16080 // 16081 // Error on DeclRefExprs referring to FieldDecls. 16082 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16083 if (isa<FieldDecl>(E->getDecl()) && 16084 !SemaRef.isUnevaluatedContext()) 16085 return SemaRef.Diag(E->getLocation(), 16086 diag::err_invalid_non_static_member_use) 16087 << E->getDecl() << E->getSourceRange(); 16088 16089 return BaseTransform::TransformDeclRefExpr(E); 16090 } 16091 16092 // Exception: filter out member pointer formation 16093 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16094 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16095 return E; 16096 16097 return BaseTransform::TransformUnaryOperator(E); 16098 } 16099 16100 // The body of a lambda-expression is in a separate expression evaluation 16101 // context so never needs to be transformed. 16102 // FIXME: Ideally we wouldn't transform the closure type either, and would 16103 // just recreate the capture expressions and lambda expression. 16104 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16105 return SkipLambdaBody(E, Body); 16106 } 16107 }; 16108 } 16109 16110 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16111 assert(isUnevaluatedContext() && 16112 "Should only transform unevaluated expressions"); 16113 ExprEvalContexts.back().Context = 16114 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16115 if (isUnevaluatedContext()) 16116 return E; 16117 return TransformToPE(*this).TransformExpr(E); 16118 } 16119 16120 void 16121 Sema::PushExpressionEvaluationContext( 16122 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16123 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16124 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16125 LambdaContextDecl, ExprContext); 16126 Cleanup.reset(); 16127 if (!MaybeODRUseExprs.empty()) 16128 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16129 } 16130 16131 void 16132 Sema::PushExpressionEvaluationContext( 16133 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16134 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16135 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16136 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16137 } 16138 16139 namespace { 16140 16141 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16142 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16143 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16144 if (E->getOpcode() == UO_Deref) 16145 return CheckPossibleDeref(S, E->getSubExpr()); 16146 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16147 return CheckPossibleDeref(S, E->getBase()); 16148 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16149 return CheckPossibleDeref(S, E->getBase()); 16150 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16151 QualType Inner; 16152 QualType Ty = E->getType(); 16153 if (const auto *Ptr = Ty->getAs<PointerType>()) 16154 Inner = Ptr->getPointeeType(); 16155 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16156 Inner = Arr->getElementType(); 16157 else 16158 return nullptr; 16159 16160 if (Inner->hasAttr(attr::NoDeref)) 16161 return E; 16162 } 16163 return nullptr; 16164 } 16165 16166 } // namespace 16167 16168 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16169 for (const Expr *E : Rec.PossibleDerefs) { 16170 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16171 if (DeclRef) { 16172 const ValueDecl *Decl = DeclRef->getDecl(); 16173 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16174 << Decl->getName() << E->getSourceRange(); 16175 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16176 } else { 16177 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16178 << E->getSourceRange(); 16179 } 16180 } 16181 Rec.PossibleDerefs.clear(); 16182 } 16183 16184 /// Check whether E, which is either a discarded-value expression or an 16185 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16186 /// and if so, remove it from the list of volatile-qualified assignments that 16187 /// we are going to warn are deprecated. 16188 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16189 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16190 return; 16191 16192 // Note: ignoring parens here is not justified by the standard rules, but 16193 // ignoring parentheses seems like a more reasonable approach, and this only 16194 // drives a deprecation warning so doesn't affect conformance. 16195 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16196 if (BO->getOpcode() == BO_Assign) { 16197 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16198 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16199 LHSs.end()); 16200 } 16201 } 16202 } 16203 16204 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16205 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16206 RebuildingImmediateInvocation) 16207 return E; 16208 16209 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16210 /// It's OK if this fails; we'll also remove this in 16211 /// HandleImmediateInvocations, but catching it here allows us to avoid 16212 /// walking the AST looking for it in simple cases. 16213 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16214 if (auto *DeclRef = 16215 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16216 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16217 16218 E = MaybeCreateExprWithCleanups(E); 16219 16220 ConstantExpr *Res = ConstantExpr::Create( 16221 getASTContext(), E.get(), 16222 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16223 getASTContext()), 16224 /*IsImmediateInvocation*/ true); 16225 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16226 return Res; 16227 } 16228 16229 static void EvaluateAndDiagnoseImmediateInvocation( 16230 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16231 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16232 Expr::EvalResult Eval; 16233 Eval.Diag = &Notes; 16234 ConstantExpr *CE = Candidate.getPointer(); 16235 bool Result = CE->EvaluateAsConstantExpr( 16236 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16237 if (!Result || !Notes.empty()) { 16238 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16239 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16240 InnerExpr = FunctionalCast->getSubExpr(); 16241 FunctionDecl *FD = nullptr; 16242 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16243 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16244 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16245 FD = Call->getConstructor(); 16246 else 16247 llvm_unreachable("unhandled decl kind"); 16248 assert(FD->isConsteval()); 16249 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16250 for (auto &Note : Notes) 16251 SemaRef.Diag(Note.first, Note.second); 16252 return; 16253 } 16254 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16255 } 16256 16257 static void RemoveNestedImmediateInvocation( 16258 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16259 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16260 struct ComplexRemove : TreeTransform<ComplexRemove> { 16261 using Base = TreeTransform<ComplexRemove>; 16262 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16263 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16264 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16265 CurrentII; 16266 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16267 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16268 SmallVector<Sema::ImmediateInvocationCandidate, 16269 4>::reverse_iterator Current) 16270 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16271 void RemoveImmediateInvocation(ConstantExpr* E) { 16272 auto It = std::find_if(CurrentII, IISet.rend(), 16273 [E](Sema::ImmediateInvocationCandidate Elem) { 16274 return Elem.getPointer() == E; 16275 }); 16276 assert(It != IISet.rend() && 16277 "ConstantExpr marked IsImmediateInvocation should " 16278 "be present"); 16279 It->setInt(1); // Mark as deleted 16280 } 16281 ExprResult TransformConstantExpr(ConstantExpr *E) { 16282 if (!E->isImmediateInvocation()) 16283 return Base::TransformConstantExpr(E); 16284 RemoveImmediateInvocation(E); 16285 return Base::TransformExpr(E->getSubExpr()); 16286 } 16287 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16288 /// we need to remove its DeclRefExpr from the DRSet. 16289 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16290 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16291 return Base::TransformCXXOperatorCallExpr(E); 16292 } 16293 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16294 /// here. 16295 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16296 if (!Init) 16297 return Init; 16298 /// ConstantExpr are the first layer of implicit node to be removed so if 16299 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16300 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16301 if (CE->isImmediateInvocation()) 16302 RemoveImmediateInvocation(CE); 16303 return Base::TransformInitializer(Init, NotCopyInit); 16304 } 16305 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16306 DRSet.erase(E); 16307 return E; 16308 } 16309 bool AlwaysRebuild() { return false; } 16310 bool ReplacingOriginal() { return true; } 16311 bool AllowSkippingCXXConstructExpr() { 16312 bool Res = AllowSkippingFirstCXXConstructExpr; 16313 AllowSkippingFirstCXXConstructExpr = true; 16314 return Res; 16315 } 16316 bool AllowSkippingFirstCXXConstructExpr = true; 16317 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16318 Rec.ImmediateInvocationCandidates, It); 16319 16320 /// CXXConstructExpr with a single argument are getting skipped by 16321 /// TreeTransform in some situtation because they could be implicit. This 16322 /// can only occur for the top-level CXXConstructExpr because it is used 16323 /// nowhere in the expression being transformed therefore will not be rebuilt. 16324 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16325 /// skipping the first CXXConstructExpr. 16326 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16327 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16328 16329 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16330 assert(Res.isUsable()); 16331 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16332 It->getPointer()->setSubExpr(Res.get()); 16333 } 16334 16335 static void 16336 HandleImmediateInvocations(Sema &SemaRef, 16337 Sema::ExpressionEvaluationContextRecord &Rec) { 16338 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16339 Rec.ReferenceToConsteval.size() == 0) || 16340 SemaRef.RebuildingImmediateInvocation) 16341 return; 16342 16343 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16344 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16345 /// need to remove ReferenceToConsteval in the immediate invocation. 16346 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16347 16348 /// Prevent sema calls during the tree transform from adding pointers that 16349 /// are already in the sets. 16350 llvm::SaveAndRestore<bool> DisableIITracking( 16351 SemaRef.RebuildingImmediateInvocation, true); 16352 16353 /// Prevent diagnostic during tree transfrom as they are duplicates 16354 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16355 16356 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16357 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16358 if (!It->getInt()) 16359 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16360 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16361 Rec.ReferenceToConsteval.size()) { 16362 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16363 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16364 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16365 bool VisitDeclRefExpr(DeclRefExpr *E) { 16366 DRSet.erase(E); 16367 return DRSet.size(); 16368 } 16369 } Visitor(Rec.ReferenceToConsteval); 16370 Visitor.TraverseStmt( 16371 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16372 } 16373 for (auto CE : Rec.ImmediateInvocationCandidates) 16374 if (!CE.getInt()) 16375 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16376 for (auto DR : Rec.ReferenceToConsteval) { 16377 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16378 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16379 << FD; 16380 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16381 } 16382 } 16383 16384 void Sema::PopExpressionEvaluationContext() { 16385 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16386 unsigned NumTypos = Rec.NumTypos; 16387 16388 if (!Rec.Lambdas.empty()) { 16389 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16390 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16391 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16392 unsigned D; 16393 if (Rec.isUnevaluated()) { 16394 // C++11 [expr.prim.lambda]p2: 16395 // A lambda-expression shall not appear in an unevaluated operand 16396 // (Clause 5). 16397 D = diag::err_lambda_unevaluated_operand; 16398 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16399 // C++1y [expr.const]p2: 16400 // A conditional-expression e is a core constant expression unless the 16401 // evaluation of e, following the rules of the abstract machine, would 16402 // evaluate [...] a lambda-expression. 16403 D = diag::err_lambda_in_constant_expression; 16404 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16405 // C++17 [expr.prim.lamda]p2: 16406 // A lambda-expression shall not appear [...] in a template-argument. 16407 D = diag::err_lambda_in_invalid_context; 16408 } else 16409 llvm_unreachable("Couldn't infer lambda error message."); 16410 16411 for (const auto *L : Rec.Lambdas) 16412 Diag(L->getBeginLoc(), D); 16413 } 16414 } 16415 16416 WarnOnPendingNoDerefs(Rec); 16417 HandleImmediateInvocations(*this, Rec); 16418 16419 // Warn on any volatile-qualified simple-assignments that are not discarded- 16420 // value expressions nor unevaluated operands (those cases get removed from 16421 // this list by CheckUnusedVolatileAssignment). 16422 for (auto *BO : Rec.VolatileAssignmentLHSs) 16423 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16424 << BO->getType(); 16425 16426 // When are coming out of an unevaluated context, clear out any 16427 // temporaries that we may have created as part of the evaluation of 16428 // the expression in that context: they aren't relevant because they 16429 // will never be constructed. 16430 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16431 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16432 ExprCleanupObjects.end()); 16433 Cleanup = Rec.ParentCleanup; 16434 CleanupVarDeclMarking(); 16435 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16436 // Otherwise, merge the contexts together. 16437 } else { 16438 Cleanup.mergeFrom(Rec.ParentCleanup); 16439 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16440 Rec.SavedMaybeODRUseExprs.end()); 16441 } 16442 16443 // Pop the current expression evaluation context off the stack. 16444 ExprEvalContexts.pop_back(); 16445 16446 // The global expression evaluation context record is never popped. 16447 ExprEvalContexts.back().NumTypos += NumTypos; 16448 } 16449 16450 void Sema::DiscardCleanupsInEvaluationContext() { 16451 ExprCleanupObjects.erase( 16452 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16453 ExprCleanupObjects.end()); 16454 Cleanup.reset(); 16455 MaybeODRUseExprs.clear(); 16456 } 16457 16458 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16459 ExprResult Result = CheckPlaceholderExpr(E); 16460 if (Result.isInvalid()) 16461 return ExprError(); 16462 E = Result.get(); 16463 if (!E->getType()->isVariablyModifiedType()) 16464 return E; 16465 return TransformToPotentiallyEvaluated(E); 16466 } 16467 16468 /// Are we in a context that is potentially constant evaluated per C++20 16469 /// [expr.const]p12? 16470 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16471 /// C++2a [expr.const]p12: 16472 // An expression or conversion is potentially constant evaluated if it is 16473 switch (SemaRef.ExprEvalContexts.back().Context) { 16474 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16475 // -- a manifestly constant-evaluated expression, 16476 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16477 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16478 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16479 // -- a potentially-evaluated expression, 16480 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16481 // -- an immediate subexpression of a braced-init-list, 16482 16483 // -- [FIXME] an expression of the form & cast-expression that occurs 16484 // within a templated entity 16485 // -- a subexpression of one of the above that is not a subexpression of 16486 // a nested unevaluated operand. 16487 return true; 16488 16489 case Sema::ExpressionEvaluationContext::Unevaluated: 16490 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16491 // Expressions in this context are never evaluated. 16492 return false; 16493 } 16494 llvm_unreachable("Invalid context"); 16495 } 16496 16497 /// Return true if this function has a calling convention that requires mangling 16498 /// in the size of the parameter pack. 16499 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16500 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16501 // we don't need parameter type sizes. 16502 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16503 if (!TT.isOSWindows() || !TT.isX86()) 16504 return false; 16505 16506 // If this is C++ and this isn't an extern "C" function, parameters do not 16507 // need to be complete. In this case, C++ mangling will apply, which doesn't 16508 // use the size of the parameters. 16509 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16510 return false; 16511 16512 // Stdcall, fastcall, and vectorcall need this special treatment. 16513 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16514 switch (CC) { 16515 case CC_X86StdCall: 16516 case CC_X86FastCall: 16517 case CC_X86VectorCall: 16518 return true; 16519 default: 16520 break; 16521 } 16522 return false; 16523 } 16524 16525 /// Require that all of the parameter types of function be complete. Normally, 16526 /// parameter types are only required to be complete when a function is called 16527 /// or defined, but to mangle functions with certain calling conventions, the 16528 /// mangler needs to know the size of the parameter list. In this situation, 16529 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16530 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16531 /// result in a linker error. Clang doesn't implement this behavior, and instead 16532 /// attempts to error at compile time. 16533 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16534 SourceLocation Loc) { 16535 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16536 FunctionDecl *FD; 16537 ParmVarDecl *Param; 16538 16539 public: 16540 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16541 : FD(FD), Param(Param) {} 16542 16543 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16544 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16545 StringRef CCName; 16546 switch (CC) { 16547 case CC_X86StdCall: 16548 CCName = "stdcall"; 16549 break; 16550 case CC_X86FastCall: 16551 CCName = "fastcall"; 16552 break; 16553 case CC_X86VectorCall: 16554 CCName = "vectorcall"; 16555 break; 16556 default: 16557 llvm_unreachable("CC does not need mangling"); 16558 } 16559 16560 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16561 << Param->getDeclName() << FD->getDeclName() << CCName; 16562 } 16563 }; 16564 16565 for (ParmVarDecl *Param : FD->parameters()) { 16566 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16567 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16568 } 16569 } 16570 16571 namespace { 16572 enum class OdrUseContext { 16573 /// Declarations in this context are not odr-used. 16574 None, 16575 /// Declarations in this context are formally odr-used, but this is a 16576 /// dependent context. 16577 Dependent, 16578 /// Declarations in this context are odr-used but not actually used (yet). 16579 FormallyOdrUsed, 16580 /// Declarations in this context are used. 16581 Used 16582 }; 16583 } 16584 16585 /// Are we within a context in which references to resolved functions or to 16586 /// variables result in odr-use? 16587 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16588 OdrUseContext Result; 16589 16590 switch (SemaRef.ExprEvalContexts.back().Context) { 16591 case Sema::ExpressionEvaluationContext::Unevaluated: 16592 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16593 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16594 return OdrUseContext::None; 16595 16596 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16597 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16598 Result = OdrUseContext::Used; 16599 break; 16600 16601 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16602 Result = OdrUseContext::FormallyOdrUsed; 16603 break; 16604 16605 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16606 // A default argument formally results in odr-use, but doesn't actually 16607 // result in a use in any real sense until it itself is used. 16608 Result = OdrUseContext::FormallyOdrUsed; 16609 break; 16610 } 16611 16612 if (SemaRef.CurContext->isDependentContext()) 16613 return OdrUseContext::Dependent; 16614 16615 return Result; 16616 } 16617 16618 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16619 if (!Func->isConstexpr()) 16620 return false; 16621 16622 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16623 return true; 16624 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16625 return CCD && CCD->getInheritedConstructor(); 16626 } 16627 16628 /// Mark a function referenced, and check whether it is odr-used 16629 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16630 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16631 bool MightBeOdrUse) { 16632 assert(Func && "No function?"); 16633 16634 Func->setReferenced(); 16635 16636 // Recursive functions aren't really used until they're used from some other 16637 // context. 16638 bool IsRecursiveCall = CurContext == Func; 16639 16640 // C++11 [basic.def.odr]p3: 16641 // A function whose name appears as a potentially-evaluated expression is 16642 // odr-used if it is the unique lookup result or the selected member of a 16643 // set of overloaded functions [...]. 16644 // 16645 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16646 // can just check that here. 16647 OdrUseContext OdrUse = 16648 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16649 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16650 OdrUse = OdrUseContext::FormallyOdrUsed; 16651 16652 // Trivial default constructors and destructors are never actually used. 16653 // FIXME: What about other special members? 16654 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16655 OdrUse == OdrUseContext::Used) { 16656 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16657 if (Constructor->isDefaultConstructor()) 16658 OdrUse = OdrUseContext::FormallyOdrUsed; 16659 if (isa<CXXDestructorDecl>(Func)) 16660 OdrUse = OdrUseContext::FormallyOdrUsed; 16661 } 16662 16663 // C++20 [expr.const]p12: 16664 // A function [...] is needed for constant evaluation if it is [...] a 16665 // constexpr function that is named by an expression that is potentially 16666 // constant evaluated 16667 bool NeededForConstantEvaluation = 16668 isPotentiallyConstantEvaluatedContext(*this) && 16669 isImplicitlyDefinableConstexprFunction(Func); 16670 16671 // Determine whether we require a function definition to exist, per 16672 // C++11 [temp.inst]p3: 16673 // Unless a function template specialization has been explicitly 16674 // instantiated or explicitly specialized, the function template 16675 // specialization is implicitly instantiated when the specialization is 16676 // referenced in a context that requires a function definition to exist. 16677 // C++20 [temp.inst]p7: 16678 // The existence of a definition of a [...] function is considered to 16679 // affect the semantics of the program if the [...] function is needed for 16680 // constant evaluation by an expression 16681 // C++20 [basic.def.odr]p10: 16682 // Every program shall contain exactly one definition of every non-inline 16683 // function or variable that is odr-used in that program outside of a 16684 // discarded statement 16685 // C++20 [special]p1: 16686 // The implementation will implicitly define [defaulted special members] 16687 // if they are odr-used or needed for constant evaluation. 16688 // 16689 // Note that we skip the implicit instantiation of templates that are only 16690 // used in unused default arguments or by recursive calls to themselves. 16691 // This is formally non-conforming, but seems reasonable in practice. 16692 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16693 NeededForConstantEvaluation); 16694 16695 // C++14 [temp.expl.spec]p6: 16696 // If a template [...] is explicitly specialized then that specialization 16697 // shall be declared before the first use of that specialization that would 16698 // cause an implicit instantiation to take place, in every translation unit 16699 // in which such a use occurs 16700 if (NeedDefinition && 16701 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16702 Func->getMemberSpecializationInfo())) 16703 checkSpecializationVisibility(Loc, Func); 16704 16705 if (getLangOpts().CUDA) 16706 CheckCUDACall(Loc, Func); 16707 16708 if (getLangOpts().SYCLIsDevice) 16709 checkSYCLDeviceFunction(Loc, Func); 16710 16711 // If we need a definition, try to create one. 16712 if (NeedDefinition && !Func->getBody()) { 16713 runWithSufficientStackSpace(Loc, [&] { 16714 if (CXXConstructorDecl *Constructor = 16715 dyn_cast<CXXConstructorDecl>(Func)) { 16716 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16717 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16718 if (Constructor->isDefaultConstructor()) { 16719 if (Constructor->isTrivial() && 16720 !Constructor->hasAttr<DLLExportAttr>()) 16721 return; 16722 DefineImplicitDefaultConstructor(Loc, Constructor); 16723 } else if (Constructor->isCopyConstructor()) { 16724 DefineImplicitCopyConstructor(Loc, Constructor); 16725 } else if (Constructor->isMoveConstructor()) { 16726 DefineImplicitMoveConstructor(Loc, Constructor); 16727 } 16728 } else if (Constructor->getInheritedConstructor()) { 16729 DefineInheritingConstructor(Loc, Constructor); 16730 } 16731 } else if (CXXDestructorDecl *Destructor = 16732 dyn_cast<CXXDestructorDecl>(Func)) { 16733 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16734 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16735 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16736 return; 16737 DefineImplicitDestructor(Loc, Destructor); 16738 } 16739 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16740 MarkVTableUsed(Loc, Destructor->getParent()); 16741 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16742 if (MethodDecl->isOverloadedOperator() && 16743 MethodDecl->getOverloadedOperator() == OO_Equal) { 16744 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16745 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16746 if (MethodDecl->isCopyAssignmentOperator()) 16747 DefineImplicitCopyAssignment(Loc, MethodDecl); 16748 else if (MethodDecl->isMoveAssignmentOperator()) 16749 DefineImplicitMoveAssignment(Loc, MethodDecl); 16750 } 16751 } else if (isa<CXXConversionDecl>(MethodDecl) && 16752 MethodDecl->getParent()->isLambda()) { 16753 CXXConversionDecl *Conversion = 16754 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16755 if (Conversion->isLambdaToBlockPointerConversion()) 16756 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16757 else 16758 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16759 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16760 MarkVTableUsed(Loc, MethodDecl->getParent()); 16761 } 16762 16763 if (Func->isDefaulted() && !Func->isDeleted()) { 16764 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16765 if (DCK != DefaultedComparisonKind::None) 16766 DefineDefaultedComparison(Loc, Func, DCK); 16767 } 16768 16769 // Implicit instantiation of function templates and member functions of 16770 // class templates. 16771 if (Func->isImplicitlyInstantiable()) { 16772 TemplateSpecializationKind TSK = 16773 Func->getTemplateSpecializationKindForInstantiation(); 16774 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16775 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16776 if (FirstInstantiation) { 16777 PointOfInstantiation = Loc; 16778 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16779 } else if (TSK != TSK_ImplicitInstantiation) { 16780 // Use the point of use as the point of instantiation, instead of the 16781 // point of explicit instantiation (which we track as the actual point 16782 // of instantiation). This gives better backtraces in diagnostics. 16783 PointOfInstantiation = Loc; 16784 } 16785 16786 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16787 Func->isConstexpr()) { 16788 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16789 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16790 CodeSynthesisContexts.size()) 16791 PendingLocalImplicitInstantiations.push_back( 16792 std::make_pair(Func, PointOfInstantiation)); 16793 else if (Func->isConstexpr()) 16794 // Do not defer instantiations of constexpr functions, to avoid the 16795 // expression evaluator needing to call back into Sema if it sees a 16796 // call to such a function. 16797 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16798 else { 16799 Func->setInstantiationIsPending(true); 16800 PendingInstantiations.push_back( 16801 std::make_pair(Func, PointOfInstantiation)); 16802 // Notify the consumer that a function was implicitly instantiated. 16803 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16804 } 16805 } 16806 } else { 16807 // Walk redefinitions, as some of them may be instantiable. 16808 for (auto i : Func->redecls()) { 16809 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16810 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16811 } 16812 } 16813 }); 16814 } 16815 16816 // C++14 [except.spec]p17: 16817 // An exception-specification is considered to be needed when: 16818 // - the function is odr-used or, if it appears in an unevaluated operand, 16819 // would be odr-used if the expression were potentially-evaluated; 16820 // 16821 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16822 // function is a pure virtual function we're calling, and in that case the 16823 // function was selected by overload resolution and we need to resolve its 16824 // exception specification for a different reason. 16825 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16826 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16827 ResolveExceptionSpec(Loc, FPT); 16828 16829 // If this is the first "real" use, act on that. 16830 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16831 // Keep track of used but undefined functions. 16832 if (!Func->isDefined()) { 16833 if (mightHaveNonExternalLinkage(Func)) 16834 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16835 else if (Func->getMostRecentDecl()->isInlined() && 16836 !LangOpts.GNUInline && 16837 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16838 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16839 else if (isExternalWithNoLinkageType(Func)) 16840 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16841 } 16842 16843 // Some x86 Windows calling conventions mangle the size of the parameter 16844 // pack into the name. Computing the size of the parameters requires the 16845 // parameter types to be complete. Check that now. 16846 if (funcHasParameterSizeMangling(*this, Func)) 16847 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16848 16849 // In the MS C++ ABI, the compiler emits destructor variants where they are 16850 // used. If the destructor is used here but defined elsewhere, mark the 16851 // virtual base destructors referenced. If those virtual base destructors 16852 // are inline, this will ensure they are defined when emitting the complete 16853 // destructor variant. This checking may be redundant if the destructor is 16854 // provided later in this TU. 16855 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16856 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16857 CXXRecordDecl *Parent = Dtor->getParent(); 16858 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16859 CheckCompleteDestructorVariant(Loc, Dtor); 16860 } 16861 } 16862 16863 Func->markUsed(Context); 16864 } 16865 } 16866 16867 /// Directly mark a variable odr-used. Given a choice, prefer to use 16868 /// MarkVariableReferenced since it does additional checks and then 16869 /// calls MarkVarDeclODRUsed. 16870 /// If the variable must be captured: 16871 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16872 /// - else capture it in the DeclContext that maps to the 16873 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16874 static void 16875 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16876 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16877 // Keep track of used but undefined variables. 16878 // FIXME: We shouldn't suppress this warning for static data members. 16879 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16880 (!Var->isExternallyVisible() || Var->isInline() || 16881 SemaRef.isExternalWithNoLinkageType(Var)) && 16882 !(Var->isStaticDataMember() && Var->hasInit())) { 16883 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16884 if (old.isInvalid()) 16885 old = Loc; 16886 } 16887 QualType CaptureType, DeclRefType; 16888 if (SemaRef.LangOpts.OpenMP) 16889 SemaRef.tryCaptureOpenMPLambdas(Var); 16890 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16891 /*EllipsisLoc*/ SourceLocation(), 16892 /*BuildAndDiagnose*/ true, 16893 CaptureType, DeclRefType, 16894 FunctionScopeIndexToStopAt); 16895 16896 Var->markUsed(SemaRef.Context); 16897 } 16898 16899 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16900 SourceLocation Loc, 16901 unsigned CapturingScopeIndex) { 16902 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16903 } 16904 16905 static void 16906 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16907 ValueDecl *var, DeclContext *DC) { 16908 DeclContext *VarDC = var->getDeclContext(); 16909 16910 // If the parameter still belongs to the translation unit, then 16911 // we're actually just using one parameter in the declaration of 16912 // the next. 16913 if (isa<ParmVarDecl>(var) && 16914 isa<TranslationUnitDecl>(VarDC)) 16915 return; 16916 16917 // For C code, don't diagnose about capture if we're not actually in code 16918 // right now; it's impossible to write a non-constant expression outside of 16919 // function context, so we'll get other (more useful) diagnostics later. 16920 // 16921 // For C++, things get a bit more nasty... it would be nice to suppress this 16922 // diagnostic for certain cases like using a local variable in an array bound 16923 // for a member of a local class, but the correct predicate is not obvious. 16924 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16925 return; 16926 16927 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16928 unsigned ContextKind = 3; // unknown 16929 if (isa<CXXMethodDecl>(VarDC) && 16930 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16931 ContextKind = 2; 16932 } else if (isa<FunctionDecl>(VarDC)) { 16933 ContextKind = 0; 16934 } else if (isa<BlockDecl>(VarDC)) { 16935 ContextKind = 1; 16936 } 16937 16938 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16939 << var << ValueKind << ContextKind << VarDC; 16940 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16941 << var; 16942 16943 // FIXME: Add additional diagnostic info about class etc. which prevents 16944 // capture. 16945 } 16946 16947 16948 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16949 bool &SubCapturesAreNested, 16950 QualType &CaptureType, 16951 QualType &DeclRefType) { 16952 // Check whether we've already captured it. 16953 if (CSI->CaptureMap.count(Var)) { 16954 // If we found a capture, any subcaptures are nested. 16955 SubCapturesAreNested = true; 16956 16957 // Retrieve the capture type for this variable. 16958 CaptureType = CSI->getCapture(Var).getCaptureType(); 16959 16960 // Compute the type of an expression that refers to this variable. 16961 DeclRefType = CaptureType.getNonReferenceType(); 16962 16963 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16964 // are mutable in the sense that user can change their value - they are 16965 // private instances of the captured declarations. 16966 const Capture &Cap = CSI->getCapture(Var); 16967 if (Cap.isCopyCapture() && 16968 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16969 !(isa<CapturedRegionScopeInfo>(CSI) && 16970 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16971 DeclRefType.addConst(); 16972 return true; 16973 } 16974 return false; 16975 } 16976 16977 // Only block literals, captured statements, and lambda expressions can 16978 // capture; other scopes don't work. 16979 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16980 SourceLocation Loc, 16981 const bool Diagnose, Sema &S) { 16982 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16983 return getLambdaAwareParentOfDeclContext(DC); 16984 else if (Var->hasLocalStorage()) { 16985 if (Diagnose) 16986 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16987 } 16988 return nullptr; 16989 } 16990 16991 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16992 // certain types of variables (unnamed, variably modified types etc.) 16993 // so check for eligibility. 16994 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16995 SourceLocation Loc, 16996 const bool Diagnose, Sema &S) { 16997 16998 bool IsBlock = isa<BlockScopeInfo>(CSI); 16999 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17000 17001 // Lambdas are not allowed to capture unnamed variables 17002 // (e.g. anonymous unions). 17003 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17004 // assuming that's the intent. 17005 if (IsLambda && !Var->getDeclName()) { 17006 if (Diagnose) { 17007 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17008 S.Diag(Var->getLocation(), diag::note_declared_at); 17009 } 17010 return false; 17011 } 17012 17013 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17014 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17015 if (Diagnose) { 17016 S.Diag(Loc, diag::err_ref_vm_type); 17017 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17018 } 17019 return false; 17020 } 17021 // Prohibit structs with flexible array members too. 17022 // We cannot capture what is in the tail end of the struct. 17023 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17024 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17025 if (Diagnose) { 17026 if (IsBlock) 17027 S.Diag(Loc, diag::err_ref_flexarray_type); 17028 else 17029 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17030 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17031 } 17032 return false; 17033 } 17034 } 17035 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17036 // Lambdas and captured statements are not allowed to capture __block 17037 // variables; they don't support the expected semantics. 17038 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17039 if (Diagnose) { 17040 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17041 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17042 } 17043 return false; 17044 } 17045 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17046 if (S.getLangOpts().OpenCL && IsBlock && 17047 Var->getType()->isBlockPointerType()) { 17048 if (Diagnose) 17049 S.Diag(Loc, diag::err_opencl_block_ref_block); 17050 return false; 17051 } 17052 17053 return true; 17054 } 17055 17056 // Returns true if the capture by block was successful. 17057 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17058 SourceLocation Loc, 17059 const bool BuildAndDiagnose, 17060 QualType &CaptureType, 17061 QualType &DeclRefType, 17062 const bool Nested, 17063 Sema &S, bool Invalid) { 17064 bool ByRef = false; 17065 17066 // Blocks are not allowed to capture arrays, excepting OpenCL. 17067 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17068 // (decayed to pointers). 17069 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17070 if (BuildAndDiagnose) { 17071 S.Diag(Loc, diag::err_ref_array_type); 17072 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17073 Invalid = true; 17074 } else { 17075 return false; 17076 } 17077 } 17078 17079 // Forbid the block-capture of autoreleasing variables. 17080 if (!Invalid && 17081 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17082 if (BuildAndDiagnose) { 17083 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17084 << /*block*/ 0; 17085 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17086 Invalid = true; 17087 } else { 17088 return false; 17089 } 17090 } 17091 17092 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17093 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17094 QualType PointeeTy = PT->getPointeeType(); 17095 17096 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17097 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17098 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17099 if (BuildAndDiagnose) { 17100 SourceLocation VarLoc = Var->getLocation(); 17101 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17102 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17103 } 17104 } 17105 } 17106 17107 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17108 if (HasBlocksAttr || CaptureType->isReferenceType() || 17109 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17110 // Block capture by reference does not change the capture or 17111 // declaration reference types. 17112 ByRef = true; 17113 } else { 17114 // Block capture by copy introduces 'const'. 17115 CaptureType = CaptureType.getNonReferenceType().withConst(); 17116 DeclRefType = CaptureType; 17117 } 17118 17119 // Actually capture the variable. 17120 if (BuildAndDiagnose) 17121 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17122 CaptureType, Invalid); 17123 17124 return !Invalid; 17125 } 17126 17127 17128 /// Capture the given variable in the captured region. 17129 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17130 VarDecl *Var, 17131 SourceLocation Loc, 17132 const bool BuildAndDiagnose, 17133 QualType &CaptureType, 17134 QualType &DeclRefType, 17135 const bool RefersToCapturedVariable, 17136 Sema &S, bool Invalid) { 17137 // By default, capture variables by reference. 17138 bool ByRef = true; 17139 // Using an LValue reference type is consistent with Lambdas (see below). 17140 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17141 if (S.isOpenMPCapturedDecl(Var)) { 17142 bool HasConst = DeclRefType.isConstQualified(); 17143 DeclRefType = DeclRefType.getUnqualifiedType(); 17144 // Don't lose diagnostics about assignments to const. 17145 if (HasConst) 17146 DeclRefType.addConst(); 17147 } 17148 // Do not capture firstprivates in tasks. 17149 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17150 OMPC_unknown) 17151 return true; 17152 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17153 RSI->OpenMPCaptureLevel); 17154 } 17155 17156 if (ByRef) 17157 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17158 else 17159 CaptureType = DeclRefType; 17160 17161 // Actually capture the variable. 17162 if (BuildAndDiagnose) 17163 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17164 Loc, SourceLocation(), CaptureType, Invalid); 17165 17166 return !Invalid; 17167 } 17168 17169 /// Capture the given variable in the lambda. 17170 static bool captureInLambda(LambdaScopeInfo *LSI, 17171 VarDecl *Var, 17172 SourceLocation Loc, 17173 const bool BuildAndDiagnose, 17174 QualType &CaptureType, 17175 QualType &DeclRefType, 17176 const bool RefersToCapturedVariable, 17177 const Sema::TryCaptureKind Kind, 17178 SourceLocation EllipsisLoc, 17179 const bool IsTopScope, 17180 Sema &S, bool Invalid) { 17181 // Determine whether we are capturing by reference or by value. 17182 bool ByRef = false; 17183 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17184 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17185 } else { 17186 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17187 } 17188 17189 // Compute the type of the field that will capture this variable. 17190 if (ByRef) { 17191 // C++11 [expr.prim.lambda]p15: 17192 // An entity is captured by reference if it is implicitly or 17193 // explicitly captured but not captured by copy. It is 17194 // unspecified whether additional unnamed non-static data 17195 // members are declared in the closure type for entities 17196 // captured by reference. 17197 // 17198 // FIXME: It is not clear whether we want to build an lvalue reference 17199 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17200 // to do the former, while EDG does the latter. Core issue 1249 will 17201 // clarify, but for now we follow GCC because it's a more permissive and 17202 // easily defensible position. 17203 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17204 } else { 17205 // C++11 [expr.prim.lambda]p14: 17206 // For each entity captured by copy, an unnamed non-static 17207 // data member is declared in the closure type. The 17208 // declaration order of these members is unspecified. The type 17209 // of such a data member is the type of the corresponding 17210 // captured entity if the entity is not a reference to an 17211 // object, or the referenced type otherwise. [Note: If the 17212 // captured entity is a reference to a function, the 17213 // corresponding data member is also a reference to a 17214 // function. - end note ] 17215 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17216 if (!RefType->getPointeeType()->isFunctionType()) 17217 CaptureType = RefType->getPointeeType(); 17218 } 17219 17220 // Forbid the lambda copy-capture of autoreleasing variables. 17221 if (!Invalid && 17222 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17223 if (BuildAndDiagnose) { 17224 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17225 S.Diag(Var->getLocation(), diag::note_previous_decl) 17226 << Var->getDeclName(); 17227 Invalid = true; 17228 } else { 17229 return false; 17230 } 17231 } 17232 17233 // Make sure that by-copy captures are of a complete and non-abstract type. 17234 if (!Invalid && BuildAndDiagnose) { 17235 if (!CaptureType->isDependentType() && 17236 S.RequireCompleteSizedType( 17237 Loc, CaptureType, 17238 diag::err_capture_of_incomplete_or_sizeless_type, 17239 Var->getDeclName())) 17240 Invalid = true; 17241 else if (S.RequireNonAbstractType(Loc, CaptureType, 17242 diag::err_capture_of_abstract_type)) 17243 Invalid = true; 17244 } 17245 } 17246 17247 // Compute the type of a reference to this captured variable. 17248 if (ByRef) 17249 DeclRefType = CaptureType.getNonReferenceType(); 17250 else { 17251 // C++ [expr.prim.lambda]p5: 17252 // The closure type for a lambda-expression has a public inline 17253 // function call operator [...]. This function call operator is 17254 // declared const (9.3.1) if and only if the lambda-expression's 17255 // parameter-declaration-clause is not followed by mutable. 17256 DeclRefType = CaptureType.getNonReferenceType(); 17257 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17258 DeclRefType.addConst(); 17259 } 17260 17261 // Add the capture. 17262 if (BuildAndDiagnose) 17263 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17264 Loc, EllipsisLoc, CaptureType, Invalid); 17265 17266 return !Invalid; 17267 } 17268 17269 bool Sema::tryCaptureVariable( 17270 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17271 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17272 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17273 // An init-capture is notionally from the context surrounding its 17274 // declaration, but its parent DC is the lambda class. 17275 DeclContext *VarDC = Var->getDeclContext(); 17276 if (Var->isInitCapture()) 17277 VarDC = VarDC->getParent(); 17278 17279 DeclContext *DC = CurContext; 17280 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17281 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17282 // We need to sync up the Declaration Context with the 17283 // FunctionScopeIndexToStopAt 17284 if (FunctionScopeIndexToStopAt) { 17285 unsigned FSIndex = FunctionScopes.size() - 1; 17286 while (FSIndex != MaxFunctionScopesIndex) { 17287 DC = getLambdaAwareParentOfDeclContext(DC); 17288 --FSIndex; 17289 } 17290 } 17291 17292 17293 // If the variable is declared in the current context, there is no need to 17294 // capture it. 17295 if (VarDC == DC) return true; 17296 17297 // Capture global variables if it is required to use private copy of this 17298 // variable. 17299 bool IsGlobal = !Var->hasLocalStorage(); 17300 if (IsGlobal && 17301 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17302 MaxFunctionScopesIndex))) 17303 return true; 17304 Var = Var->getCanonicalDecl(); 17305 17306 // Walk up the stack to determine whether we can capture the variable, 17307 // performing the "simple" checks that don't depend on type. We stop when 17308 // we've either hit the declared scope of the variable or find an existing 17309 // capture of that variable. We start from the innermost capturing-entity 17310 // (the DC) and ensure that all intervening capturing-entities 17311 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17312 // declcontext can either capture the variable or have already captured 17313 // the variable. 17314 CaptureType = Var->getType(); 17315 DeclRefType = CaptureType.getNonReferenceType(); 17316 bool Nested = false; 17317 bool Explicit = (Kind != TryCapture_Implicit); 17318 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17319 do { 17320 // Only block literals, captured statements, and lambda expressions can 17321 // capture; other scopes don't work. 17322 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17323 ExprLoc, 17324 BuildAndDiagnose, 17325 *this); 17326 // We need to check for the parent *first* because, if we *have* 17327 // private-captured a global variable, we need to recursively capture it in 17328 // intermediate blocks, lambdas, etc. 17329 if (!ParentDC) { 17330 if (IsGlobal) { 17331 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17332 break; 17333 } 17334 return true; 17335 } 17336 17337 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17338 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17339 17340 17341 // Check whether we've already captured it. 17342 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17343 DeclRefType)) { 17344 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17345 break; 17346 } 17347 // If we are instantiating a generic lambda call operator body, 17348 // we do not want to capture new variables. What was captured 17349 // during either a lambdas transformation or initial parsing 17350 // should be used. 17351 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17352 if (BuildAndDiagnose) { 17353 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17354 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17355 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17356 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17357 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17358 } else 17359 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17360 } 17361 return true; 17362 } 17363 17364 // Try to capture variable-length arrays types. 17365 if (Var->getType()->isVariablyModifiedType()) { 17366 // We're going to walk down into the type and look for VLA 17367 // expressions. 17368 QualType QTy = Var->getType(); 17369 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17370 QTy = PVD->getOriginalType(); 17371 captureVariablyModifiedType(Context, QTy, CSI); 17372 } 17373 17374 if (getLangOpts().OpenMP) { 17375 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17376 // OpenMP private variables should not be captured in outer scope, so 17377 // just break here. Similarly, global variables that are captured in a 17378 // target region should not be captured outside the scope of the region. 17379 if (RSI->CapRegionKind == CR_OpenMP) { 17380 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17381 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17382 // If the variable is private (i.e. not captured) and has variably 17383 // modified type, we still need to capture the type for correct 17384 // codegen in all regions, associated with the construct. Currently, 17385 // it is captured in the innermost captured region only. 17386 if (IsOpenMPPrivateDecl != OMPC_unknown && 17387 Var->getType()->isVariablyModifiedType()) { 17388 QualType QTy = Var->getType(); 17389 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17390 QTy = PVD->getOriginalType(); 17391 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17392 I < E; ++I) { 17393 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17394 FunctionScopes[FunctionScopesIndex - I]); 17395 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17396 "Wrong number of captured regions associated with the " 17397 "OpenMP construct."); 17398 captureVariablyModifiedType(Context, QTy, OuterRSI); 17399 } 17400 } 17401 bool IsTargetCap = 17402 IsOpenMPPrivateDecl != OMPC_private && 17403 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17404 RSI->OpenMPCaptureLevel); 17405 // Do not capture global if it is not privatized in outer regions. 17406 bool IsGlobalCap = 17407 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17408 RSI->OpenMPCaptureLevel); 17409 17410 // When we detect target captures we are looking from inside the 17411 // target region, therefore we need to propagate the capture from the 17412 // enclosing region. Therefore, the capture is not initially nested. 17413 if (IsTargetCap) 17414 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17415 17416 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17417 (IsGlobal && !IsGlobalCap)) { 17418 Nested = !IsTargetCap; 17419 DeclRefType = DeclRefType.getUnqualifiedType(); 17420 CaptureType = Context.getLValueReferenceType(DeclRefType); 17421 break; 17422 } 17423 } 17424 } 17425 } 17426 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17427 // No capture-default, and this is not an explicit capture 17428 // so cannot capture this variable. 17429 if (BuildAndDiagnose) { 17430 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17431 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17432 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17433 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17434 diag::note_lambda_decl); 17435 // FIXME: If we error out because an outer lambda can not implicitly 17436 // capture a variable that an inner lambda explicitly captures, we 17437 // should have the inner lambda do the explicit capture - because 17438 // it makes for cleaner diagnostics later. This would purely be done 17439 // so that the diagnostic does not misleadingly claim that a variable 17440 // can not be captured by a lambda implicitly even though it is captured 17441 // explicitly. Suggestion: 17442 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17443 // at the function head 17444 // - cache the StartingDeclContext - this must be a lambda 17445 // - captureInLambda in the innermost lambda the variable. 17446 } 17447 return true; 17448 } 17449 17450 FunctionScopesIndex--; 17451 DC = ParentDC; 17452 Explicit = false; 17453 } while (!VarDC->Equals(DC)); 17454 17455 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17456 // computing the type of the capture at each step, checking type-specific 17457 // requirements, and adding captures if requested. 17458 // If the variable had already been captured previously, we start capturing 17459 // at the lambda nested within that one. 17460 bool Invalid = false; 17461 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17462 ++I) { 17463 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17464 17465 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17466 // certain types of variables (unnamed, variably modified types etc.) 17467 // so check for eligibility. 17468 if (!Invalid) 17469 Invalid = 17470 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17471 17472 // After encountering an error, if we're actually supposed to capture, keep 17473 // capturing in nested contexts to suppress any follow-on diagnostics. 17474 if (Invalid && !BuildAndDiagnose) 17475 return true; 17476 17477 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17478 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17479 DeclRefType, Nested, *this, Invalid); 17480 Nested = true; 17481 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17482 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17483 CaptureType, DeclRefType, Nested, 17484 *this, Invalid); 17485 Nested = true; 17486 } else { 17487 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17488 Invalid = 17489 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17490 DeclRefType, Nested, Kind, EllipsisLoc, 17491 /*IsTopScope*/ I == N - 1, *this, Invalid); 17492 Nested = true; 17493 } 17494 17495 if (Invalid && !BuildAndDiagnose) 17496 return true; 17497 } 17498 return Invalid; 17499 } 17500 17501 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17502 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17503 QualType CaptureType; 17504 QualType DeclRefType; 17505 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17506 /*BuildAndDiagnose=*/true, CaptureType, 17507 DeclRefType, nullptr); 17508 } 17509 17510 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17511 QualType CaptureType; 17512 QualType DeclRefType; 17513 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17514 /*BuildAndDiagnose=*/false, CaptureType, 17515 DeclRefType, nullptr); 17516 } 17517 17518 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17519 QualType CaptureType; 17520 QualType DeclRefType; 17521 17522 // Determine whether we can capture this variable. 17523 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17524 /*BuildAndDiagnose=*/false, CaptureType, 17525 DeclRefType, nullptr)) 17526 return QualType(); 17527 17528 return DeclRefType; 17529 } 17530 17531 namespace { 17532 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17533 // The produced TemplateArgumentListInfo* points to data stored within this 17534 // object, so should only be used in contexts where the pointer will not be 17535 // used after the CopiedTemplateArgs object is destroyed. 17536 class CopiedTemplateArgs { 17537 bool HasArgs; 17538 TemplateArgumentListInfo TemplateArgStorage; 17539 public: 17540 template<typename RefExpr> 17541 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17542 if (HasArgs) 17543 E->copyTemplateArgumentsInto(TemplateArgStorage); 17544 } 17545 operator TemplateArgumentListInfo*() 17546 #ifdef __has_cpp_attribute 17547 #if __has_cpp_attribute(clang::lifetimebound) 17548 [[clang::lifetimebound]] 17549 #endif 17550 #endif 17551 { 17552 return HasArgs ? &TemplateArgStorage : nullptr; 17553 } 17554 }; 17555 } 17556 17557 /// Walk the set of potential results of an expression and mark them all as 17558 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17559 /// 17560 /// \return A new expression if we found any potential results, ExprEmpty() if 17561 /// not, and ExprError() if we diagnosed an error. 17562 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17563 NonOdrUseReason NOUR) { 17564 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17565 // an object that satisfies the requirements for appearing in a 17566 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17567 // is immediately applied." This function handles the lvalue-to-rvalue 17568 // conversion part. 17569 // 17570 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17571 // transform it into the relevant kind of non-odr-use node and rebuild the 17572 // tree of nodes leading to it. 17573 // 17574 // This is a mini-TreeTransform that only transforms a restricted subset of 17575 // nodes (and only certain operands of them). 17576 17577 // Rebuild a subexpression. 17578 auto Rebuild = [&](Expr *Sub) { 17579 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17580 }; 17581 17582 // Check whether a potential result satisfies the requirements of NOUR. 17583 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17584 // Any entity other than a VarDecl is always odr-used whenever it's named 17585 // in a potentially-evaluated expression. 17586 auto *VD = dyn_cast<VarDecl>(D); 17587 if (!VD) 17588 return true; 17589 17590 // C++2a [basic.def.odr]p4: 17591 // A variable x whose name appears as a potentially-evalauted expression 17592 // e is odr-used by e unless 17593 // -- x is a reference that is usable in constant expressions, or 17594 // -- x is a variable of non-reference type that is usable in constant 17595 // expressions and has no mutable subobjects, and e is an element of 17596 // the set of potential results of an expression of 17597 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17598 // conversion is applied, or 17599 // -- x is a variable of non-reference type, and e is an element of the 17600 // set of potential results of a discarded-value expression to which 17601 // the lvalue-to-rvalue conversion is not applied 17602 // 17603 // We check the first bullet and the "potentially-evaluated" condition in 17604 // BuildDeclRefExpr. We check the type requirements in the second bullet 17605 // in CheckLValueToRValueConversionOperand below. 17606 switch (NOUR) { 17607 case NOUR_None: 17608 case NOUR_Unevaluated: 17609 llvm_unreachable("unexpected non-odr-use-reason"); 17610 17611 case NOUR_Constant: 17612 // Constant references were handled when they were built. 17613 if (VD->getType()->isReferenceType()) 17614 return true; 17615 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17616 if (RD->hasMutableFields()) 17617 return true; 17618 if (!VD->isUsableInConstantExpressions(S.Context)) 17619 return true; 17620 break; 17621 17622 case NOUR_Discarded: 17623 if (VD->getType()->isReferenceType()) 17624 return true; 17625 break; 17626 } 17627 return false; 17628 }; 17629 17630 // Mark that this expression does not constitute an odr-use. 17631 auto MarkNotOdrUsed = [&] { 17632 S.MaybeODRUseExprs.remove(E); 17633 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17634 LSI->markVariableExprAsNonODRUsed(E); 17635 }; 17636 17637 // C++2a [basic.def.odr]p2: 17638 // The set of potential results of an expression e is defined as follows: 17639 switch (E->getStmtClass()) { 17640 // -- If e is an id-expression, ... 17641 case Expr::DeclRefExprClass: { 17642 auto *DRE = cast<DeclRefExpr>(E); 17643 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17644 break; 17645 17646 // Rebuild as a non-odr-use DeclRefExpr. 17647 MarkNotOdrUsed(); 17648 return DeclRefExpr::Create( 17649 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17650 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17651 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17652 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17653 } 17654 17655 case Expr::FunctionParmPackExprClass: { 17656 auto *FPPE = cast<FunctionParmPackExpr>(E); 17657 // If any of the declarations in the pack is odr-used, then the expression 17658 // as a whole constitutes an odr-use. 17659 for (VarDecl *D : *FPPE) 17660 if (IsPotentialResultOdrUsed(D)) 17661 return ExprEmpty(); 17662 17663 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17664 // nothing cares about whether we marked this as an odr-use, but it might 17665 // be useful for non-compiler tools. 17666 MarkNotOdrUsed(); 17667 break; 17668 } 17669 17670 // -- If e is a subscripting operation with an array operand... 17671 case Expr::ArraySubscriptExprClass: { 17672 auto *ASE = cast<ArraySubscriptExpr>(E); 17673 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17674 if (!OldBase->getType()->isArrayType()) 17675 break; 17676 ExprResult Base = Rebuild(OldBase); 17677 if (!Base.isUsable()) 17678 return Base; 17679 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17680 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17681 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17682 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17683 ASE->getRBracketLoc()); 17684 } 17685 17686 case Expr::MemberExprClass: { 17687 auto *ME = cast<MemberExpr>(E); 17688 // -- If e is a class member access expression [...] naming a non-static 17689 // data member... 17690 if (isa<FieldDecl>(ME->getMemberDecl())) { 17691 ExprResult Base = Rebuild(ME->getBase()); 17692 if (!Base.isUsable()) 17693 return Base; 17694 return MemberExpr::Create( 17695 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17696 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17697 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17698 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17699 ME->getObjectKind(), ME->isNonOdrUse()); 17700 } 17701 17702 if (ME->getMemberDecl()->isCXXInstanceMember()) 17703 break; 17704 17705 // -- If e is a class member access expression naming a static data member, 17706 // ... 17707 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17708 break; 17709 17710 // Rebuild as a non-odr-use MemberExpr. 17711 MarkNotOdrUsed(); 17712 return MemberExpr::Create( 17713 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17714 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17715 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17716 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17717 return ExprEmpty(); 17718 } 17719 17720 case Expr::BinaryOperatorClass: { 17721 auto *BO = cast<BinaryOperator>(E); 17722 Expr *LHS = BO->getLHS(); 17723 Expr *RHS = BO->getRHS(); 17724 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17725 if (BO->getOpcode() == BO_PtrMemD) { 17726 ExprResult Sub = Rebuild(LHS); 17727 if (!Sub.isUsable()) 17728 return Sub; 17729 LHS = Sub.get(); 17730 // -- If e is a comma expression, ... 17731 } else if (BO->getOpcode() == BO_Comma) { 17732 ExprResult Sub = Rebuild(RHS); 17733 if (!Sub.isUsable()) 17734 return Sub; 17735 RHS = Sub.get(); 17736 } else { 17737 break; 17738 } 17739 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17740 LHS, RHS); 17741 } 17742 17743 // -- If e has the form (e1)... 17744 case Expr::ParenExprClass: { 17745 auto *PE = cast<ParenExpr>(E); 17746 ExprResult Sub = Rebuild(PE->getSubExpr()); 17747 if (!Sub.isUsable()) 17748 return Sub; 17749 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17750 } 17751 17752 // -- If e is a glvalue conditional expression, ... 17753 // We don't apply this to a binary conditional operator. FIXME: Should we? 17754 case Expr::ConditionalOperatorClass: { 17755 auto *CO = cast<ConditionalOperator>(E); 17756 ExprResult LHS = Rebuild(CO->getLHS()); 17757 if (LHS.isInvalid()) 17758 return ExprError(); 17759 ExprResult RHS = Rebuild(CO->getRHS()); 17760 if (RHS.isInvalid()) 17761 return ExprError(); 17762 if (!LHS.isUsable() && !RHS.isUsable()) 17763 return ExprEmpty(); 17764 if (!LHS.isUsable()) 17765 LHS = CO->getLHS(); 17766 if (!RHS.isUsable()) 17767 RHS = CO->getRHS(); 17768 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17769 CO->getCond(), LHS.get(), RHS.get()); 17770 } 17771 17772 // [Clang extension] 17773 // -- If e has the form __extension__ e1... 17774 case Expr::UnaryOperatorClass: { 17775 auto *UO = cast<UnaryOperator>(E); 17776 if (UO->getOpcode() != UO_Extension) 17777 break; 17778 ExprResult Sub = Rebuild(UO->getSubExpr()); 17779 if (!Sub.isUsable()) 17780 return Sub; 17781 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17782 Sub.get()); 17783 } 17784 17785 // [Clang extension] 17786 // -- If e has the form _Generic(...), the set of potential results is the 17787 // union of the sets of potential results of the associated expressions. 17788 case Expr::GenericSelectionExprClass: { 17789 auto *GSE = cast<GenericSelectionExpr>(E); 17790 17791 SmallVector<Expr *, 4> AssocExprs; 17792 bool AnyChanged = false; 17793 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17794 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17795 if (AssocExpr.isInvalid()) 17796 return ExprError(); 17797 if (AssocExpr.isUsable()) { 17798 AssocExprs.push_back(AssocExpr.get()); 17799 AnyChanged = true; 17800 } else { 17801 AssocExprs.push_back(OrigAssocExpr); 17802 } 17803 } 17804 17805 return AnyChanged ? S.CreateGenericSelectionExpr( 17806 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17807 GSE->getRParenLoc(), GSE->getControllingExpr(), 17808 GSE->getAssocTypeSourceInfos(), AssocExprs) 17809 : ExprEmpty(); 17810 } 17811 17812 // [Clang extension] 17813 // -- If e has the form __builtin_choose_expr(...), the set of potential 17814 // results is the union of the sets of potential results of the 17815 // second and third subexpressions. 17816 case Expr::ChooseExprClass: { 17817 auto *CE = cast<ChooseExpr>(E); 17818 17819 ExprResult LHS = Rebuild(CE->getLHS()); 17820 if (LHS.isInvalid()) 17821 return ExprError(); 17822 17823 ExprResult RHS = Rebuild(CE->getLHS()); 17824 if (RHS.isInvalid()) 17825 return ExprError(); 17826 17827 if (!LHS.get() && !RHS.get()) 17828 return ExprEmpty(); 17829 if (!LHS.isUsable()) 17830 LHS = CE->getLHS(); 17831 if (!RHS.isUsable()) 17832 RHS = CE->getRHS(); 17833 17834 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17835 RHS.get(), CE->getRParenLoc()); 17836 } 17837 17838 // Step through non-syntactic nodes. 17839 case Expr::ConstantExprClass: { 17840 auto *CE = cast<ConstantExpr>(E); 17841 ExprResult Sub = Rebuild(CE->getSubExpr()); 17842 if (!Sub.isUsable()) 17843 return Sub; 17844 return ConstantExpr::Create(S.Context, Sub.get()); 17845 } 17846 17847 // We could mostly rely on the recursive rebuilding to rebuild implicit 17848 // casts, but not at the top level, so rebuild them here. 17849 case Expr::ImplicitCastExprClass: { 17850 auto *ICE = cast<ImplicitCastExpr>(E); 17851 // Only step through the narrow set of cast kinds we expect to encounter. 17852 // Anything else suggests we've left the region in which potential results 17853 // can be found. 17854 switch (ICE->getCastKind()) { 17855 case CK_NoOp: 17856 case CK_DerivedToBase: 17857 case CK_UncheckedDerivedToBase: { 17858 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17859 if (!Sub.isUsable()) 17860 return Sub; 17861 CXXCastPath Path(ICE->path()); 17862 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17863 ICE->getValueKind(), &Path); 17864 } 17865 17866 default: 17867 break; 17868 } 17869 break; 17870 } 17871 17872 default: 17873 break; 17874 } 17875 17876 // Can't traverse through this node. Nothing to do. 17877 return ExprEmpty(); 17878 } 17879 17880 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17881 // Check whether the operand is or contains an object of non-trivial C union 17882 // type. 17883 if (E->getType().isVolatileQualified() && 17884 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17885 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17886 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17887 Sema::NTCUC_LValueToRValueVolatile, 17888 NTCUK_Destruct|NTCUK_Copy); 17889 17890 // C++2a [basic.def.odr]p4: 17891 // [...] an expression of non-volatile-qualified non-class type to which 17892 // the lvalue-to-rvalue conversion is applied [...] 17893 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17894 return E; 17895 17896 ExprResult Result = 17897 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17898 if (Result.isInvalid()) 17899 return ExprError(); 17900 return Result.get() ? Result : E; 17901 } 17902 17903 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17904 Res = CorrectDelayedTyposInExpr(Res); 17905 17906 if (!Res.isUsable()) 17907 return Res; 17908 17909 // If a constant-expression is a reference to a variable where we delay 17910 // deciding whether it is an odr-use, just assume we will apply the 17911 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17912 // (a non-type template argument), we have special handling anyway. 17913 return CheckLValueToRValueConversionOperand(Res.get()); 17914 } 17915 17916 void Sema::CleanupVarDeclMarking() { 17917 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17918 // call. 17919 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17920 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17921 17922 for (Expr *E : LocalMaybeODRUseExprs) { 17923 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17924 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17925 DRE->getLocation(), *this); 17926 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17927 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17928 *this); 17929 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17930 for (VarDecl *VD : *FP) 17931 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17932 } else { 17933 llvm_unreachable("Unexpected expression"); 17934 } 17935 } 17936 17937 assert(MaybeODRUseExprs.empty() && 17938 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17939 } 17940 17941 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17942 VarDecl *Var, Expr *E) { 17943 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17944 isa<FunctionParmPackExpr>(E)) && 17945 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17946 Var->setReferenced(); 17947 17948 if (Var->isInvalidDecl()) 17949 return; 17950 17951 // Record a CUDA/HIP static device/constant variable if it is referenced 17952 // by host code. This is done conservatively, when the variable is referenced 17953 // in any of the following contexts: 17954 // - a non-function context 17955 // - a host function 17956 // - a host device function 17957 // This also requires the reference of the static device/constant variable by 17958 // host code to be visible in the device compilation for the compiler to be 17959 // able to externalize the static device/constant variable. 17960 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 17961 auto *CurContext = SemaRef.CurContext; 17962 if (!CurContext || !isa<FunctionDecl>(CurContext) || 17963 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 17964 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 17965 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 17966 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 17967 } 17968 17969 auto *MSI = Var->getMemberSpecializationInfo(); 17970 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17971 : Var->getTemplateSpecializationKind(); 17972 17973 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17974 bool UsableInConstantExpr = 17975 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17976 17977 // C++20 [expr.const]p12: 17978 // A variable [...] is needed for constant evaluation if it is [...] a 17979 // variable whose name appears as a potentially constant evaluated 17980 // expression that is either a contexpr variable or is of non-volatile 17981 // const-qualified integral type or of reference type 17982 bool NeededForConstantEvaluation = 17983 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17984 17985 bool NeedDefinition = 17986 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17987 17988 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17989 "Can't instantiate a partial template specialization."); 17990 17991 // If this might be a member specialization of a static data member, check 17992 // the specialization is visible. We already did the checks for variable 17993 // template specializations when we created them. 17994 if (NeedDefinition && TSK != TSK_Undeclared && 17995 !isa<VarTemplateSpecializationDecl>(Var)) 17996 SemaRef.checkSpecializationVisibility(Loc, Var); 17997 17998 // Perform implicit instantiation of static data members, static data member 17999 // templates of class templates, and variable template specializations. Delay 18000 // instantiations of variable templates, except for those that could be used 18001 // in a constant expression. 18002 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18003 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18004 // instantiation declaration if a variable is usable in a constant 18005 // expression (among other cases). 18006 bool TryInstantiating = 18007 TSK == TSK_ImplicitInstantiation || 18008 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18009 18010 if (TryInstantiating) { 18011 SourceLocation PointOfInstantiation = 18012 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18013 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18014 if (FirstInstantiation) { 18015 PointOfInstantiation = Loc; 18016 if (MSI) 18017 MSI->setPointOfInstantiation(PointOfInstantiation); 18018 else 18019 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18020 } 18021 18022 if (UsableInConstantExpr) { 18023 // Do not defer instantiations of variables that could be used in a 18024 // constant expression. 18025 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18026 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18027 }); 18028 } else if (FirstInstantiation || 18029 isa<VarTemplateSpecializationDecl>(Var)) { 18030 // FIXME: For a specialization of a variable template, we don't 18031 // distinguish between "declaration and type implicitly instantiated" 18032 // and "implicit instantiation of definition requested", so we have 18033 // no direct way to avoid enqueueing the pending instantiation 18034 // multiple times. 18035 SemaRef.PendingInstantiations 18036 .push_back(std::make_pair(Var, PointOfInstantiation)); 18037 } 18038 } 18039 } 18040 18041 // C++2a [basic.def.odr]p4: 18042 // A variable x whose name appears as a potentially-evaluated expression e 18043 // is odr-used by e unless 18044 // -- x is a reference that is usable in constant expressions 18045 // -- x is a variable of non-reference type that is usable in constant 18046 // expressions and has no mutable subobjects [FIXME], and e is an 18047 // element of the set of potential results of an expression of 18048 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18049 // conversion is applied 18050 // -- x is a variable of non-reference type, and e is an element of the set 18051 // of potential results of a discarded-value expression to which the 18052 // lvalue-to-rvalue conversion is not applied [FIXME] 18053 // 18054 // We check the first part of the second bullet here, and 18055 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18056 // FIXME: To get the third bullet right, we need to delay this even for 18057 // variables that are not usable in constant expressions. 18058 18059 // If we already know this isn't an odr-use, there's nothing more to do. 18060 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18061 if (DRE->isNonOdrUse()) 18062 return; 18063 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18064 if (ME->isNonOdrUse()) 18065 return; 18066 18067 switch (OdrUse) { 18068 case OdrUseContext::None: 18069 assert((!E || isa<FunctionParmPackExpr>(E)) && 18070 "missing non-odr-use marking for unevaluated decl ref"); 18071 break; 18072 18073 case OdrUseContext::FormallyOdrUsed: 18074 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18075 // behavior. 18076 break; 18077 18078 case OdrUseContext::Used: 18079 // If we might later find that this expression isn't actually an odr-use, 18080 // delay the marking. 18081 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18082 SemaRef.MaybeODRUseExprs.insert(E); 18083 else 18084 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18085 break; 18086 18087 case OdrUseContext::Dependent: 18088 // If this is a dependent context, we don't need to mark variables as 18089 // odr-used, but we may still need to track them for lambda capture. 18090 // FIXME: Do we also need to do this inside dependent typeid expressions 18091 // (which are modeled as unevaluated at this point)? 18092 const bool RefersToEnclosingScope = 18093 (SemaRef.CurContext != Var->getDeclContext() && 18094 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18095 if (RefersToEnclosingScope) { 18096 LambdaScopeInfo *const LSI = 18097 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18098 if (LSI && (!LSI->CallOperator || 18099 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18100 // If a variable could potentially be odr-used, defer marking it so 18101 // until we finish analyzing the full expression for any 18102 // lvalue-to-rvalue 18103 // or discarded value conversions that would obviate odr-use. 18104 // Add it to the list of potential captures that will be analyzed 18105 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18106 // unless the variable is a reference that was initialized by a constant 18107 // expression (this will never need to be captured or odr-used). 18108 // 18109 // FIXME: We can simplify this a lot after implementing P0588R1. 18110 assert(E && "Capture variable should be used in an expression."); 18111 if (!Var->getType()->isReferenceType() || 18112 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18113 LSI->addPotentialCapture(E->IgnoreParens()); 18114 } 18115 } 18116 break; 18117 } 18118 } 18119 18120 /// Mark a variable referenced, and check whether it is odr-used 18121 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18122 /// used directly for normal expressions referring to VarDecl. 18123 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18124 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18125 } 18126 18127 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18128 Decl *D, Expr *E, bool MightBeOdrUse) { 18129 if (SemaRef.isInOpenMPDeclareTargetContext()) 18130 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18131 18132 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18133 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18134 return; 18135 } 18136 18137 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18138 18139 // If this is a call to a method via a cast, also mark the method in the 18140 // derived class used in case codegen can devirtualize the call. 18141 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18142 if (!ME) 18143 return; 18144 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18145 if (!MD) 18146 return; 18147 // Only attempt to devirtualize if this is truly a virtual call. 18148 bool IsVirtualCall = MD->isVirtual() && 18149 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18150 if (!IsVirtualCall) 18151 return; 18152 18153 // If it's possible to devirtualize the call, mark the called function 18154 // referenced. 18155 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18156 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18157 if (DM) 18158 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18159 } 18160 18161 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18162 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18163 // TODO: update this with DR# once a defect report is filed. 18164 // C++11 defect. The address of a pure member should not be an ODR use, even 18165 // if it's a qualified reference. 18166 bool OdrUse = true; 18167 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18168 if (Method->isVirtual() && 18169 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18170 OdrUse = false; 18171 18172 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18173 if (!isConstantEvaluated() && FD->isConsteval() && 18174 !RebuildingImmediateInvocation) 18175 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18176 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18177 } 18178 18179 /// Perform reference-marking and odr-use handling for a MemberExpr. 18180 void Sema::MarkMemberReferenced(MemberExpr *E) { 18181 // C++11 [basic.def.odr]p2: 18182 // A non-overloaded function whose name appears as a potentially-evaluated 18183 // expression or a member of a set of candidate functions, if selected by 18184 // overload resolution when referred to from a potentially-evaluated 18185 // expression, is odr-used, unless it is a pure virtual function and its 18186 // name is not explicitly qualified. 18187 bool MightBeOdrUse = true; 18188 if (E->performsVirtualDispatch(getLangOpts())) { 18189 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18190 if (Method->isPure()) 18191 MightBeOdrUse = false; 18192 } 18193 SourceLocation Loc = 18194 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18195 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18196 } 18197 18198 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18199 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18200 for (VarDecl *VD : *E) 18201 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18202 } 18203 18204 /// Perform marking for a reference to an arbitrary declaration. It 18205 /// marks the declaration referenced, and performs odr-use checking for 18206 /// functions and variables. This method should not be used when building a 18207 /// normal expression which refers to a variable. 18208 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18209 bool MightBeOdrUse) { 18210 if (MightBeOdrUse) { 18211 if (auto *VD = dyn_cast<VarDecl>(D)) { 18212 MarkVariableReferenced(Loc, VD); 18213 return; 18214 } 18215 } 18216 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18217 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18218 return; 18219 } 18220 D->setReferenced(); 18221 } 18222 18223 namespace { 18224 // Mark all of the declarations used by a type as referenced. 18225 // FIXME: Not fully implemented yet! We need to have a better understanding 18226 // of when we're entering a context we should not recurse into. 18227 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18228 // TreeTransforms rebuilding the type in a new context. Rather than 18229 // duplicating the TreeTransform logic, we should consider reusing it here. 18230 // Currently that causes problems when rebuilding LambdaExprs. 18231 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18232 Sema &S; 18233 SourceLocation Loc; 18234 18235 public: 18236 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18237 18238 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18239 18240 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18241 }; 18242 } 18243 18244 bool MarkReferencedDecls::TraverseTemplateArgument( 18245 const TemplateArgument &Arg) { 18246 { 18247 // A non-type template argument is a constant-evaluated context. 18248 EnterExpressionEvaluationContext Evaluated( 18249 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18250 if (Arg.getKind() == TemplateArgument::Declaration) { 18251 if (Decl *D = Arg.getAsDecl()) 18252 S.MarkAnyDeclReferenced(Loc, D, true); 18253 } else if (Arg.getKind() == TemplateArgument::Expression) { 18254 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18255 } 18256 } 18257 18258 return Inherited::TraverseTemplateArgument(Arg); 18259 } 18260 18261 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18262 MarkReferencedDecls Marker(*this, Loc); 18263 Marker.TraverseType(T); 18264 } 18265 18266 namespace { 18267 /// Helper class that marks all of the declarations referenced by 18268 /// potentially-evaluated subexpressions as "referenced". 18269 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18270 public: 18271 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18272 bool SkipLocalVariables; 18273 18274 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18275 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18276 18277 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18278 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18279 } 18280 18281 void VisitDeclRefExpr(DeclRefExpr *E) { 18282 // If we were asked not to visit local variables, don't. 18283 if (SkipLocalVariables) { 18284 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18285 if (VD->hasLocalStorage()) 18286 return; 18287 } 18288 S.MarkDeclRefReferenced(E); 18289 } 18290 18291 void VisitMemberExpr(MemberExpr *E) { 18292 S.MarkMemberReferenced(E); 18293 Visit(E->getBase()); 18294 } 18295 }; 18296 } // namespace 18297 18298 /// Mark any declarations that appear within this expression or any 18299 /// potentially-evaluated subexpressions as "referenced". 18300 /// 18301 /// \param SkipLocalVariables If true, don't mark local variables as 18302 /// 'referenced'. 18303 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18304 bool SkipLocalVariables) { 18305 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18306 } 18307 18308 /// Emit a diagnostic that describes an effect on the run-time behavior 18309 /// of the program being compiled. 18310 /// 18311 /// This routine emits the given diagnostic when the code currently being 18312 /// type-checked is "potentially evaluated", meaning that there is a 18313 /// possibility that the code will actually be executable. Code in sizeof() 18314 /// expressions, code used only during overload resolution, etc., are not 18315 /// potentially evaluated. This routine will suppress such diagnostics or, 18316 /// in the absolutely nutty case of potentially potentially evaluated 18317 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18318 /// later. 18319 /// 18320 /// This routine should be used for all diagnostics that describe the run-time 18321 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18322 /// Failure to do so will likely result in spurious diagnostics or failures 18323 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18324 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18325 const PartialDiagnostic &PD) { 18326 switch (ExprEvalContexts.back().Context) { 18327 case ExpressionEvaluationContext::Unevaluated: 18328 case ExpressionEvaluationContext::UnevaluatedList: 18329 case ExpressionEvaluationContext::UnevaluatedAbstract: 18330 case ExpressionEvaluationContext::DiscardedStatement: 18331 // The argument will never be evaluated, so don't complain. 18332 break; 18333 18334 case ExpressionEvaluationContext::ConstantEvaluated: 18335 // Relevant diagnostics should be produced by constant evaluation. 18336 break; 18337 18338 case ExpressionEvaluationContext::PotentiallyEvaluated: 18339 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18340 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18341 FunctionScopes.back()->PossiblyUnreachableDiags. 18342 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18343 return true; 18344 } 18345 18346 // The initializer of a constexpr variable or of the first declaration of a 18347 // static data member is not syntactically a constant evaluated constant, 18348 // but nonetheless is always required to be a constant expression, so we 18349 // can skip diagnosing. 18350 // FIXME: Using the mangling context here is a hack. 18351 if (auto *VD = dyn_cast_or_null<VarDecl>( 18352 ExprEvalContexts.back().ManglingContextDecl)) { 18353 if (VD->isConstexpr() || 18354 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18355 break; 18356 // FIXME: For any other kind of variable, we should build a CFG for its 18357 // initializer and check whether the context in question is reachable. 18358 } 18359 18360 Diag(Loc, PD); 18361 return true; 18362 } 18363 18364 return false; 18365 } 18366 18367 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18368 const PartialDiagnostic &PD) { 18369 return DiagRuntimeBehavior( 18370 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18371 } 18372 18373 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18374 CallExpr *CE, FunctionDecl *FD) { 18375 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18376 return false; 18377 18378 // If we're inside a decltype's expression, don't check for a valid return 18379 // type or construct temporaries until we know whether this is the last call. 18380 if (ExprEvalContexts.back().ExprContext == 18381 ExpressionEvaluationContextRecord::EK_Decltype) { 18382 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18383 return false; 18384 } 18385 18386 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18387 FunctionDecl *FD; 18388 CallExpr *CE; 18389 18390 public: 18391 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18392 : FD(FD), CE(CE) { } 18393 18394 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18395 if (!FD) { 18396 S.Diag(Loc, diag::err_call_incomplete_return) 18397 << T << CE->getSourceRange(); 18398 return; 18399 } 18400 18401 S.Diag(Loc, diag::err_call_function_incomplete_return) 18402 << CE->getSourceRange() << FD << T; 18403 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18404 << FD->getDeclName(); 18405 } 18406 } Diagnoser(FD, CE); 18407 18408 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18409 return true; 18410 18411 return false; 18412 } 18413 18414 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18415 // will prevent this condition from triggering, which is what we want. 18416 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18417 SourceLocation Loc; 18418 18419 unsigned diagnostic = diag::warn_condition_is_assignment; 18420 bool IsOrAssign = false; 18421 18422 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18423 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18424 return; 18425 18426 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18427 18428 // Greylist some idioms by putting them into a warning subcategory. 18429 if (ObjCMessageExpr *ME 18430 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18431 Selector Sel = ME->getSelector(); 18432 18433 // self = [<foo> init...] 18434 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18435 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18436 18437 // <foo> = [<bar> nextObject] 18438 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18439 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18440 } 18441 18442 Loc = Op->getOperatorLoc(); 18443 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18444 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18445 return; 18446 18447 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18448 Loc = Op->getOperatorLoc(); 18449 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18450 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18451 else { 18452 // Not an assignment. 18453 return; 18454 } 18455 18456 Diag(Loc, diagnostic) << E->getSourceRange(); 18457 18458 SourceLocation Open = E->getBeginLoc(); 18459 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18460 Diag(Loc, diag::note_condition_assign_silence) 18461 << FixItHint::CreateInsertion(Open, "(") 18462 << FixItHint::CreateInsertion(Close, ")"); 18463 18464 if (IsOrAssign) 18465 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18466 << FixItHint::CreateReplacement(Loc, "!="); 18467 else 18468 Diag(Loc, diag::note_condition_assign_to_comparison) 18469 << FixItHint::CreateReplacement(Loc, "=="); 18470 } 18471 18472 /// Redundant parentheses over an equality comparison can indicate 18473 /// that the user intended an assignment used as condition. 18474 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18475 // Don't warn if the parens came from a macro. 18476 SourceLocation parenLoc = ParenE->getBeginLoc(); 18477 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18478 return; 18479 // Don't warn for dependent expressions. 18480 if (ParenE->isTypeDependent()) 18481 return; 18482 18483 Expr *E = ParenE->IgnoreParens(); 18484 18485 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18486 if (opE->getOpcode() == BO_EQ && 18487 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18488 == Expr::MLV_Valid) { 18489 SourceLocation Loc = opE->getOperatorLoc(); 18490 18491 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18492 SourceRange ParenERange = ParenE->getSourceRange(); 18493 Diag(Loc, diag::note_equality_comparison_silence) 18494 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18495 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18496 Diag(Loc, diag::note_equality_comparison_to_assign) 18497 << FixItHint::CreateReplacement(Loc, "="); 18498 } 18499 } 18500 18501 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18502 bool IsConstexpr) { 18503 DiagnoseAssignmentAsCondition(E); 18504 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18505 DiagnoseEqualityWithExtraParens(parenE); 18506 18507 ExprResult result = CheckPlaceholderExpr(E); 18508 if (result.isInvalid()) return ExprError(); 18509 E = result.get(); 18510 18511 if (!E->isTypeDependent()) { 18512 if (getLangOpts().CPlusPlus) 18513 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18514 18515 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18516 if (ERes.isInvalid()) 18517 return ExprError(); 18518 E = ERes.get(); 18519 18520 QualType T = E->getType(); 18521 if (!T->isScalarType()) { // C99 6.8.4.1p1 18522 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18523 << T << E->getSourceRange(); 18524 return ExprError(); 18525 } 18526 CheckBoolLikeConversion(E, Loc); 18527 } 18528 18529 return E; 18530 } 18531 18532 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18533 Expr *SubExpr, ConditionKind CK) { 18534 // Empty conditions are valid in for-statements. 18535 if (!SubExpr) 18536 return ConditionResult(); 18537 18538 ExprResult Cond; 18539 switch (CK) { 18540 case ConditionKind::Boolean: 18541 Cond = CheckBooleanCondition(Loc, SubExpr); 18542 break; 18543 18544 case ConditionKind::ConstexprIf: 18545 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18546 break; 18547 18548 case ConditionKind::Switch: 18549 Cond = CheckSwitchCondition(Loc, SubExpr); 18550 break; 18551 } 18552 if (Cond.isInvalid()) { 18553 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18554 {SubExpr}); 18555 if (!Cond.get()) 18556 return ConditionError(); 18557 } 18558 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18559 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18560 if (!FullExpr.get()) 18561 return ConditionError(); 18562 18563 return ConditionResult(*this, nullptr, FullExpr, 18564 CK == ConditionKind::ConstexprIf); 18565 } 18566 18567 namespace { 18568 /// A visitor for rebuilding a call to an __unknown_any expression 18569 /// to have an appropriate type. 18570 struct RebuildUnknownAnyFunction 18571 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18572 18573 Sema &S; 18574 18575 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18576 18577 ExprResult VisitStmt(Stmt *S) { 18578 llvm_unreachable("unexpected statement!"); 18579 } 18580 18581 ExprResult VisitExpr(Expr *E) { 18582 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18583 << E->getSourceRange(); 18584 return ExprError(); 18585 } 18586 18587 /// Rebuild an expression which simply semantically wraps another 18588 /// expression which it shares the type and value kind of. 18589 template <class T> ExprResult rebuildSugarExpr(T *E) { 18590 ExprResult SubResult = Visit(E->getSubExpr()); 18591 if (SubResult.isInvalid()) return ExprError(); 18592 18593 Expr *SubExpr = SubResult.get(); 18594 E->setSubExpr(SubExpr); 18595 E->setType(SubExpr->getType()); 18596 E->setValueKind(SubExpr->getValueKind()); 18597 assert(E->getObjectKind() == OK_Ordinary); 18598 return E; 18599 } 18600 18601 ExprResult VisitParenExpr(ParenExpr *E) { 18602 return rebuildSugarExpr(E); 18603 } 18604 18605 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18606 return rebuildSugarExpr(E); 18607 } 18608 18609 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18610 ExprResult SubResult = Visit(E->getSubExpr()); 18611 if (SubResult.isInvalid()) return ExprError(); 18612 18613 Expr *SubExpr = SubResult.get(); 18614 E->setSubExpr(SubExpr); 18615 E->setType(S.Context.getPointerType(SubExpr->getType())); 18616 assert(E->getValueKind() == VK_RValue); 18617 assert(E->getObjectKind() == OK_Ordinary); 18618 return E; 18619 } 18620 18621 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18622 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18623 18624 E->setType(VD->getType()); 18625 18626 assert(E->getValueKind() == VK_RValue); 18627 if (S.getLangOpts().CPlusPlus && 18628 !(isa<CXXMethodDecl>(VD) && 18629 cast<CXXMethodDecl>(VD)->isInstance())) 18630 E->setValueKind(VK_LValue); 18631 18632 return E; 18633 } 18634 18635 ExprResult VisitMemberExpr(MemberExpr *E) { 18636 return resolveDecl(E, E->getMemberDecl()); 18637 } 18638 18639 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18640 return resolveDecl(E, E->getDecl()); 18641 } 18642 }; 18643 } 18644 18645 /// Given a function expression of unknown-any type, try to rebuild it 18646 /// to have a function type. 18647 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18648 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18649 if (Result.isInvalid()) return ExprError(); 18650 return S.DefaultFunctionArrayConversion(Result.get()); 18651 } 18652 18653 namespace { 18654 /// A visitor for rebuilding an expression of type __unknown_anytype 18655 /// into one which resolves the type directly on the referring 18656 /// expression. Strict preservation of the original source 18657 /// structure is not a goal. 18658 struct RebuildUnknownAnyExpr 18659 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18660 18661 Sema &S; 18662 18663 /// The current destination type. 18664 QualType DestType; 18665 18666 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18667 : S(S), DestType(CastType) {} 18668 18669 ExprResult VisitStmt(Stmt *S) { 18670 llvm_unreachable("unexpected statement!"); 18671 } 18672 18673 ExprResult VisitExpr(Expr *E) { 18674 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18675 << E->getSourceRange(); 18676 return ExprError(); 18677 } 18678 18679 ExprResult VisitCallExpr(CallExpr *E); 18680 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18681 18682 /// Rebuild an expression which simply semantically wraps another 18683 /// expression which it shares the type and value kind of. 18684 template <class T> ExprResult rebuildSugarExpr(T *E) { 18685 ExprResult SubResult = Visit(E->getSubExpr()); 18686 if (SubResult.isInvalid()) return ExprError(); 18687 Expr *SubExpr = SubResult.get(); 18688 E->setSubExpr(SubExpr); 18689 E->setType(SubExpr->getType()); 18690 E->setValueKind(SubExpr->getValueKind()); 18691 assert(E->getObjectKind() == OK_Ordinary); 18692 return E; 18693 } 18694 18695 ExprResult VisitParenExpr(ParenExpr *E) { 18696 return rebuildSugarExpr(E); 18697 } 18698 18699 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18700 return rebuildSugarExpr(E); 18701 } 18702 18703 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18704 const PointerType *Ptr = DestType->getAs<PointerType>(); 18705 if (!Ptr) { 18706 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18707 << E->getSourceRange(); 18708 return ExprError(); 18709 } 18710 18711 if (isa<CallExpr>(E->getSubExpr())) { 18712 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18713 << E->getSourceRange(); 18714 return ExprError(); 18715 } 18716 18717 assert(E->getValueKind() == VK_RValue); 18718 assert(E->getObjectKind() == OK_Ordinary); 18719 E->setType(DestType); 18720 18721 // Build the sub-expression as if it were an object of the pointee type. 18722 DestType = Ptr->getPointeeType(); 18723 ExprResult SubResult = Visit(E->getSubExpr()); 18724 if (SubResult.isInvalid()) return ExprError(); 18725 E->setSubExpr(SubResult.get()); 18726 return E; 18727 } 18728 18729 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18730 18731 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18732 18733 ExprResult VisitMemberExpr(MemberExpr *E) { 18734 return resolveDecl(E, E->getMemberDecl()); 18735 } 18736 18737 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18738 return resolveDecl(E, E->getDecl()); 18739 } 18740 }; 18741 } 18742 18743 /// Rebuilds a call expression which yielded __unknown_anytype. 18744 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18745 Expr *CalleeExpr = E->getCallee(); 18746 18747 enum FnKind { 18748 FK_MemberFunction, 18749 FK_FunctionPointer, 18750 FK_BlockPointer 18751 }; 18752 18753 FnKind Kind; 18754 QualType CalleeType = CalleeExpr->getType(); 18755 if (CalleeType == S.Context.BoundMemberTy) { 18756 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18757 Kind = FK_MemberFunction; 18758 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18759 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18760 CalleeType = Ptr->getPointeeType(); 18761 Kind = FK_FunctionPointer; 18762 } else { 18763 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18764 Kind = FK_BlockPointer; 18765 } 18766 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18767 18768 // Verify that this is a legal result type of a function. 18769 if (DestType->isArrayType() || DestType->isFunctionType()) { 18770 unsigned diagID = diag::err_func_returning_array_function; 18771 if (Kind == FK_BlockPointer) 18772 diagID = diag::err_block_returning_array_function; 18773 18774 S.Diag(E->getExprLoc(), diagID) 18775 << DestType->isFunctionType() << DestType; 18776 return ExprError(); 18777 } 18778 18779 // Otherwise, go ahead and set DestType as the call's result. 18780 E->setType(DestType.getNonLValueExprType(S.Context)); 18781 E->setValueKind(Expr::getValueKindForType(DestType)); 18782 assert(E->getObjectKind() == OK_Ordinary); 18783 18784 // Rebuild the function type, replacing the result type with DestType. 18785 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18786 if (Proto) { 18787 // __unknown_anytype(...) is a special case used by the debugger when 18788 // it has no idea what a function's signature is. 18789 // 18790 // We want to build this call essentially under the K&R 18791 // unprototyped rules, but making a FunctionNoProtoType in C++ 18792 // would foul up all sorts of assumptions. However, we cannot 18793 // simply pass all arguments as variadic arguments, nor can we 18794 // portably just call the function under a non-variadic type; see 18795 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18796 // However, it turns out that in practice it is generally safe to 18797 // call a function declared as "A foo(B,C,D);" under the prototype 18798 // "A foo(B,C,D,...);". The only known exception is with the 18799 // Windows ABI, where any variadic function is implicitly cdecl 18800 // regardless of its normal CC. Therefore we change the parameter 18801 // types to match the types of the arguments. 18802 // 18803 // This is a hack, but it is far superior to moving the 18804 // corresponding target-specific code from IR-gen to Sema/AST. 18805 18806 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18807 SmallVector<QualType, 8> ArgTypes; 18808 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18809 ArgTypes.reserve(E->getNumArgs()); 18810 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18811 Expr *Arg = E->getArg(i); 18812 QualType ArgType = Arg->getType(); 18813 if (E->isLValue()) { 18814 ArgType = S.Context.getLValueReferenceType(ArgType); 18815 } else if (E->isXValue()) { 18816 ArgType = S.Context.getRValueReferenceType(ArgType); 18817 } 18818 ArgTypes.push_back(ArgType); 18819 } 18820 ParamTypes = ArgTypes; 18821 } 18822 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18823 Proto->getExtProtoInfo()); 18824 } else { 18825 DestType = S.Context.getFunctionNoProtoType(DestType, 18826 FnType->getExtInfo()); 18827 } 18828 18829 // Rebuild the appropriate pointer-to-function type. 18830 switch (Kind) { 18831 case FK_MemberFunction: 18832 // Nothing to do. 18833 break; 18834 18835 case FK_FunctionPointer: 18836 DestType = S.Context.getPointerType(DestType); 18837 break; 18838 18839 case FK_BlockPointer: 18840 DestType = S.Context.getBlockPointerType(DestType); 18841 break; 18842 } 18843 18844 // Finally, we can recurse. 18845 ExprResult CalleeResult = Visit(CalleeExpr); 18846 if (!CalleeResult.isUsable()) return ExprError(); 18847 E->setCallee(CalleeResult.get()); 18848 18849 // Bind a temporary if necessary. 18850 return S.MaybeBindToTemporary(E); 18851 } 18852 18853 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18854 // Verify that this is a legal result type of a call. 18855 if (DestType->isArrayType() || DestType->isFunctionType()) { 18856 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18857 << DestType->isFunctionType() << DestType; 18858 return ExprError(); 18859 } 18860 18861 // Rewrite the method result type if available. 18862 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18863 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18864 Method->setReturnType(DestType); 18865 } 18866 18867 // Change the type of the message. 18868 E->setType(DestType.getNonReferenceType()); 18869 E->setValueKind(Expr::getValueKindForType(DestType)); 18870 18871 return S.MaybeBindToTemporary(E); 18872 } 18873 18874 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18875 // The only case we should ever see here is a function-to-pointer decay. 18876 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18877 assert(E->getValueKind() == VK_RValue); 18878 assert(E->getObjectKind() == OK_Ordinary); 18879 18880 E->setType(DestType); 18881 18882 // Rebuild the sub-expression as the pointee (function) type. 18883 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18884 18885 ExprResult Result = Visit(E->getSubExpr()); 18886 if (!Result.isUsable()) return ExprError(); 18887 18888 E->setSubExpr(Result.get()); 18889 return E; 18890 } else if (E->getCastKind() == CK_LValueToRValue) { 18891 assert(E->getValueKind() == VK_RValue); 18892 assert(E->getObjectKind() == OK_Ordinary); 18893 18894 assert(isa<BlockPointerType>(E->getType())); 18895 18896 E->setType(DestType); 18897 18898 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18899 DestType = S.Context.getLValueReferenceType(DestType); 18900 18901 ExprResult Result = Visit(E->getSubExpr()); 18902 if (!Result.isUsable()) return ExprError(); 18903 18904 E->setSubExpr(Result.get()); 18905 return E; 18906 } else { 18907 llvm_unreachable("Unhandled cast type!"); 18908 } 18909 } 18910 18911 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18912 ExprValueKind ValueKind = VK_LValue; 18913 QualType Type = DestType; 18914 18915 // We know how to make this work for certain kinds of decls: 18916 18917 // - functions 18918 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18919 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18920 DestType = Ptr->getPointeeType(); 18921 ExprResult Result = resolveDecl(E, VD); 18922 if (Result.isInvalid()) return ExprError(); 18923 return S.ImpCastExprToType(Result.get(), Type, 18924 CK_FunctionToPointerDecay, VK_RValue); 18925 } 18926 18927 if (!Type->isFunctionType()) { 18928 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18929 << VD << E->getSourceRange(); 18930 return ExprError(); 18931 } 18932 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18933 // We must match the FunctionDecl's type to the hack introduced in 18934 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18935 // type. See the lengthy commentary in that routine. 18936 QualType FDT = FD->getType(); 18937 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18938 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18939 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18940 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18941 SourceLocation Loc = FD->getLocation(); 18942 FunctionDecl *NewFD = FunctionDecl::Create( 18943 S.Context, FD->getDeclContext(), Loc, Loc, 18944 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18945 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18946 /*ConstexprKind*/ CSK_unspecified); 18947 18948 if (FD->getQualifier()) 18949 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18950 18951 SmallVector<ParmVarDecl*, 16> Params; 18952 for (const auto &AI : FT->param_types()) { 18953 ParmVarDecl *Param = 18954 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18955 Param->setScopeInfo(0, Params.size()); 18956 Params.push_back(Param); 18957 } 18958 NewFD->setParams(Params); 18959 DRE->setDecl(NewFD); 18960 VD = DRE->getDecl(); 18961 } 18962 } 18963 18964 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18965 if (MD->isInstance()) { 18966 ValueKind = VK_RValue; 18967 Type = S.Context.BoundMemberTy; 18968 } 18969 18970 // Function references aren't l-values in C. 18971 if (!S.getLangOpts().CPlusPlus) 18972 ValueKind = VK_RValue; 18973 18974 // - variables 18975 } else if (isa<VarDecl>(VD)) { 18976 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18977 Type = RefTy->getPointeeType(); 18978 } else if (Type->isFunctionType()) { 18979 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18980 << VD << E->getSourceRange(); 18981 return ExprError(); 18982 } 18983 18984 // - nothing else 18985 } else { 18986 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18987 << VD << E->getSourceRange(); 18988 return ExprError(); 18989 } 18990 18991 // Modifying the declaration like this is friendly to IR-gen but 18992 // also really dangerous. 18993 VD->setType(DestType); 18994 E->setType(Type); 18995 E->setValueKind(ValueKind); 18996 return E; 18997 } 18998 18999 /// Check a cast of an unknown-any type. We intentionally only 19000 /// trigger this for C-style casts. 19001 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19002 Expr *CastExpr, CastKind &CastKind, 19003 ExprValueKind &VK, CXXCastPath &Path) { 19004 // The type we're casting to must be either void or complete. 19005 if (!CastType->isVoidType() && 19006 RequireCompleteType(TypeRange.getBegin(), CastType, 19007 diag::err_typecheck_cast_to_incomplete)) 19008 return ExprError(); 19009 19010 // Rewrite the casted expression from scratch. 19011 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19012 if (!result.isUsable()) return ExprError(); 19013 19014 CastExpr = result.get(); 19015 VK = CastExpr->getValueKind(); 19016 CastKind = CK_NoOp; 19017 19018 return CastExpr; 19019 } 19020 19021 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19022 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19023 } 19024 19025 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19026 Expr *arg, QualType ¶mType) { 19027 // If the syntactic form of the argument is not an explicit cast of 19028 // any sort, just do default argument promotion. 19029 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19030 if (!castArg) { 19031 ExprResult result = DefaultArgumentPromotion(arg); 19032 if (result.isInvalid()) return ExprError(); 19033 paramType = result.get()->getType(); 19034 return result; 19035 } 19036 19037 // Otherwise, use the type that was written in the explicit cast. 19038 assert(!arg->hasPlaceholderType()); 19039 paramType = castArg->getTypeAsWritten(); 19040 19041 // Copy-initialize a parameter of that type. 19042 InitializedEntity entity = 19043 InitializedEntity::InitializeParameter(Context, paramType, 19044 /*consumed*/ false); 19045 return PerformCopyInitialization(entity, callLoc, arg); 19046 } 19047 19048 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19049 Expr *orig = E; 19050 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19051 while (true) { 19052 E = E->IgnoreParenImpCasts(); 19053 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19054 E = call->getCallee(); 19055 diagID = diag::err_uncasted_call_of_unknown_any; 19056 } else { 19057 break; 19058 } 19059 } 19060 19061 SourceLocation loc; 19062 NamedDecl *d; 19063 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19064 loc = ref->getLocation(); 19065 d = ref->getDecl(); 19066 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19067 loc = mem->getMemberLoc(); 19068 d = mem->getMemberDecl(); 19069 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19070 diagID = diag::err_uncasted_call_of_unknown_any; 19071 loc = msg->getSelectorStartLoc(); 19072 d = msg->getMethodDecl(); 19073 if (!d) { 19074 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19075 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19076 << orig->getSourceRange(); 19077 return ExprError(); 19078 } 19079 } else { 19080 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19081 << E->getSourceRange(); 19082 return ExprError(); 19083 } 19084 19085 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19086 19087 // Never recoverable. 19088 return ExprError(); 19089 } 19090 19091 /// Check for operands with placeholder types and complain if found. 19092 /// Returns ExprError() if there was an error and no recovery was possible. 19093 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19094 if (!Context.isDependenceAllowed()) { 19095 // C cannot handle TypoExpr nodes on either side of a binop because it 19096 // doesn't handle dependent types properly, so make sure any TypoExprs have 19097 // been dealt with before checking the operands. 19098 ExprResult Result = CorrectDelayedTyposInExpr(E); 19099 if (!Result.isUsable()) return ExprError(); 19100 E = Result.get(); 19101 } 19102 19103 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19104 if (!placeholderType) return E; 19105 19106 switch (placeholderType->getKind()) { 19107 19108 // Overloaded expressions. 19109 case BuiltinType::Overload: { 19110 // Try to resolve a single function template specialization. 19111 // This is obligatory. 19112 ExprResult Result = E; 19113 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19114 return Result; 19115 19116 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19117 // leaves Result unchanged on failure. 19118 Result = E; 19119 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19120 return Result; 19121 19122 // If that failed, try to recover with a call. 19123 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19124 /*complain*/ true); 19125 return Result; 19126 } 19127 19128 // Bound member functions. 19129 case BuiltinType::BoundMember: { 19130 ExprResult result = E; 19131 const Expr *BME = E->IgnoreParens(); 19132 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19133 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19134 if (isa<CXXPseudoDestructorExpr>(BME)) { 19135 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19136 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19137 if (ME->getMemberNameInfo().getName().getNameKind() == 19138 DeclarationName::CXXDestructorName) 19139 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19140 } 19141 tryToRecoverWithCall(result, PD, 19142 /*complain*/ true); 19143 return result; 19144 } 19145 19146 // ARC unbridged casts. 19147 case BuiltinType::ARCUnbridgedCast: { 19148 Expr *realCast = stripARCUnbridgedCast(E); 19149 diagnoseARCUnbridgedCast(realCast); 19150 return realCast; 19151 } 19152 19153 // Expressions of unknown type. 19154 case BuiltinType::UnknownAny: 19155 return diagnoseUnknownAnyExpr(*this, E); 19156 19157 // Pseudo-objects. 19158 case BuiltinType::PseudoObject: 19159 return checkPseudoObjectRValue(E); 19160 19161 case BuiltinType::BuiltinFn: { 19162 // Accept __noop without parens by implicitly converting it to a call expr. 19163 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19164 if (DRE) { 19165 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19166 if (FD->getBuiltinID() == Builtin::BI__noop) { 19167 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19168 CK_BuiltinFnToFnPtr) 19169 .get(); 19170 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19171 VK_RValue, SourceLocation(), 19172 FPOptionsOverride()); 19173 } 19174 } 19175 19176 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19177 return ExprError(); 19178 } 19179 19180 case BuiltinType::IncompleteMatrixIdx: 19181 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19182 ->getRowIdx() 19183 ->getBeginLoc(), 19184 diag::err_matrix_incomplete_index); 19185 return ExprError(); 19186 19187 // Expressions of unknown type. 19188 case BuiltinType::OMPArraySection: 19189 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19190 return ExprError(); 19191 19192 // Expressions of unknown type. 19193 case BuiltinType::OMPArrayShaping: 19194 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19195 19196 case BuiltinType::OMPIterator: 19197 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19198 19199 // Everything else should be impossible. 19200 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19201 case BuiltinType::Id: 19202 #include "clang/Basic/OpenCLImageTypes.def" 19203 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19204 case BuiltinType::Id: 19205 #include "clang/Basic/OpenCLExtensionTypes.def" 19206 #define SVE_TYPE(Name, Id, SingletonId) \ 19207 case BuiltinType::Id: 19208 #include "clang/Basic/AArch64SVEACLETypes.def" 19209 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19210 #define PLACEHOLDER_TYPE(Id, SingletonId) 19211 #include "clang/AST/BuiltinTypes.def" 19212 break; 19213 } 19214 19215 llvm_unreachable("invalid placeholder type!"); 19216 } 19217 19218 bool Sema::CheckCaseExpression(Expr *E) { 19219 if (E->isTypeDependent()) 19220 return true; 19221 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19222 return E->getType()->isIntegralOrEnumerationType(); 19223 return false; 19224 } 19225 19226 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19227 ExprResult 19228 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19229 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19230 "Unknown Objective-C Boolean value!"); 19231 QualType BoolT = Context.ObjCBuiltinBoolTy; 19232 if (!Context.getBOOLDecl()) { 19233 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19234 Sema::LookupOrdinaryName); 19235 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19236 NamedDecl *ND = Result.getFoundDecl(); 19237 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19238 Context.setBOOLDecl(TD); 19239 } 19240 } 19241 if (Context.getBOOLDecl()) 19242 BoolT = Context.getBOOLType(); 19243 return new (Context) 19244 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19245 } 19246 19247 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19248 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19249 SourceLocation RParen) { 19250 19251 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19252 19253 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19254 return Spec.getPlatform() == Platform; 19255 }); 19256 19257 VersionTuple Version; 19258 if (Spec != AvailSpecs.end()) 19259 Version = Spec->getVersion(); 19260 19261 // The use of `@available` in the enclosing function should be analyzed to 19262 // warn when it's used inappropriately (i.e. not if(@available)). 19263 if (getCurFunctionOrMethodDecl()) 19264 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19265 else if (getCurBlock() || getCurLambda()) 19266 getCurFunction()->HasPotentialAvailabilityViolations = true; 19267 19268 return new (Context) 19269 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19270 } 19271 19272 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19273 ArrayRef<Expr *> SubExprs, QualType T) { 19274 if (!Context.getLangOpts().RecoveryAST) 19275 return ExprError(); 19276 19277 if (isSFINAEContext()) 19278 return ExprError(); 19279 19280 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19281 // We don't know the concrete type, fallback to dependent type. 19282 T = Context.DependentTy; 19283 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19284 } 19285