1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/FixedPoint.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 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 701 // C11 6.3.2.1p2: 702 // ... if the lvalue has atomic type, the value has the non-atomic version 703 // of the type of the lvalue ... 704 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 705 T = Atomic->getValueType().getUnqualifiedType(); 706 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 707 nullptr, VK_RValue); 708 } 709 710 return Res; 711 } 712 713 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 714 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 715 if (Res.isInvalid()) 716 return ExprError(); 717 Res = DefaultLvalueConversion(Res.get()); 718 if (Res.isInvalid()) 719 return ExprError(); 720 return Res; 721 } 722 723 /// CallExprUnaryConversions - a special case of an unary conversion 724 /// performed on a function designator of a call expression. 725 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 726 QualType Ty = E->getType(); 727 ExprResult Res = E; 728 // Only do implicit cast for a function type, but not for a pointer 729 // to function type. 730 if (Ty->isFunctionType()) { 731 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 732 CK_FunctionToPointerDecay); 733 if (Res.isInvalid()) 734 return ExprError(); 735 } 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res.get(); 740 } 741 742 /// UsualUnaryConversions - Performs various conversions that are common to most 743 /// operators (C99 6.3). The conversions of array and function types are 744 /// sometimes suppressed. For example, the array->pointer conversion doesn't 745 /// apply if the array is an argument to the sizeof or address (&) operators. 746 /// In these instances, this routine should *not* be called. 747 ExprResult Sema::UsualUnaryConversions(Expr *E) { 748 // First, convert to an r-value. 749 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 750 if (Res.isInvalid()) 751 return ExprError(); 752 E = Res.get(); 753 754 QualType Ty = E->getType(); 755 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 756 757 // Half FP have to be promoted to float unless it is natively supported 758 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 759 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 760 761 // Try to perform integral promotions if the object has a theoretically 762 // promotable type. 763 if (Ty->isIntegralOrUnscopedEnumerationType()) { 764 // C99 6.3.1.1p2: 765 // 766 // The following may be used in an expression wherever an int or 767 // unsigned int may be used: 768 // - an object or expression with an integer type whose integer 769 // conversion rank is less than or equal to the rank of int 770 // and unsigned int. 771 // - A bit-field of type _Bool, int, signed int, or unsigned int. 772 // 773 // If an int can represent all values of the original type, the 774 // value is converted to an int; otherwise, it is converted to an 775 // unsigned int. These are called the integer promotions. All 776 // other types are unchanged by the integer promotions. 777 778 QualType PTy = Context.isPromotableBitField(E); 779 if (!PTy.isNull()) { 780 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 781 return E; 782 } 783 if (Ty->isPromotableIntegerType()) { 784 QualType PT = Context.getPromotedIntegerType(Ty); 785 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 786 return E; 787 } 788 } 789 return E; 790 } 791 792 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 793 /// do not have a prototype. Arguments that have type float or __fp16 794 /// are promoted to double. All other argument types are converted by 795 /// UsualUnaryConversions(). 796 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 797 QualType Ty = E->getType(); 798 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 799 800 ExprResult Res = UsualUnaryConversions(E); 801 if (Res.isInvalid()) 802 return ExprError(); 803 E = Res.get(); 804 805 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 806 // promote to double. 807 // Note that default argument promotion applies only to float (and 808 // half/fp16); it does not apply to _Float16. 809 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 810 if (BTy && (BTy->getKind() == BuiltinType::Half || 811 BTy->getKind() == BuiltinType::Float)) { 812 if (getLangOpts().OpenCL && 813 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 814 if (BTy->getKind() == BuiltinType::Half) { 815 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 816 } 817 } else { 818 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 819 } 820 } 821 822 // C++ performs lvalue-to-rvalue conversion as a default argument 823 // promotion, even on class types, but note: 824 // C++11 [conv.lval]p2: 825 // When an lvalue-to-rvalue conversion occurs in an unevaluated 826 // operand or a subexpression thereof the value contained in the 827 // referenced object is not accessed. Otherwise, if the glvalue 828 // has a class type, the conversion copy-initializes a temporary 829 // of type T from the glvalue and the result of the conversion 830 // is a prvalue for the temporary. 831 // FIXME: add some way to gate this entire thing for correctness in 832 // potentially potentially evaluated contexts. 833 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 834 ExprResult Temp = PerformCopyInitialization( 835 InitializedEntity::InitializeTemporary(E->getType()), 836 E->getExprLoc(), E); 837 if (Temp.isInvalid()) 838 return ExprError(); 839 E = Temp.get(); 840 } 841 842 return E; 843 } 844 845 /// Determine the degree of POD-ness for an expression. 846 /// Incomplete types are considered POD, since this check can be performed 847 /// when we're in an unevaluated context. 848 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 849 if (Ty->isIncompleteType()) { 850 // C++11 [expr.call]p7: 851 // After these conversions, if the argument does not have arithmetic, 852 // enumeration, pointer, pointer to member, or class type, the program 853 // is ill-formed. 854 // 855 // Since we've already performed array-to-pointer and function-to-pointer 856 // decay, the only such type in C++ is cv void. This also handles 857 // initializer lists as variadic arguments. 858 if (Ty->isVoidType()) 859 return VAK_Invalid; 860 861 if (Ty->isObjCObjectType()) 862 return VAK_Invalid; 863 return VAK_Valid; 864 } 865 866 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 867 return VAK_Invalid; 868 869 if (Ty.isCXX98PODType(Context)) 870 return VAK_Valid; 871 872 // C++11 [expr.call]p7: 873 // Passing a potentially-evaluated argument of class type (Clause 9) 874 // having a non-trivial copy constructor, a non-trivial move constructor, 875 // or a non-trivial destructor, with no corresponding parameter, 876 // is conditionally-supported with implementation-defined semantics. 877 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 878 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 879 if (!Record->hasNonTrivialCopyConstructor() && 880 !Record->hasNonTrivialMoveConstructor() && 881 !Record->hasNonTrivialDestructor()) 882 return VAK_ValidInCXX11; 883 884 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 885 return VAK_Valid; 886 887 if (Ty->isObjCObjectType()) 888 return VAK_Invalid; 889 890 if (getLangOpts().MSVCCompat) 891 return VAK_MSVCUndefined; 892 893 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 894 // permitted to reject them. We should consider doing so. 895 return VAK_Undefined; 896 } 897 898 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 899 // Don't allow one to pass an Objective-C interface to a vararg. 900 const QualType &Ty = E->getType(); 901 VarArgKind VAK = isValidVarArgType(Ty); 902 903 // Complain about passing non-POD types through varargs. 904 switch (VAK) { 905 case VAK_ValidInCXX11: 906 DiagRuntimeBehavior( 907 E->getBeginLoc(), nullptr, 908 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 909 LLVM_FALLTHROUGH; 910 case VAK_Valid: 911 if (Ty->isRecordType()) { 912 // This is unlikely to be what the user intended. If the class has a 913 // 'c_str' member function, the user probably meant to call that. 914 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 915 PDiag(diag::warn_pass_class_arg_to_vararg) 916 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 917 } 918 break; 919 920 case VAK_Undefined: 921 case VAK_MSVCUndefined: 922 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 923 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 924 << getLangOpts().CPlusPlus11 << Ty << CT); 925 break; 926 927 case VAK_Invalid: 928 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 929 Diag(E->getBeginLoc(), 930 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 931 << Ty << CT; 932 else if (Ty->isObjCObjectType()) 933 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 934 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 935 << Ty << CT); 936 else 937 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 938 << isa<InitListExpr>(E) << Ty << CT; 939 break; 940 } 941 } 942 943 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 944 /// will create a trap if the resulting type is not a POD type. 945 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 946 FunctionDecl *FDecl) { 947 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 948 // Strip the unbridged-cast placeholder expression off, if applicable. 949 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 950 (CT == VariadicMethod || 951 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 952 E = stripARCUnbridgedCast(E); 953 954 // Otherwise, do normal placeholder checking. 955 } else { 956 ExprResult ExprRes = CheckPlaceholderExpr(E); 957 if (ExprRes.isInvalid()) 958 return ExprError(); 959 E = ExprRes.get(); 960 } 961 } 962 963 ExprResult ExprRes = DefaultArgumentPromotion(E); 964 if (ExprRes.isInvalid()) 965 return ExprError(); 966 967 // Copy blocks to the heap. 968 if (ExprRes.get()->getType()->isBlockPointerType()) 969 maybeExtendBlockObject(ExprRes); 970 971 E = ExprRes.get(); 972 973 // Diagnostics regarding non-POD argument types are 974 // emitted along with format string checking in Sema::CheckFunctionCall(). 975 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 976 // Turn this into a trap. 977 CXXScopeSpec SS; 978 SourceLocation TemplateKWLoc; 979 UnqualifiedId Name; 980 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 981 E->getBeginLoc()); 982 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 983 /*HasTrailingLParen=*/true, 984 /*IsAddressOfOperand=*/false); 985 if (TrapFn.isInvalid()) 986 return ExprError(); 987 988 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 989 None, E->getEndLoc()); 990 if (Call.isInvalid()) 991 return ExprError(); 992 993 ExprResult Comma = 994 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 995 if (Comma.isInvalid()) 996 return ExprError(); 997 return Comma.get(); 998 } 999 1000 if (!getLangOpts().CPlusPlus && 1001 RequireCompleteType(E->getExprLoc(), E->getType(), 1002 diag::err_call_incomplete_argument)) 1003 return ExprError(); 1004 1005 return E; 1006 } 1007 1008 /// Converts an integer to complex float type. Helper function of 1009 /// UsualArithmeticConversions() 1010 /// 1011 /// \return false if the integer expression is an integer type and is 1012 /// successfully converted to the complex type. 1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1014 ExprResult &ComplexExpr, 1015 QualType IntTy, 1016 QualType ComplexTy, 1017 bool SkipCast) { 1018 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1019 if (SkipCast) return false; 1020 if (IntTy->isIntegerType()) { 1021 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1022 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1024 CK_FloatingRealToComplex); 1025 } else { 1026 assert(IntTy->isComplexIntegerType()); 1027 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1028 CK_IntegralComplexToFloatingComplex); 1029 } 1030 return false; 1031 } 1032 1033 /// Handle arithmetic conversion with complex types. Helper function of 1034 /// UsualArithmeticConversions() 1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1036 ExprResult &RHS, QualType LHSType, 1037 QualType RHSType, 1038 bool IsCompAssign) { 1039 // if we have an integer operand, the result is the complex type. 1040 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1041 /*skipCast*/false)) 1042 return LHSType; 1043 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1044 /*skipCast*/IsCompAssign)) 1045 return RHSType; 1046 1047 // This handles complex/complex, complex/float, or float/complex. 1048 // When both operands are complex, the shorter operand is converted to the 1049 // type of the longer, and that is the type of the result. This corresponds 1050 // to what is done when combining two real floating-point operands. 1051 // The fun begins when size promotion occur across type domains. 1052 // From H&S 6.3.4: When one operand is complex and the other is a real 1053 // floating-point type, the less precise type is converted, within it's 1054 // real or complex domain, to the precision of the other type. For example, 1055 // when combining a "long double" with a "double _Complex", the 1056 // "double _Complex" is promoted to "long double _Complex". 1057 1058 // Compute the rank of the two types, regardless of whether they are complex. 1059 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1060 1061 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1062 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1063 QualType LHSElementType = 1064 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1065 QualType RHSElementType = 1066 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1067 1068 QualType ResultType = S.Context.getComplexType(LHSElementType); 1069 if (Order < 0) { 1070 // Promote the precision of the LHS if not an assignment. 1071 ResultType = S.Context.getComplexType(RHSElementType); 1072 if (!IsCompAssign) { 1073 if (LHSComplexType) 1074 LHS = 1075 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1076 else 1077 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1078 } 1079 } else if (Order > 0) { 1080 // Promote the precision of the RHS. 1081 if (RHSComplexType) 1082 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1083 else 1084 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1085 } 1086 return ResultType; 1087 } 1088 1089 /// Handle arithmetic conversion from integer to float. Helper function 1090 /// of UsualArithmeticConversions() 1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1092 ExprResult &IntExpr, 1093 QualType FloatTy, QualType IntTy, 1094 bool ConvertFloat, bool ConvertInt) { 1095 if (IntTy->isIntegerType()) { 1096 if (ConvertInt) 1097 // Convert intExpr to the lhs floating point type. 1098 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1099 CK_IntegralToFloating); 1100 return FloatTy; 1101 } 1102 1103 // Convert both sides to the appropriate complex float. 1104 assert(IntTy->isComplexIntegerType()); 1105 QualType result = S.Context.getComplexType(FloatTy); 1106 1107 // _Complex int -> _Complex float 1108 if (ConvertInt) 1109 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1110 CK_IntegralComplexToFloatingComplex); 1111 1112 // float -> _Complex float 1113 if (ConvertFloat) 1114 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1115 CK_FloatingRealToComplex); 1116 1117 return result; 1118 } 1119 1120 /// Handle arithmethic conversion with floating point types. Helper 1121 /// function of UsualArithmeticConversions() 1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1123 ExprResult &RHS, QualType LHSType, 1124 QualType RHSType, bool IsCompAssign) { 1125 bool LHSFloat = LHSType->isRealFloatingType(); 1126 bool RHSFloat = RHSType->isRealFloatingType(); 1127 1128 // FIXME: Implement floating to fixed point conversion.(Bug 46268) 1129 // Reference N1169 4.1.4 (Type conversion, usual arithmetic conversions). 1130 if ((LHSType->isFixedPointType() && RHSFloat) || 1131 (LHSFloat && RHSType->isFixedPointType())) 1132 return QualType(); 1133 // If we have two real floating types, convert the smaller operand 1134 // to the bigger result. 1135 if (LHSFloat && RHSFloat) { 1136 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1137 if (order > 0) { 1138 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1139 return LHSType; 1140 } 1141 1142 assert(order < 0 && "illegal float comparison"); 1143 if (!IsCompAssign) 1144 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1145 return RHSType; 1146 } 1147 1148 if (LHSFloat) { 1149 // Half FP has to be promoted to float unless it is natively supported 1150 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1151 LHSType = S.Context.FloatTy; 1152 1153 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1154 /*ConvertFloat=*/!IsCompAssign, 1155 /*ConvertInt=*/ true); 1156 } 1157 assert(RHSFloat); 1158 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1159 /*ConvertFloat=*/ true, 1160 /*ConvertInt=*/!IsCompAssign); 1161 } 1162 1163 /// Diagnose attempts to convert between __float128 and long double if 1164 /// there is no support for such conversion. Helper function of 1165 /// UsualArithmeticConversions(). 1166 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1167 QualType RHSType) { 1168 /* No issue converting if at least one of the types is not a floating point 1169 type or the two types have the same rank. 1170 */ 1171 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1172 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1173 return false; 1174 1175 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1176 "The remaining types must be floating point types."); 1177 1178 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1179 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1180 1181 QualType LHSElemType = LHSComplex ? 1182 LHSComplex->getElementType() : LHSType; 1183 QualType RHSElemType = RHSComplex ? 1184 RHSComplex->getElementType() : RHSType; 1185 1186 // No issue if the two types have the same representation 1187 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1188 &S.Context.getFloatTypeSemantics(RHSElemType)) 1189 return false; 1190 1191 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1192 RHSElemType == S.Context.LongDoubleTy); 1193 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1194 RHSElemType == S.Context.Float128Ty); 1195 1196 // We've handled the situation where __float128 and long double have the same 1197 // representation. We allow all conversions for all possible long double types 1198 // except PPC's double double. 1199 return Float128AndLongDouble && 1200 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1201 &llvm::APFloat::PPCDoubleDouble()); 1202 } 1203 1204 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1205 1206 namespace { 1207 /// These helper callbacks are placed in an anonymous namespace to 1208 /// permit their use as function template parameters. 1209 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1210 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1211 } 1212 1213 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1214 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1215 CK_IntegralComplexCast); 1216 } 1217 } 1218 1219 /// Handle integer arithmetic conversions. Helper function of 1220 /// UsualArithmeticConversions() 1221 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1222 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1223 ExprResult &RHS, QualType LHSType, 1224 QualType RHSType, bool IsCompAssign) { 1225 // The rules for this case are in C99 6.3.1.8 1226 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1227 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1228 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1229 if (LHSSigned == RHSSigned) { 1230 // Same signedness; use the higher-ranked type 1231 if (order >= 0) { 1232 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1233 return LHSType; 1234 } else if (!IsCompAssign) 1235 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1236 return RHSType; 1237 } else if (order != (LHSSigned ? 1 : -1)) { 1238 // The unsigned type has greater than or equal rank to the 1239 // signed type, so use the unsigned type 1240 if (RHSSigned) { 1241 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1242 return LHSType; 1243 } else if (!IsCompAssign) 1244 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1245 return RHSType; 1246 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1247 // The two types are different widths; if we are here, that 1248 // means the signed type is larger than the unsigned type, so 1249 // use the signed type. 1250 if (LHSSigned) { 1251 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1252 return LHSType; 1253 } else if (!IsCompAssign) 1254 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1255 return RHSType; 1256 } else { 1257 // The signed type is higher-ranked than the unsigned type, 1258 // but isn't actually any bigger (like unsigned int and long 1259 // on most 32-bit systems). Use the unsigned type corresponding 1260 // to the signed type. 1261 QualType result = 1262 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1263 RHS = (*doRHSCast)(S, RHS.get(), result); 1264 if (!IsCompAssign) 1265 LHS = (*doLHSCast)(S, LHS.get(), result); 1266 return result; 1267 } 1268 } 1269 1270 /// Handle conversions with GCC complex int extension. Helper function 1271 /// of UsualArithmeticConversions() 1272 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1273 ExprResult &RHS, QualType LHSType, 1274 QualType RHSType, 1275 bool IsCompAssign) { 1276 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1277 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1278 1279 if (LHSComplexInt && RHSComplexInt) { 1280 QualType LHSEltType = LHSComplexInt->getElementType(); 1281 QualType RHSEltType = RHSComplexInt->getElementType(); 1282 QualType ScalarType = 1283 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1284 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1285 1286 return S.Context.getComplexType(ScalarType); 1287 } 1288 1289 if (LHSComplexInt) { 1290 QualType LHSEltType = LHSComplexInt->getElementType(); 1291 QualType ScalarType = 1292 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1293 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1294 QualType ComplexType = S.Context.getComplexType(ScalarType); 1295 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1296 CK_IntegralRealToComplex); 1297 1298 return ComplexType; 1299 } 1300 1301 assert(RHSComplexInt); 1302 1303 QualType RHSEltType = RHSComplexInt->getElementType(); 1304 QualType ScalarType = 1305 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1306 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1307 QualType ComplexType = S.Context.getComplexType(ScalarType); 1308 1309 if (!IsCompAssign) 1310 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1311 CK_IntegralRealToComplex); 1312 return ComplexType; 1313 } 1314 1315 /// Return the rank of a given fixed point or integer type. The value itself 1316 /// doesn't matter, but the values must be increasing with proper increasing 1317 /// rank as described in N1169 4.1.1. 1318 static unsigned GetFixedPointRank(QualType Ty) { 1319 const auto *BTy = Ty->getAs<BuiltinType>(); 1320 assert(BTy && "Expected a builtin type."); 1321 1322 switch (BTy->getKind()) { 1323 case BuiltinType::ShortFract: 1324 case BuiltinType::UShortFract: 1325 case BuiltinType::SatShortFract: 1326 case BuiltinType::SatUShortFract: 1327 return 1; 1328 case BuiltinType::Fract: 1329 case BuiltinType::UFract: 1330 case BuiltinType::SatFract: 1331 case BuiltinType::SatUFract: 1332 return 2; 1333 case BuiltinType::LongFract: 1334 case BuiltinType::ULongFract: 1335 case BuiltinType::SatLongFract: 1336 case BuiltinType::SatULongFract: 1337 return 3; 1338 case BuiltinType::ShortAccum: 1339 case BuiltinType::UShortAccum: 1340 case BuiltinType::SatShortAccum: 1341 case BuiltinType::SatUShortAccum: 1342 return 4; 1343 case BuiltinType::Accum: 1344 case BuiltinType::UAccum: 1345 case BuiltinType::SatAccum: 1346 case BuiltinType::SatUAccum: 1347 return 5; 1348 case BuiltinType::LongAccum: 1349 case BuiltinType::ULongAccum: 1350 case BuiltinType::SatLongAccum: 1351 case BuiltinType::SatULongAccum: 1352 return 6; 1353 default: 1354 if (BTy->isInteger()) 1355 return 0; 1356 llvm_unreachable("Unexpected fixed point or integer type"); 1357 } 1358 } 1359 1360 /// handleFixedPointConversion - Fixed point operations between fixed 1361 /// point types and integers or other fixed point types do not fall under 1362 /// usual arithmetic conversion since these conversions could result in loss 1363 /// of precsision (N1169 4.1.4). These operations should be calculated with 1364 /// the full precision of their result type (N1169 4.1.6.2.1). 1365 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1366 QualType RHSTy) { 1367 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1368 "Expected at least one of the operands to be a fixed point type"); 1369 assert((LHSTy->isFixedPointOrIntegerType() || 1370 RHSTy->isFixedPointOrIntegerType()) && 1371 "Special fixed point arithmetic operation conversions are only " 1372 "applied to ints or other fixed point types"); 1373 1374 // If one operand has signed fixed-point type and the other operand has 1375 // unsigned fixed-point type, then the unsigned fixed-point operand is 1376 // converted to its corresponding signed fixed-point type and the resulting 1377 // type is the type of the converted operand. 1378 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1379 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1380 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1381 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1382 1383 // The result type is the type with the highest rank, whereby a fixed-point 1384 // conversion rank is always greater than an integer conversion rank; if the 1385 // type of either of the operands is a saturating fixedpoint type, the result 1386 // type shall be the saturating fixed-point type corresponding to the type 1387 // with the highest rank; the resulting value is converted (taking into 1388 // account rounding and overflow) to the precision of the resulting type. 1389 // Same ranks between signed and unsigned types are resolved earlier, so both 1390 // types are either signed or both unsigned at this point. 1391 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1392 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1393 1394 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1395 1396 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1397 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1398 1399 return ResultTy; 1400 } 1401 1402 /// Check that the usual arithmetic conversions can be performed on this pair of 1403 /// expressions that might be of enumeration type. 1404 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1405 SourceLocation Loc, 1406 Sema::ArithConvKind ACK) { 1407 // C++2a [expr.arith.conv]p1: 1408 // If one operand is of enumeration type and the other operand is of a 1409 // different enumeration type or a floating-point type, this behavior is 1410 // deprecated ([depr.arith.conv.enum]). 1411 // 1412 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1413 // Eventually we will presumably reject these cases (in C++23 onwards?). 1414 QualType L = LHS->getType(), R = RHS->getType(); 1415 bool LEnum = L->isUnscopedEnumerationType(), 1416 REnum = R->isUnscopedEnumerationType(); 1417 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1418 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1419 (REnum && L->isFloatingType())) { 1420 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1421 ? diag::warn_arith_conv_enum_float_cxx20 1422 : diag::warn_arith_conv_enum_float) 1423 << LHS->getSourceRange() << RHS->getSourceRange() 1424 << (int)ACK << LEnum << L << R; 1425 } else if (!IsCompAssign && LEnum && REnum && 1426 !S.Context.hasSameUnqualifiedType(L, R)) { 1427 unsigned DiagID; 1428 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1429 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1430 // If either enumeration type is unnamed, it's less likely that the 1431 // user cares about this, but this situation is still deprecated in 1432 // C++2a. Use a different warning group. 1433 DiagID = S.getLangOpts().CPlusPlus20 1434 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1435 : diag::warn_arith_conv_mixed_anon_enum_types; 1436 } else if (ACK == Sema::ACK_Conditional) { 1437 // Conditional expressions are separated out because they have 1438 // historically had a different warning flag. 1439 DiagID = S.getLangOpts().CPlusPlus20 1440 ? diag::warn_conditional_mixed_enum_types_cxx20 1441 : diag::warn_conditional_mixed_enum_types; 1442 } else if (ACK == Sema::ACK_Comparison) { 1443 // Comparison expressions are separated out because they have 1444 // historically had a different warning flag. 1445 DiagID = S.getLangOpts().CPlusPlus20 1446 ? diag::warn_comparison_mixed_enum_types_cxx20 1447 : diag::warn_comparison_mixed_enum_types; 1448 } else { 1449 DiagID = S.getLangOpts().CPlusPlus20 1450 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1451 : diag::warn_arith_conv_mixed_enum_types; 1452 } 1453 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1454 << (int)ACK << L << R; 1455 } 1456 } 1457 1458 /// UsualArithmeticConversions - Performs various conversions that are common to 1459 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1460 /// routine returns the first non-arithmetic type found. The client is 1461 /// responsible for emitting appropriate error diagnostics. 1462 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1463 SourceLocation Loc, 1464 ArithConvKind ACK) { 1465 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1466 1467 if (ACK != ACK_CompAssign) { 1468 LHS = UsualUnaryConversions(LHS.get()); 1469 if (LHS.isInvalid()) 1470 return QualType(); 1471 } 1472 1473 RHS = UsualUnaryConversions(RHS.get()); 1474 if (RHS.isInvalid()) 1475 return QualType(); 1476 1477 // For conversion purposes, we ignore any qualifiers. 1478 // For example, "const float" and "float" are equivalent. 1479 QualType LHSType = 1480 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1481 QualType RHSType = 1482 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1483 1484 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1485 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1486 LHSType = AtomicLHS->getValueType(); 1487 1488 // If both types are identical, no conversion is needed. 1489 if (LHSType == RHSType) 1490 return LHSType; 1491 1492 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1493 // The caller can deal with this (e.g. pointer + int). 1494 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1495 return QualType(); 1496 1497 // Apply unary and bitfield promotions to the LHS's type. 1498 QualType LHSUnpromotedType = LHSType; 1499 if (LHSType->isPromotableIntegerType()) 1500 LHSType = Context.getPromotedIntegerType(LHSType); 1501 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1502 if (!LHSBitfieldPromoteTy.isNull()) 1503 LHSType = LHSBitfieldPromoteTy; 1504 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1505 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1506 1507 // If both types are identical, no conversion is needed. 1508 if (LHSType == RHSType) 1509 return LHSType; 1510 1511 // ExtInt types aren't subject to conversions between them or normal integers, 1512 // so this fails. 1513 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1514 return QualType(); 1515 1516 // At this point, we have two different arithmetic types. 1517 1518 // Diagnose attempts to convert between __float128 and long double where 1519 // such conversions currently can't be handled. 1520 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1521 return QualType(); 1522 1523 // Handle complex types first (C99 6.3.1.8p1). 1524 if (LHSType->isComplexType() || RHSType->isComplexType()) 1525 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1526 ACK == ACK_CompAssign); 1527 1528 // Now handle "real" floating types (i.e. float, double, long double). 1529 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1530 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1531 ACK == ACK_CompAssign); 1532 1533 // Handle GCC complex int extension. 1534 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1535 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1536 ACK == ACK_CompAssign); 1537 1538 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1539 return handleFixedPointConversion(*this, LHSType, RHSType); 1540 1541 // Finally, we have two differing integer types. 1542 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1543 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1544 } 1545 1546 //===----------------------------------------------------------------------===// 1547 // Semantic Analysis for various Expression Types 1548 //===----------------------------------------------------------------------===// 1549 1550 1551 ExprResult 1552 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1553 SourceLocation DefaultLoc, 1554 SourceLocation RParenLoc, 1555 Expr *ControllingExpr, 1556 ArrayRef<ParsedType> ArgTypes, 1557 ArrayRef<Expr *> ArgExprs) { 1558 unsigned NumAssocs = ArgTypes.size(); 1559 assert(NumAssocs == ArgExprs.size()); 1560 1561 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1562 for (unsigned i = 0; i < NumAssocs; ++i) { 1563 if (ArgTypes[i]) 1564 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1565 else 1566 Types[i] = nullptr; 1567 } 1568 1569 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1570 ControllingExpr, 1571 llvm::makeArrayRef(Types, NumAssocs), 1572 ArgExprs); 1573 delete [] Types; 1574 return ER; 1575 } 1576 1577 ExprResult 1578 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1579 SourceLocation DefaultLoc, 1580 SourceLocation RParenLoc, 1581 Expr *ControllingExpr, 1582 ArrayRef<TypeSourceInfo *> Types, 1583 ArrayRef<Expr *> Exprs) { 1584 unsigned NumAssocs = Types.size(); 1585 assert(NumAssocs == Exprs.size()); 1586 1587 // Decay and strip qualifiers for the controlling expression type, and handle 1588 // placeholder type replacement. See committee discussion from WG14 DR423. 1589 { 1590 EnterExpressionEvaluationContext Unevaluated( 1591 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1592 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1593 if (R.isInvalid()) 1594 return ExprError(); 1595 ControllingExpr = R.get(); 1596 } 1597 1598 // The controlling expression is an unevaluated operand, so side effects are 1599 // likely unintended. 1600 if (!inTemplateInstantiation() && 1601 ControllingExpr->HasSideEffects(Context, false)) 1602 Diag(ControllingExpr->getExprLoc(), 1603 diag::warn_side_effects_unevaluated_context); 1604 1605 bool TypeErrorFound = false, 1606 IsResultDependent = ControllingExpr->isTypeDependent(), 1607 ContainsUnexpandedParameterPack 1608 = ControllingExpr->containsUnexpandedParameterPack(); 1609 1610 for (unsigned i = 0; i < NumAssocs; ++i) { 1611 if (Exprs[i]->containsUnexpandedParameterPack()) 1612 ContainsUnexpandedParameterPack = true; 1613 1614 if (Types[i]) { 1615 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1616 ContainsUnexpandedParameterPack = true; 1617 1618 if (Types[i]->getType()->isDependentType()) { 1619 IsResultDependent = true; 1620 } else { 1621 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1622 // complete object type other than a variably modified type." 1623 unsigned D = 0; 1624 if (Types[i]->getType()->isIncompleteType()) 1625 D = diag::err_assoc_type_incomplete; 1626 else if (!Types[i]->getType()->isObjectType()) 1627 D = diag::err_assoc_type_nonobject; 1628 else if (Types[i]->getType()->isVariablyModifiedType()) 1629 D = diag::err_assoc_type_variably_modified; 1630 1631 if (D != 0) { 1632 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1633 << Types[i]->getTypeLoc().getSourceRange() 1634 << Types[i]->getType(); 1635 TypeErrorFound = true; 1636 } 1637 1638 // C11 6.5.1.1p2 "No two generic associations in the same generic 1639 // selection shall specify compatible types." 1640 for (unsigned j = i+1; j < NumAssocs; ++j) 1641 if (Types[j] && !Types[j]->getType()->isDependentType() && 1642 Context.typesAreCompatible(Types[i]->getType(), 1643 Types[j]->getType())) { 1644 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1645 diag::err_assoc_compatible_types) 1646 << Types[j]->getTypeLoc().getSourceRange() 1647 << Types[j]->getType() 1648 << Types[i]->getType(); 1649 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1650 diag::note_compat_assoc) 1651 << Types[i]->getTypeLoc().getSourceRange() 1652 << Types[i]->getType(); 1653 TypeErrorFound = true; 1654 } 1655 } 1656 } 1657 } 1658 if (TypeErrorFound) 1659 return ExprError(); 1660 1661 // If we determined that the generic selection is result-dependent, don't 1662 // try to compute the result expression. 1663 if (IsResultDependent) 1664 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1665 Exprs, DefaultLoc, RParenLoc, 1666 ContainsUnexpandedParameterPack); 1667 1668 SmallVector<unsigned, 1> CompatIndices; 1669 unsigned DefaultIndex = -1U; 1670 for (unsigned i = 0; i < NumAssocs; ++i) { 1671 if (!Types[i]) 1672 DefaultIndex = i; 1673 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1674 Types[i]->getType())) 1675 CompatIndices.push_back(i); 1676 } 1677 1678 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1679 // type compatible with at most one of the types named in its generic 1680 // association list." 1681 if (CompatIndices.size() > 1) { 1682 // We strip parens here because the controlling expression is typically 1683 // parenthesized in macro definitions. 1684 ControllingExpr = ControllingExpr->IgnoreParens(); 1685 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1686 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1687 << (unsigned)CompatIndices.size(); 1688 for (unsigned I : CompatIndices) { 1689 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1690 diag::note_compat_assoc) 1691 << Types[I]->getTypeLoc().getSourceRange() 1692 << Types[I]->getType(); 1693 } 1694 return ExprError(); 1695 } 1696 1697 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1698 // its controlling expression shall have type compatible with exactly one of 1699 // the types named in its generic association list." 1700 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1701 // We strip parens here because the controlling expression is typically 1702 // parenthesized in macro definitions. 1703 ControllingExpr = ControllingExpr->IgnoreParens(); 1704 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1705 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1706 return ExprError(); 1707 } 1708 1709 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1710 // type name that is compatible with the type of the controlling expression, 1711 // then the result expression of the generic selection is the expression 1712 // in that generic association. Otherwise, the result expression of the 1713 // generic selection is the expression in the default generic association." 1714 unsigned ResultIndex = 1715 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1716 1717 return GenericSelectionExpr::Create( 1718 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1719 ContainsUnexpandedParameterPack, ResultIndex); 1720 } 1721 1722 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1723 /// location of the token and the offset of the ud-suffix within it. 1724 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1725 unsigned Offset) { 1726 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1727 S.getLangOpts()); 1728 } 1729 1730 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1731 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1732 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1733 IdentifierInfo *UDSuffix, 1734 SourceLocation UDSuffixLoc, 1735 ArrayRef<Expr*> Args, 1736 SourceLocation LitEndLoc) { 1737 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1738 1739 QualType ArgTy[2]; 1740 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1741 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1742 if (ArgTy[ArgIdx]->isArrayType()) 1743 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1744 } 1745 1746 DeclarationName OpName = 1747 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1748 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1749 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1750 1751 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1752 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1753 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1754 /*AllowStringTemplate*/ false, 1755 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1756 return ExprError(); 1757 1758 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1759 } 1760 1761 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1762 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1763 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1764 /// multiple tokens. However, the common case is that StringToks points to one 1765 /// string. 1766 /// 1767 ExprResult 1768 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1769 assert(!StringToks.empty() && "Must have at least one string!"); 1770 1771 StringLiteralParser Literal(StringToks, PP); 1772 if (Literal.hadError) 1773 return ExprError(); 1774 1775 SmallVector<SourceLocation, 4> StringTokLocs; 1776 for (const Token &Tok : StringToks) 1777 StringTokLocs.push_back(Tok.getLocation()); 1778 1779 QualType CharTy = Context.CharTy; 1780 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1781 if (Literal.isWide()) { 1782 CharTy = Context.getWideCharType(); 1783 Kind = StringLiteral::Wide; 1784 } else if (Literal.isUTF8()) { 1785 if (getLangOpts().Char8) 1786 CharTy = Context.Char8Ty; 1787 Kind = StringLiteral::UTF8; 1788 } else if (Literal.isUTF16()) { 1789 CharTy = Context.Char16Ty; 1790 Kind = StringLiteral::UTF16; 1791 } else if (Literal.isUTF32()) { 1792 CharTy = Context.Char32Ty; 1793 Kind = StringLiteral::UTF32; 1794 } else if (Literal.isPascal()) { 1795 CharTy = Context.UnsignedCharTy; 1796 } 1797 1798 // Warn on initializing an array of char from a u8 string literal; this 1799 // becomes ill-formed in C++2a. 1800 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1801 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1802 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1803 1804 // Create removals for all 'u8' prefixes in the string literal(s). This 1805 // ensures C++2a compatibility (but may change the program behavior when 1806 // built by non-Clang compilers for which the execution character set is 1807 // not always UTF-8). 1808 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1809 SourceLocation RemovalDiagLoc; 1810 for (const Token &Tok : StringToks) { 1811 if (Tok.getKind() == tok::utf8_string_literal) { 1812 if (RemovalDiagLoc.isInvalid()) 1813 RemovalDiagLoc = Tok.getLocation(); 1814 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1815 Tok.getLocation(), 1816 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1817 getSourceManager(), getLangOpts()))); 1818 } 1819 } 1820 Diag(RemovalDiagLoc, RemovalDiag); 1821 } 1822 1823 QualType StrTy = 1824 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1825 1826 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1827 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1828 Kind, Literal.Pascal, StrTy, 1829 &StringTokLocs[0], 1830 StringTokLocs.size()); 1831 if (Literal.getUDSuffix().empty()) 1832 return Lit; 1833 1834 // We're building a user-defined literal. 1835 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1836 SourceLocation UDSuffixLoc = 1837 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1838 Literal.getUDSuffixOffset()); 1839 1840 // Make sure we're allowed user-defined literals here. 1841 if (!UDLScope) 1842 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1843 1844 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1845 // operator "" X (str, len) 1846 QualType SizeType = Context.getSizeType(); 1847 1848 DeclarationName OpName = 1849 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1850 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1851 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1852 1853 QualType ArgTy[] = { 1854 Context.getArrayDecayedType(StrTy), SizeType 1855 }; 1856 1857 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1858 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1859 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1860 /*AllowStringTemplate*/ true, 1861 /*DiagnoseMissing*/ true)) { 1862 1863 case LOLR_Cooked: { 1864 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1865 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1866 StringTokLocs[0]); 1867 Expr *Args[] = { Lit, LenArg }; 1868 1869 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1870 } 1871 1872 case LOLR_StringTemplate: { 1873 TemplateArgumentListInfo ExplicitArgs; 1874 1875 unsigned CharBits = Context.getIntWidth(CharTy); 1876 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1877 llvm::APSInt Value(CharBits, CharIsUnsigned); 1878 1879 TemplateArgument TypeArg(CharTy); 1880 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1881 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1882 1883 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1884 Value = Lit->getCodeUnit(I); 1885 TemplateArgument Arg(Context, Value, CharTy); 1886 TemplateArgumentLocInfo ArgInfo; 1887 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1888 } 1889 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1890 &ExplicitArgs); 1891 } 1892 case LOLR_Raw: 1893 case LOLR_Template: 1894 case LOLR_ErrorNoDiagnostic: 1895 llvm_unreachable("unexpected literal operator lookup result"); 1896 case LOLR_Error: 1897 return ExprError(); 1898 } 1899 llvm_unreachable("unexpected literal operator lookup result"); 1900 } 1901 1902 DeclRefExpr * 1903 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1904 SourceLocation Loc, 1905 const CXXScopeSpec *SS) { 1906 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1907 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1908 } 1909 1910 DeclRefExpr * 1911 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1912 const DeclarationNameInfo &NameInfo, 1913 const CXXScopeSpec *SS, NamedDecl *FoundD, 1914 SourceLocation TemplateKWLoc, 1915 const TemplateArgumentListInfo *TemplateArgs) { 1916 NestedNameSpecifierLoc NNS = 1917 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1918 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1919 TemplateArgs); 1920 } 1921 1922 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1923 // A declaration named in an unevaluated operand never constitutes an odr-use. 1924 if (isUnevaluatedContext()) 1925 return NOUR_Unevaluated; 1926 1927 // C++2a [basic.def.odr]p4: 1928 // A variable x whose name appears as a potentially-evaluated expression e 1929 // is odr-used by e unless [...] x is a reference that is usable in 1930 // constant expressions. 1931 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1932 if (VD->getType()->isReferenceType() && 1933 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1934 VD->isUsableInConstantExpressions(Context)) 1935 return NOUR_Constant; 1936 } 1937 1938 // All remaining non-variable cases constitute an odr-use. For variables, we 1939 // need to wait and see how the expression is used. 1940 return NOUR_None; 1941 } 1942 1943 /// BuildDeclRefExpr - Build an expression that references a 1944 /// declaration that does not require a closure capture. 1945 DeclRefExpr * 1946 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1947 const DeclarationNameInfo &NameInfo, 1948 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1949 SourceLocation TemplateKWLoc, 1950 const TemplateArgumentListInfo *TemplateArgs) { 1951 bool RefersToCapturedVariable = 1952 isa<VarDecl>(D) && 1953 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1954 1955 DeclRefExpr *E = DeclRefExpr::Create( 1956 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1957 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1958 MarkDeclRefReferenced(E); 1959 1960 // C++ [except.spec]p17: 1961 // An exception-specification is considered to be needed when: 1962 // - in an expression, the function is the unique lookup result or 1963 // the selected member of a set of overloaded functions. 1964 // 1965 // We delay doing this until after we've built the function reference and 1966 // marked it as used so that: 1967 // a) if the function is defaulted, we get errors from defining it before / 1968 // instead of errors from computing its exception specification, and 1969 // b) if the function is a defaulted comparison, we can use the body we 1970 // build when defining it as input to the exception specification 1971 // computation rather than computing a new body. 1972 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1973 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1974 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1975 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1976 } 1977 } 1978 1979 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1980 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1981 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1982 getCurFunction()->recordUseOfWeak(E); 1983 1984 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1985 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1986 FD = IFD->getAnonField(); 1987 if (FD) { 1988 UnusedPrivateFields.remove(FD); 1989 // Just in case we're building an illegal pointer-to-member. 1990 if (FD->isBitField()) 1991 E->setObjectKind(OK_BitField); 1992 } 1993 1994 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1995 // designates a bit-field. 1996 if (auto *BD = dyn_cast<BindingDecl>(D)) 1997 if (auto *BE = BD->getBinding()) 1998 E->setObjectKind(BE->getObjectKind()); 1999 2000 return E; 2001 } 2002 2003 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2004 /// possibly a list of template arguments. 2005 /// 2006 /// If this produces template arguments, it is permitted to call 2007 /// DecomposeTemplateName. 2008 /// 2009 /// This actually loses a lot of source location information for 2010 /// non-standard name kinds; we should consider preserving that in 2011 /// some way. 2012 void 2013 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2014 TemplateArgumentListInfo &Buffer, 2015 DeclarationNameInfo &NameInfo, 2016 const TemplateArgumentListInfo *&TemplateArgs) { 2017 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2018 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2019 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2020 2021 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2022 Id.TemplateId->NumArgs); 2023 translateTemplateArguments(TemplateArgsPtr, Buffer); 2024 2025 TemplateName TName = Id.TemplateId->Template.get(); 2026 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2027 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2028 TemplateArgs = &Buffer; 2029 } else { 2030 NameInfo = GetNameFromUnqualifiedId(Id); 2031 TemplateArgs = nullptr; 2032 } 2033 } 2034 2035 static void emitEmptyLookupTypoDiagnostic( 2036 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2037 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2038 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2039 DeclContext *Ctx = 2040 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2041 if (!TC) { 2042 // Emit a special diagnostic for failed member lookups. 2043 // FIXME: computing the declaration context might fail here (?) 2044 if (Ctx) 2045 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2046 << SS.getRange(); 2047 else 2048 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2049 return; 2050 } 2051 2052 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2053 bool DroppedSpecifier = 2054 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2055 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2056 ? diag::note_implicit_param_decl 2057 : diag::note_previous_decl; 2058 if (!Ctx) 2059 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2060 SemaRef.PDiag(NoteID)); 2061 else 2062 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2063 << Typo << Ctx << DroppedSpecifier 2064 << SS.getRange(), 2065 SemaRef.PDiag(NoteID)); 2066 } 2067 2068 /// Diagnose an empty lookup. 2069 /// 2070 /// \return false if new lookup candidates were found 2071 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2072 CorrectionCandidateCallback &CCC, 2073 TemplateArgumentListInfo *ExplicitTemplateArgs, 2074 ArrayRef<Expr *> Args, TypoExpr **Out) { 2075 DeclarationName Name = R.getLookupName(); 2076 2077 unsigned diagnostic = diag::err_undeclared_var_use; 2078 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2079 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2080 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2081 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2082 diagnostic = diag::err_undeclared_use; 2083 diagnostic_suggest = diag::err_undeclared_use_suggest; 2084 } 2085 2086 // If the original lookup was an unqualified lookup, fake an 2087 // unqualified lookup. This is useful when (for example) the 2088 // original lookup would not have found something because it was a 2089 // dependent name. 2090 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2091 while (DC) { 2092 if (isa<CXXRecordDecl>(DC)) { 2093 LookupQualifiedName(R, DC); 2094 2095 if (!R.empty()) { 2096 // Don't give errors about ambiguities in this lookup. 2097 R.suppressDiagnostics(); 2098 2099 // During a default argument instantiation the CurContext points 2100 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2101 // function parameter list, hence add an explicit check. 2102 bool isDefaultArgument = 2103 !CodeSynthesisContexts.empty() && 2104 CodeSynthesisContexts.back().Kind == 2105 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2106 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2107 bool isInstance = CurMethod && 2108 CurMethod->isInstance() && 2109 DC == CurMethod->getParent() && !isDefaultArgument; 2110 2111 // Give a code modification hint to insert 'this->'. 2112 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2113 // Actually quite difficult! 2114 if (getLangOpts().MSVCCompat) 2115 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2116 if (isInstance) { 2117 Diag(R.getNameLoc(), diagnostic) << Name 2118 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2119 CheckCXXThisCapture(R.getNameLoc()); 2120 } else { 2121 Diag(R.getNameLoc(), diagnostic) << Name; 2122 } 2123 2124 // Do we really want to note all of these? 2125 for (NamedDecl *D : R) 2126 Diag(D->getLocation(), diag::note_dependent_var_use); 2127 2128 // Return true if we are inside a default argument instantiation 2129 // and the found name refers to an instance member function, otherwise 2130 // the function calling DiagnoseEmptyLookup will try to create an 2131 // implicit member call and this is wrong for default argument. 2132 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2133 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2134 return true; 2135 } 2136 2137 // Tell the callee to try to recover. 2138 return false; 2139 } 2140 2141 R.clear(); 2142 } 2143 2144 DC = DC->getLookupParent(); 2145 } 2146 2147 // We didn't find anything, so try to correct for a typo. 2148 TypoCorrection Corrected; 2149 if (S && Out) { 2150 SourceLocation TypoLoc = R.getNameLoc(); 2151 assert(!ExplicitTemplateArgs && 2152 "Diagnosing an empty lookup with explicit template args!"); 2153 *Out = CorrectTypoDelayed( 2154 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2155 [=](const TypoCorrection &TC) { 2156 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2157 diagnostic, diagnostic_suggest); 2158 }, 2159 nullptr, CTK_ErrorRecovery); 2160 if (*Out) 2161 return true; 2162 } else if (S && 2163 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2164 S, &SS, CCC, CTK_ErrorRecovery))) { 2165 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2166 bool DroppedSpecifier = 2167 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2168 R.setLookupName(Corrected.getCorrection()); 2169 2170 bool AcceptableWithRecovery = false; 2171 bool AcceptableWithoutRecovery = false; 2172 NamedDecl *ND = Corrected.getFoundDecl(); 2173 if (ND) { 2174 if (Corrected.isOverloaded()) { 2175 OverloadCandidateSet OCS(R.getNameLoc(), 2176 OverloadCandidateSet::CSK_Normal); 2177 OverloadCandidateSet::iterator Best; 2178 for (NamedDecl *CD : Corrected) { 2179 if (FunctionTemplateDecl *FTD = 2180 dyn_cast<FunctionTemplateDecl>(CD)) 2181 AddTemplateOverloadCandidate( 2182 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2183 Args, OCS); 2184 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2185 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2186 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2187 Args, OCS); 2188 } 2189 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2190 case OR_Success: 2191 ND = Best->FoundDecl; 2192 Corrected.setCorrectionDecl(ND); 2193 break; 2194 default: 2195 // FIXME: Arbitrarily pick the first declaration for the note. 2196 Corrected.setCorrectionDecl(ND); 2197 break; 2198 } 2199 } 2200 R.addDecl(ND); 2201 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2202 CXXRecordDecl *Record = nullptr; 2203 if (Corrected.getCorrectionSpecifier()) { 2204 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2205 Record = Ty->getAsCXXRecordDecl(); 2206 } 2207 if (!Record) 2208 Record = cast<CXXRecordDecl>( 2209 ND->getDeclContext()->getRedeclContext()); 2210 R.setNamingClass(Record); 2211 } 2212 2213 auto *UnderlyingND = ND->getUnderlyingDecl(); 2214 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2215 isa<FunctionTemplateDecl>(UnderlyingND); 2216 // FIXME: If we ended up with a typo for a type name or 2217 // Objective-C class name, we're in trouble because the parser 2218 // is in the wrong place to recover. Suggest the typo 2219 // correction, but don't make it a fix-it since we're not going 2220 // to recover well anyway. 2221 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2222 getAsTypeTemplateDecl(UnderlyingND) || 2223 isa<ObjCInterfaceDecl>(UnderlyingND); 2224 } else { 2225 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2226 // because we aren't able to recover. 2227 AcceptableWithoutRecovery = true; 2228 } 2229 2230 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2231 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2232 ? diag::note_implicit_param_decl 2233 : diag::note_previous_decl; 2234 if (SS.isEmpty()) 2235 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2236 PDiag(NoteID), AcceptableWithRecovery); 2237 else 2238 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2239 << Name << computeDeclContext(SS, false) 2240 << DroppedSpecifier << SS.getRange(), 2241 PDiag(NoteID), AcceptableWithRecovery); 2242 2243 // Tell the callee whether to try to recover. 2244 return !AcceptableWithRecovery; 2245 } 2246 } 2247 R.clear(); 2248 2249 // Emit a special diagnostic for failed member lookups. 2250 // FIXME: computing the declaration context might fail here (?) 2251 if (!SS.isEmpty()) { 2252 Diag(R.getNameLoc(), diag::err_no_member) 2253 << Name << computeDeclContext(SS, false) 2254 << SS.getRange(); 2255 return true; 2256 } 2257 2258 // Give up, we can't recover. 2259 Diag(R.getNameLoc(), diagnostic) << Name; 2260 return true; 2261 } 2262 2263 /// In Microsoft mode, if we are inside a template class whose parent class has 2264 /// dependent base classes, and we can't resolve an unqualified identifier, then 2265 /// assume the identifier is a member of a dependent base class. We can only 2266 /// recover successfully in static methods, instance methods, and other contexts 2267 /// where 'this' is available. This doesn't precisely match MSVC's 2268 /// instantiation model, but it's close enough. 2269 static Expr * 2270 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2271 DeclarationNameInfo &NameInfo, 2272 SourceLocation TemplateKWLoc, 2273 const TemplateArgumentListInfo *TemplateArgs) { 2274 // Only try to recover from lookup into dependent bases in static methods or 2275 // contexts where 'this' is available. 2276 QualType ThisType = S.getCurrentThisType(); 2277 const CXXRecordDecl *RD = nullptr; 2278 if (!ThisType.isNull()) 2279 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2280 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2281 RD = MD->getParent(); 2282 if (!RD || !RD->hasAnyDependentBases()) 2283 return nullptr; 2284 2285 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2286 // is available, suggest inserting 'this->' as a fixit. 2287 SourceLocation Loc = NameInfo.getLoc(); 2288 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2289 DB << NameInfo.getName() << RD; 2290 2291 if (!ThisType.isNull()) { 2292 DB << FixItHint::CreateInsertion(Loc, "this->"); 2293 return CXXDependentScopeMemberExpr::Create( 2294 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2295 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2296 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2297 } 2298 2299 // Synthesize a fake NNS that points to the derived class. This will 2300 // perform name lookup during template instantiation. 2301 CXXScopeSpec SS; 2302 auto *NNS = 2303 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2304 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2305 return DependentScopeDeclRefExpr::Create( 2306 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2307 TemplateArgs); 2308 } 2309 2310 ExprResult 2311 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2312 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2313 bool HasTrailingLParen, bool IsAddressOfOperand, 2314 CorrectionCandidateCallback *CCC, 2315 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2316 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2317 "cannot be direct & operand and have a trailing lparen"); 2318 if (SS.isInvalid()) 2319 return ExprError(); 2320 2321 TemplateArgumentListInfo TemplateArgsBuffer; 2322 2323 // Decompose the UnqualifiedId into the following data. 2324 DeclarationNameInfo NameInfo; 2325 const TemplateArgumentListInfo *TemplateArgs; 2326 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2327 2328 DeclarationName Name = NameInfo.getName(); 2329 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2330 SourceLocation NameLoc = NameInfo.getLoc(); 2331 2332 if (II && II->isEditorPlaceholder()) { 2333 // FIXME: When typed placeholders are supported we can create a typed 2334 // placeholder expression node. 2335 return ExprError(); 2336 } 2337 2338 // C++ [temp.dep.expr]p3: 2339 // An id-expression is type-dependent if it contains: 2340 // -- an identifier that was declared with a dependent type, 2341 // (note: handled after lookup) 2342 // -- a template-id that is dependent, 2343 // (note: handled in BuildTemplateIdExpr) 2344 // -- a conversion-function-id that specifies a dependent type, 2345 // -- a nested-name-specifier that contains a class-name that 2346 // names a dependent type. 2347 // Determine whether this is a member of an unknown specialization; 2348 // we need to handle these differently. 2349 bool DependentID = false; 2350 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2351 Name.getCXXNameType()->isDependentType()) { 2352 DependentID = true; 2353 } else if (SS.isSet()) { 2354 if (DeclContext *DC = computeDeclContext(SS, false)) { 2355 if (RequireCompleteDeclContext(SS, DC)) 2356 return ExprError(); 2357 } else { 2358 DependentID = true; 2359 } 2360 } 2361 2362 if (DependentID) 2363 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2364 IsAddressOfOperand, TemplateArgs); 2365 2366 // Perform the required lookup. 2367 LookupResult R(*this, NameInfo, 2368 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2369 ? LookupObjCImplicitSelfParam 2370 : LookupOrdinaryName); 2371 if (TemplateKWLoc.isValid() || TemplateArgs) { 2372 // Lookup the template name again to correctly establish the context in 2373 // which it was found. This is really unfortunate as we already did the 2374 // lookup to determine that it was a template name in the first place. If 2375 // this becomes a performance hit, we can work harder to preserve those 2376 // results until we get here but it's likely not worth it. 2377 bool MemberOfUnknownSpecialization; 2378 AssumedTemplateKind AssumedTemplate; 2379 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2380 MemberOfUnknownSpecialization, TemplateKWLoc, 2381 &AssumedTemplate)) 2382 return ExprError(); 2383 2384 if (MemberOfUnknownSpecialization || 2385 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2386 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2387 IsAddressOfOperand, TemplateArgs); 2388 } else { 2389 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2390 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2391 2392 // If the result might be in a dependent base class, this is a dependent 2393 // id-expression. 2394 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2395 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2396 IsAddressOfOperand, TemplateArgs); 2397 2398 // If this reference is in an Objective-C method, then we need to do 2399 // some special Objective-C lookup, too. 2400 if (IvarLookupFollowUp) { 2401 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2402 if (E.isInvalid()) 2403 return ExprError(); 2404 2405 if (Expr *Ex = E.getAs<Expr>()) 2406 return Ex; 2407 } 2408 } 2409 2410 if (R.isAmbiguous()) 2411 return ExprError(); 2412 2413 // This could be an implicitly declared function reference (legal in C90, 2414 // extension in C99, forbidden in C++). 2415 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2416 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2417 if (D) R.addDecl(D); 2418 } 2419 2420 // Determine whether this name might be a candidate for 2421 // argument-dependent lookup. 2422 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2423 2424 if (R.empty() && !ADL) { 2425 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2426 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2427 TemplateKWLoc, TemplateArgs)) 2428 return E; 2429 } 2430 2431 // Don't diagnose an empty lookup for inline assembly. 2432 if (IsInlineAsmIdentifier) 2433 return ExprError(); 2434 2435 // If this name wasn't predeclared and if this is not a function 2436 // call, diagnose the problem. 2437 TypoExpr *TE = nullptr; 2438 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2439 : nullptr); 2440 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2441 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2442 "Typo correction callback misconfigured"); 2443 if (CCC) { 2444 // Make sure the callback knows what the typo being diagnosed is. 2445 CCC->setTypoName(II); 2446 if (SS.isValid()) 2447 CCC->setTypoNNS(SS.getScopeRep()); 2448 } 2449 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2450 // a template name, but we happen to have always already looked up the name 2451 // before we get here if it must be a template name. 2452 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2453 None, &TE)) { 2454 if (TE && KeywordReplacement) { 2455 auto &State = getTypoExprState(TE); 2456 auto BestTC = State.Consumer->getNextCorrection(); 2457 if (BestTC.isKeyword()) { 2458 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2459 if (State.DiagHandler) 2460 State.DiagHandler(BestTC); 2461 KeywordReplacement->startToken(); 2462 KeywordReplacement->setKind(II->getTokenID()); 2463 KeywordReplacement->setIdentifierInfo(II); 2464 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2465 // Clean up the state associated with the TypoExpr, since it has 2466 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2467 clearDelayedTypo(TE); 2468 // Signal that a correction to a keyword was performed by returning a 2469 // valid-but-null ExprResult. 2470 return (Expr*)nullptr; 2471 } 2472 State.Consumer->resetCorrectionStream(); 2473 } 2474 return TE ? TE : ExprError(); 2475 } 2476 2477 assert(!R.empty() && 2478 "DiagnoseEmptyLookup returned false but added no results"); 2479 2480 // If we found an Objective-C instance variable, let 2481 // LookupInObjCMethod build the appropriate expression to 2482 // reference the ivar. 2483 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2484 R.clear(); 2485 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2486 // In a hopelessly buggy code, Objective-C instance variable 2487 // lookup fails and no expression will be built to reference it. 2488 if (!E.isInvalid() && !E.get()) 2489 return ExprError(); 2490 return E; 2491 } 2492 } 2493 2494 // This is guaranteed from this point on. 2495 assert(!R.empty() || ADL); 2496 2497 // Check whether this might be a C++ implicit instance member access. 2498 // C++ [class.mfct.non-static]p3: 2499 // When an id-expression that is not part of a class member access 2500 // syntax and not used to form a pointer to member is used in the 2501 // body of a non-static member function of class X, if name lookup 2502 // resolves the name in the id-expression to a non-static non-type 2503 // member of some class C, the id-expression is transformed into a 2504 // class member access expression using (*this) as the 2505 // postfix-expression to the left of the . operator. 2506 // 2507 // But we don't actually need to do this for '&' operands if R 2508 // resolved to a function or overloaded function set, because the 2509 // expression is ill-formed if it actually works out to be a 2510 // non-static member function: 2511 // 2512 // C++ [expr.ref]p4: 2513 // Otherwise, if E1.E2 refers to a non-static member function. . . 2514 // [t]he expression can be used only as the left-hand operand of a 2515 // member function call. 2516 // 2517 // There are other safeguards against such uses, but it's important 2518 // to get this right here so that we don't end up making a 2519 // spuriously dependent expression if we're inside a dependent 2520 // instance method. 2521 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2522 bool MightBeImplicitMember; 2523 if (!IsAddressOfOperand) 2524 MightBeImplicitMember = true; 2525 else if (!SS.isEmpty()) 2526 MightBeImplicitMember = false; 2527 else if (R.isOverloadedResult()) 2528 MightBeImplicitMember = false; 2529 else if (R.isUnresolvableResult()) 2530 MightBeImplicitMember = true; 2531 else 2532 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2533 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2534 isa<MSPropertyDecl>(R.getFoundDecl()); 2535 2536 if (MightBeImplicitMember) 2537 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2538 R, TemplateArgs, S); 2539 } 2540 2541 if (TemplateArgs || TemplateKWLoc.isValid()) { 2542 2543 // In C++1y, if this is a variable template id, then check it 2544 // in BuildTemplateIdExpr(). 2545 // The single lookup result must be a variable template declaration. 2546 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2547 Id.TemplateId->Kind == TNK_Var_template) { 2548 assert(R.getAsSingle<VarTemplateDecl>() && 2549 "There should only be one declaration found."); 2550 } 2551 2552 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2553 } 2554 2555 return BuildDeclarationNameExpr(SS, R, ADL); 2556 } 2557 2558 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2559 /// declaration name, generally during template instantiation. 2560 /// There's a large number of things which don't need to be done along 2561 /// this path. 2562 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2563 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2564 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2565 DeclContext *DC = computeDeclContext(SS, false); 2566 if (!DC) 2567 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2568 NameInfo, /*TemplateArgs=*/nullptr); 2569 2570 if (RequireCompleteDeclContext(SS, DC)) 2571 return ExprError(); 2572 2573 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2574 LookupQualifiedName(R, DC); 2575 2576 if (R.isAmbiguous()) 2577 return ExprError(); 2578 2579 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2580 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2581 NameInfo, /*TemplateArgs=*/nullptr); 2582 2583 if (R.empty()) { 2584 Diag(NameInfo.getLoc(), diag::err_no_member) 2585 << NameInfo.getName() << DC << SS.getRange(); 2586 return ExprError(); 2587 } 2588 2589 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2590 // Diagnose a missing typename if this resolved unambiguously to a type in 2591 // a dependent context. If we can recover with a type, downgrade this to 2592 // a warning in Microsoft compatibility mode. 2593 unsigned DiagID = diag::err_typename_missing; 2594 if (RecoveryTSI && getLangOpts().MSVCCompat) 2595 DiagID = diag::ext_typename_missing; 2596 SourceLocation Loc = SS.getBeginLoc(); 2597 auto D = Diag(Loc, DiagID); 2598 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2599 << SourceRange(Loc, NameInfo.getEndLoc()); 2600 2601 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2602 // context. 2603 if (!RecoveryTSI) 2604 return ExprError(); 2605 2606 // Only issue the fixit if we're prepared to recover. 2607 D << FixItHint::CreateInsertion(Loc, "typename "); 2608 2609 // Recover by pretending this was an elaborated type. 2610 QualType Ty = Context.getTypeDeclType(TD); 2611 TypeLocBuilder TLB; 2612 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2613 2614 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2615 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2616 QTL.setElaboratedKeywordLoc(SourceLocation()); 2617 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2618 2619 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2620 2621 return ExprEmpty(); 2622 } 2623 2624 // Defend against this resolving to an implicit member access. We usually 2625 // won't get here if this might be a legitimate a class member (we end up in 2626 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2627 // a pointer-to-member or in an unevaluated context in C++11. 2628 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2629 return BuildPossibleImplicitMemberExpr(SS, 2630 /*TemplateKWLoc=*/SourceLocation(), 2631 R, /*TemplateArgs=*/nullptr, S); 2632 2633 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2634 } 2635 2636 /// The parser has read a name in, and Sema has detected that we're currently 2637 /// inside an ObjC method. Perform some additional checks and determine if we 2638 /// should form a reference to an ivar. 2639 /// 2640 /// Ideally, most of this would be done by lookup, but there's 2641 /// actually quite a lot of extra work involved. 2642 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2643 IdentifierInfo *II) { 2644 SourceLocation Loc = Lookup.getNameLoc(); 2645 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2646 2647 // Check for error condition which is already reported. 2648 if (!CurMethod) 2649 return DeclResult(true); 2650 2651 // There are two cases to handle here. 1) scoped lookup could have failed, 2652 // in which case we should look for an ivar. 2) scoped lookup could have 2653 // found a decl, but that decl is outside the current instance method (i.e. 2654 // a global variable). In these two cases, we do a lookup for an ivar with 2655 // this name, if the lookup sucedes, we replace it our current decl. 2656 2657 // If we're in a class method, we don't normally want to look for 2658 // ivars. But if we don't find anything else, and there's an 2659 // ivar, that's an error. 2660 bool IsClassMethod = CurMethod->isClassMethod(); 2661 2662 bool LookForIvars; 2663 if (Lookup.empty()) 2664 LookForIvars = true; 2665 else if (IsClassMethod) 2666 LookForIvars = false; 2667 else 2668 LookForIvars = (Lookup.isSingleResult() && 2669 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2670 ObjCInterfaceDecl *IFace = nullptr; 2671 if (LookForIvars) { 2672 IFace = CurMethod->getClassInterface(); 2673 ObjCInterfaceDecl *ClassDeclared; 2674 ObjCIvarDecl *IV = nullptr; 2675 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2676 // Diagnose using an ivar in a class method. 2677 if (IsClassMethod) { 2678 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2679 return DeclResult(true); 2680 } 2681 2682 // Diagnose the use of an ivar outside of the declaring class. 2683 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2684 !declaresSameEntity(ClassDeclared, IFace) && 2685 !getLangOpts().DebuggerSupport) 2686 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2687 2688 // Success. 2689 return IV; 2690 } 2691 } else if (CurMethod->isInstanceMethod()) { 2692 // We should warn if a local variable hides an ivar. 2693 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2694 ObjCInterfaceDecl *ClassDeclared; 2695 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2696 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2697 declaresSameEntity(IFace, ClassDeclared)) 2698 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2699 } 2700 } 2701 } else if (Lookup.isSingleResult() && 2702 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2703 // If accessing a stand-alone ivar in a class method, this is an error. 2704 if (const ObjCIvarDecl *IV = 2705 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2706 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2707 return DeclResult(true); 2708 } 2709 } 2710 2711 // Didn't encounter an error, didn't find an ivar. 2712 return DeclResult(false); 2713 } 2714 2715 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2716 ObjCIvarDecl *IV) { 2717 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2718 assert(CurMethod && CurMethod->isInstanceMethod() && 2719 "should not reference ivar from this context"); 2720 2721 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2722 assert(IFace && "should not reference ivar from this context"); 2723 2724 // If we're referencing an invalid decl, just return this as a silent 2725 // error node. The error diagnostic was already emitted on the decl. 2726 if (IV->isInvalidDecl()) 2727 return ExprError(); 2728 2729 // Check if referencing a field with __attribute__((deprecated)). 2730 if (DiagnoseUseOfDecl(IV, Loc)) 2731 return ExprError(); 2732 2733 // FIXME: This should use a new expr for a direct reference, don't 2734 // turn this into Self->ivar, just return a BareIVarExpr or something. 2735 IdentifierInfo &II = Context.Idents.get("self"); 2736 UnqualifiedId SelfName; 2737 SelfName.setIdentifier(&II, SourceLocation()); 2738 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2739 CXXScopeSpec SelfScopeSpec; 2740 SourceLocation TemplateKWLoc; 2741 ExprResult SelfExpr = 2742 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2743 /*HasTrailingLParen=*/false, 2744 /*IsAddressOfOperand=*/false); 2745 if (SelfExpr.isInvalid()) 2746 return ExprError(); 2747 2748 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2749 if (SelfExpr.isInvalid()) 2750 return ExprError(); 2751 2752 MarkAnyDeclReferenced(Loc, IV, true); 2753 2754 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2755 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2756 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2757 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2758 2759 ObjCIvarRefExpr *Result = new (Context) 2760 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2761 IV->getLocation(), SelfExpr.get(), true, true); 2762 2763 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2764 if (!isUnevaluatedContext() && 2765 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2766 getCurFunction()->recordUseOfWeak(Result); 2767 } 2768 if (getLangOpts().ObjCAutoRefCount) 2769 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2770 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2771 2772 return Result; 2773 } 2774 2775 /// The parser has read a name in, and Sema has detected that we're currently 2776 /// inside an ObjC method. Perform some additional checks and determine if we 2777 /// should form a reference to an ivar. If so, build an expression referencing 2778 /// that ivar. 2779 ExprResult 2780 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2781 IdentifierInfo *II, bool AllowBuiltinCreation) { 2782 // FIXME: Integrate this lookup step into LookupParsedName. 2783 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2784 if (Ivar.isInvalid()) 2785 return ExprError(); 2786 if (Ivar.isUsable()) 2787 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2788 cast<ObjCIvarDecl>(Ivar.get())); 2789 2790 if (Lookup.empty() && II && AllowBuiltinCreation) 2791 LookupBuiltin(Lookup); 2792 2793 // Sentinel value saying that we didn't do anything special. 2794 return ExprResult(false); 2795 } 2796 2797 /// Cast a base object to a member's actual type. 2798 /// 2799 /// Logically this happens in three phases: 2800 /// 2801 /// * First we cast from the base type to the naming class. 2802 /// The naming class is the class into which we were looking 2803 /// when we found the member; it's the qualifier type if a 2804 /// qualifier was provided, and otherwise it's the base type. 2805 /// 2806 /// * Next we cast from the naming class to the declaring class. 2807 /// If the member we found was brought into a class's scope by 2808 /// a using declaration, this is that class; otherwise it's 2809 /// the class declaring the member. 2810 /// 2811 /// * Finally we cast from the declaring class to the "true" 2812 /// declaring class of the member. This conversion does not 2813 /// obey access control. 2814 ExprResult 2815 Sema::PerformObjectMemberConversion(Expr *From, 2816 NestedNameSpecifier *Qualifier, 2817 NamedDecl *FoundDecl, 2818 NamedDecl *Member) { 2819 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2820 if (!RD) 2821 return From; 2822 2823 QualType DestRecordType; 2824 QualType DestType; 2825 QualType FromRecordType; 2826 QualType FromType = From->getType(); 2827 bool PointerConversions = false; 2828 if (isa<FieldDecl>(Member)) { 2829 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2830 auto FromPtrType = FromType->getAs<PointerType>(); 2831 DestRecordType = Context.getAddrSpaceQualType( 2832 DestRecordType, FromPtrType 2833 ? FromType->getPointeeType().getAddressSpace() 2834 : FromType.getAddressSpace()); 2835 2836 if (FromPtrType) { 2837 DestType = Context.getPointerType(DestRecordType); 2838 FromRecordType = FromPtrType->getPointeeType(); 2839 PointerConversions = true; 2840 } else { 2841 DestType = DestRecordType; 2842 FromRecordType = FromType; 2843 } 2844 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2845 if (Method->isStatic()) 2846 return From; 2847 2848 DestType = Method->getThisType(); 2849 DestRecordType = DestType->getPointeeType(); 2850 2851 if (FromType->getAs<PointerType>()) { 2852 FromRecordType = FromType->getPointeeType(); 2853 PointerConversions = true; 2854 } else { 2855 FromRecordType = FromType; 2856 DestType = DestRecordType; 2857 } 2858 2859 LangAS FromAS = FromRecordType.getAddressSpace(); 2860 LangAS DestAS = DestRecordType.getAddressSpace(); 2861 if (FromAS != DestAS) { 2862 QualType FromRecordTypeWithoutAS = 2863 Context.removeAddrSpaceQualType(FromRecordType); 2864 QualType FromTypeWithDestAS = 2865 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2866 if (PointerConversions) 2867 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2868 From = ImpCastExprToType(From, FromTypeWithDestAS, 2869 CK_AddressSpaceConversion, From->getValueKind()) 2870 .get(); 2871 } 2872 } else { 2873 // No conversion necessary. 2874 return From; 2875 } 2876 2877 if (DestType->isDependentType() || FromType->isDependentType()) 2878 return From; 2879 2880 // If the unqualified types are the same, no conversion is necessary. 2881 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2882 return From; 2883 2884 SourceRange FromRange = From->getSourceRange(); 2885 SourceLocation FromLoc = FromRange.getBegin(); 2886 2887 ExprValueKind VK = From->getValueKind(); 2888 2889 // C++ [class.member.lookup]p8: 2890 // [...] Ambiguities can often be resolved by qualifying a name with its 2891 // class name. 2892 // 2893 // If the member was a qualified name and the qualified referred to a 2894 // specific base subobject type, we'll cast to that intermediate type 2895 // first and then to the object in which the member is declared. That allows 2896 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2897 // 2898 // class Base { public: int x; }; 2899 // class Derived1 : public Base { }; 2900 // class Derived2 : public Base { }; 2901 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2902 // 2903 // void VeryDerived::f() { 2904 // x = 17; // error: ambiguous base subobjects 2905 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2906 // } 2907 if (Qualifier && Qualifier->getAsType()) { 2908 QualType QType = QualType(Qualifier->getAsType(), 0); 2909 assert(QType->isRecordType() && "lookup done with non-record type"); 2910 2911 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2912 2913 // In C++98, the qualifier type doesn't actually have to be a base 2914 // type of the object type, in which case we just ignore it. 2915 // Otherwise build the appropriate casts. 2916 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2917 CXXCastPath BasePath; 2918 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2919 FromLoc, FromRange, &BasePath)) 2920 return ExprError(); 2921 2922 if (PointerConversions) 2923 QType = Context.getPointerType(QType); 2924 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2925 VK, &BasePath).get(); 2926 2927 FromType = QType; 2928 FromRecordType = QRecordType; 2929 2930 // If the qualifier type was the same as the destination type, 2931 // we're done. 2932 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2933 return From; 2934 } 2935 } 2936 2937 bool IgnoreAccess = false; 2938 2939 // If we actually found the member through a using declaration, cast 2940 // down to the using declaration's type. 2941 // 2942 // Pointer equality is fine here because only one declaration of a 2943 // class ever has member declarations. 2944 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2945 assert(isa<UsingShadowDecl>(FoundDecl)); 2946 QualType URecordType = Context.getTypeDeclType( 2947 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2948 2949 // We only need to do this if the naming-class to declaring-class 2950 // conversion is non-trivial. 2951 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2952 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2953 CXXCastPath BasePath; 2954 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2955 FromLoc, FromRange, &BasePath)) 2956 return ExprError(); 2957 2958 QualType UType = URecordType; 2959 if (PointerConversions) 2960 UType = Context.getPointerType(UType); 2961 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2962 VK, &BasePath).get(); 2963 FromType = UType; 2964 FromRecordType = URecordType; 2965 } 2966 2967 // We don't do access control for the conversion from the 2968 // declaring class to the true declaring class. 2969 IgnoreAccess = true; 2970 } 2971 2972 CXXCastPath BasePath; 2973 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2974 FromLoc, FromRange, &BasePath, 2975 IgnoreAccess)) 2976 return ExprError(); 2977 2978 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2979 VK, &BasePath); 2980 } 2981 2982 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2983 const LookupResult &R, 2984 bool HasTrailingLParen) { 2985 // Only when used directly as the postfix-expression of a call. 2986 if (!HasTrailingLParen) 2987 return false; 2988 2989 // Never if a scope specifier was provided. 2990 if (SS.isSet()) 2991 return false; 2992 2993 // Only in C++ or ObjC++. 2994 if (!getLangOpts().CPlusPlus) 2995 return false; 2996 2997 // Turn off ADL when we find certain kinds of declarations during 2998 // normal lookup: 2999 for (NamedDecl *D : R) { 3000 // C++0x [basic.lookup.argdep]p3: 3001 // -- a declaration of a class member 3002 // Since using decls preserve this property, we check this on the 3003 // original decl. 3004 if (D->isCXXClassMember()) 3005 return false; 3006 3007 // C++0x [basic.lookup.argdep]p3: 3008 // -- a block-scope function declaration that is not a 3009 // using-declaration 3010 // NOTE: we also trigger this for function templates (in fact, we 3011 // don't check the decl type at all, since all other decl types 3012 // turn off ADL anyway). 3013 if (isa<UsingShadowDecl>(D)) 3014 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3015 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3016 return false; 3017 3018 // C++0x [basic.lookup.argdep]p3: 3019 // -- a declaration that is neither a function or a function 3020 // template 3021 // And also for builtin functions. 3022 if (isa<FunctionDecl>(D)) { 3023 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3024 3025 // But also builtin functions. 3026 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3027 return false; 3028 } else if (!isa<FunctionTemplateDecl>(D)) 3029 return false; 3030 } 3031 3032 return true; 3033 } 3034 3035 3036 /// Diagnoses obvious problems with the use of the given declaration 3037 /// as an expression. This is only actually called for lookups that 3038 /// were not overloaded, and it doesn't promise that the declaration 3039 /// will in fact be used. 3040 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3041 if (D->isInvalidDecl()) 3042 return true; 3043 3044 if (isa<TypedefNameDecl>(D)) { 3045 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3046 return true; 3047 } 3048 3049 if (isa<ObjCInterfaceDecl>(D)) { 3050 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3051 return true; 3052 } 3053 3054 if (isa<NamespaceDecl>(D)) { 3055 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3056 return true; 3057 } 3058 3059 return false; 3060 } 3061 3062 // Certain multiversion types should be treated as overloaded even when there is 3063 // only one result. 3064 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3065 assert(R.isSingleResult() && "Expected only a single result"); 3066 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3067 return FD && 3068 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3069 } 3070 3071 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3072 LookupResult &R, bool NeedsADL, 3073 bool AcceptInvalidDecl) { 3074 // If this is a single, fully-resolved result and we don't need ADL, 3075 // just build an ordinary singleton decl ref. 3076 if (!NeedsADL && R.isSingleResult() && 3077 !R.getAsSingle<FunctionTemplateDecl>() && 3078 !ShouldLookupResultBeMultiVersionOverload(R)) 3079 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3080 R.getRepresentativeDecl(), nullptr, 3081 AcceptInvalidDecl); 3082 3083 // We only need to check the declaration if there's exactly one 3084 // result, because in the overloaded case the results can only be 3085 // functions and function templates. 3086 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3087 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3088 return ExprError(); 3089 3090 // Otherwise, just build an unresolved lookup expression. Suppress 3091 // any lookup-related diagnostics; we'll hash these out later, when 3092 // we've picked a target. 3093 R.suppressDiagnostics(); 3094 3095 UnresolvedLookupExpr *ULE 3096 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3097 SS.getWithLocInContext(Context), 3098 R.getLookupNameInfo(), 3099 NeedsADL, R.isOverloadedResult(), 3100 R.begin(), R.end()); 3101 3102 return ULE; 3103 } 3104 3105 static void 3106 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3107 ValueDecl *var, DeclContext *DC); 3108 3109 /// Complete semantic analysis for a reference to the given declaration. 3110 ExprResult Sema::BuildDeclarationNameExpr( 3111 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3112 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3113 bool AcceptInvalidDecl) { 3114 assert(D && "Cannot refer to a NULL declaration"); 3115 assert(!isa<FunctionTemplateDecl>(D) && 3116 "Cannot refer unambiguously to a function template"); 3117 3118 SourceLocation Loc = NameInfo.getLoc(); 3119 if (CheckDeclInExpr(*this, Loc, D)) 3120 return ExprError(); 3121 3122 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3123 // Specifically diagnose references to class templates that are missing 3124 // a template argument list. 3125 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3126 return ExprError(); 3127 } 3128 3129 // Make sure that we're referring to a value. 3130 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3131 if (!VD) { 3132 Diag(Loc, diag::err_ref_non_value) 3133 << D << SS.getRange(); 3134 Diag(D->getLocation(), diag::note_declared_at); 3135 return ExprError(); 3136 } 3137 3138 // Check whether this declaration can be used. Note that we suppress 3139 // this check when we're going to perform argument-dependent lookup 3140 // on this function name, because this might not be the function 3141 // that overload resolution actually selects. 3142 if (DiagnoseUseOfDecl(VD, Loc)) 3143 return ExprError(); 3144 3145 // Only create DeclRefExpr's for valid Decl's. 3146 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3147 return ExprError(); 3148 3149 // Handle members of anonymous structs and unions. If we got here, 3150 // and the reference is to a class member indirect field, then this 3151 // must be the subject of a pointer-to-member expression. 3152 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3153 if (!indirectField->isCXXClassMember()) 3154 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3155 indirectField); 3156 3157 { 3158 QualType type = VD->getType(); 3159 if (type.isNull()) 3160 return ExprError(); 3161 ExprValueKind valueKind = VK_RValue; 3162 3163 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3164 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3165 // is expanded by some outer '...' in the context of the use. 3166 type = type.getNonPackExpansionType(); 3167 3168 switch (D->getKind()) { 3169 // Ignore all the non-ValueDecl kinds. 3170 #define ABSTRACT_DECL(kind) 3171 #define VALUE(type, base) 3172 #define DECL(type, base) \ 3173 case Decl::type: 3174 #include "clang/AST/DeclNodes.inc" 3175 llvm_unreachable("invalid value decl kind"); 3176 3177 // These shouldn't make it here. 3178 case Decl::ObjCAtDefsField: 3179 llvm_unreachable("forming non-member reference to ivar?"); 3180 3181 // Enum constants are always r-values and never references. 3182 // Unresolved using declarations are dependent. 3183 case Decl::EnumConstant: 3184 case Decl::UnresolvedUsingValue: 3185 case Decl::OMPDeclareReduction: 3186 case Decl::OMPDeclareMapper: 3187 valueKind = VK_RValue; 3188 break; 3189 3190 // Fields and indirect fields that got here must be for 3191 // pointer-to-member expressions; we just call them l-values for 3192 // internal consistency, because this subexpression doesn't really 3193 // exist in the high-level semantics. 3194 case Decl::Field: 3195 case Decl::IndirectField: 3196 case Decl::ObjCIvar: 3197 assert(getLangOpts().CPlusPlus && 3198 "building reference to field in C?"); 3199 3200 // These can't have reference type in well-formed programs, but 3201 // for internal consistency we do this anyway. 3202 type = type.getNonReferenceType(); 3203 valueKind = VK_LValue; 3204 break; 3205 3206 // Non-type template parameters are either l-values or r-values 3207 // depending on the type. 3208 case Decl::NonTypeTemplateParm: { 3209 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3210 type = reftype->getPointeeType(); 3211 valueKind = VK_LValue; // even if the parameter is an r-value reference 3212 break; 3213 } 3214 3215 // For non-references, we need to strip qualifiers just in case 3216 // the template parameter was declared as 'const int' or whatever. 3217 valueKind = VK_RValue; 3218 type = type.getUnqualifiedType(); 3219 break; 3220 } 3221 3222 case Decl::Var: 3223 case Decl::VarTemplateSpecialization: 3224 case Decl::VarTemplatePartialSpecialization: 3225 case Decl::Decomposition: 3226 case Decl::OMPCapturedExpr: 3227 // In C, "extern void blah;" is valid and is an r-value. 3228 if (!getLangOpts().CPlusPlus && 3229 !type.hasQualifiers() && 3230 type->isVoidType()) { 3231 valueKind = VK_RValue; 3232 break; 3233 } 3234 LLVM_FALLTHROUGH; 3235 3236 case Decl::ImplicitParam: 3237 case Decl::ParmVar: { 3238 // These are always l-values. 3239 valueKind = VK_LValue; 3240 type = type.getNonReferenceType(); 3241 3242 // FIXME: Does the addition of const really only apply in 3243 // potentially-evaluated contexts? Since the variable isn't actually 3244 // captured in an unevaluated context, it seems that the answer is no. 3245 if (!isUnevaluatedContext()) { 3246 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3247 if (!CapturedType.isNull()) 3248 type = CapturedType; 3249 } 3250 3251 break; 3252 } 3253 3254 case Decl::Binding: { 3255 // These are always lvalues. 3256 valueKind = VK_LValue; 3257 type = type.getNonReferenceType(); 3258 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3259 // decides how that's supposed to work. 3260 auto *BD = cast<BindingDecl>(VD); 3261 if (BD->getDeclContext() != CurContext) { 3262 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3263 if (DD && DD->hasLocalStorage()) 3264 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3265 } 3266 break; 3267 } 3268 3269 case Decl::Function: { 3270 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3271 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3272 type = Context.BuiltinFnTy; 3273 valueKind = VK_RValue; 3274 break; 3275 } 3276 } 3277 3278 const FunctionType *fty = type->castAs<FunctionType>(); 3279 3280 // If we're referring to a function with an __unknown_anytype 3281 // result type, make the entire expression __unknown_anytype. 3282 if (fty->getReturnType() == Context.UnknownAnyTy) { 3283 type = Context.UnknownAnyTy; 3284 valueKind = VK_RValue; 3285 break; 3286 } 3287 3288 // Functions are l-values in C++. 3289 if (getLangOpts().CPlusPlus) { 3290 valueKind = VK_LValue; 3291 break; 3292 } 3293 3294 // C99 DR 316 says that, if a function type comes from a 3295 // function definition (without a prototype), that type is only 3296 // used for checking compatibility. Therefore, when referencing 3297 // the function, we pretend that we don't have the full function 3298 // type. 3299 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3300 isa<FunctionProtoType>(fty)) 3301 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3302 fty->getExtInfo()); 3303 3304 // Functions are r-values in C. 3305 valueKind = VK_RValue; 3306 break; 3307 } 3308 3309 case Decl::CXXDeductionGuide: 3310 llvm_unreachable("building reference to deduction guide"); 3311 3312 case Decl::MSProperty: 3313 case Decl::MSGuid: 3314 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3315 // or duplicated between host and device? 3316 valueKind = VK_LValue; 3317 break; 3318 3319 case Decl::CXXMethod: 3320 // If we're referring to a method with an __unknown_anytype 3321 // result type, make the entire expression __unknown_anytype. 3322 // This should only be possible with a type written directly. 3323 if (const FunctionProtoType *proto 3324 = dyn_cast<FunctionProtoType>(VD->getType())) 3325 if (proto->getReturnType() == Context.UnknownAnyTy) { 3326 type = Context.UnknownAnyTy; 3327 valueKind = VK_RValue; 3328 break; 3329 } 3330 3331 // C++ methods are l-values if static, r-values if non-static. 3332 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3333 valueKind = VK_LValue; 3334 break; 3335 } 3336 LLVM_FALLTHROUGH; 3337 3338 case Decl::CXXConversion: 3339 case Decl::CXXDestructor: 3340 case Decl::CXXConstructor: 3341 valueKind = VK_RValue; 3342 break; 3343 } 3344 3345 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3346 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3347 TemplateArgs); 3348 } 3349 } 3350 3351 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3352 SmallString<32> &Target) { 3353 Target.resize(CharByteWidth * (Source.size() + 1)); 3354 char *ResultPtr = &Target[0]; 3355 const llvm::UTF8 *ErrorPtr; 3356 bool success = 3357 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3358 (void)success; 3359 assert(success); 3360 Target.resize(ResultPtr - &Target[0]); 3361 } 3362 3363 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3364 PredefinedExpr::IdentKind IK) { 3365 // Pick the current block, lambda, captured statement or function. 3366 Decl *currentDecl = nullptr; 3367 if (const BlockScopeInfo *BSI = getCurBlock()) 3368 currentDecl = BSI->TheDecl; 3369 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3370 currentDecl = LSI->CallOperator; 3371 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3372 currentDecl = CSI->TheCapturedDecl; 3373 else 3374 currentDecl = getCurFunctionOrMethodDecl(); 3375 3376 if (!currentDecl) { 3377 Diag(Loc, diag::ext_predef_outside_function); 3378 currentDecl = Context.getTranslationUnitDecl(); 3379 } 3380 3381 QualType ResTy; 3382 StringLiteral *SL = nullptr; 3383 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3384 ResTy = Context.DependentTy; 3385 else { 3386 // Pre-defined identifiers are of type char[x], where x is the length of 3387 // the string. 3388 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3389 unsigned Length = Str.length(); 3390 3391 llvm::APInt LengthI(32, Length + 1); 3392 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3393 ResTy = 3394 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3395 SmallString<32> RawChars; 3396 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3397 Str, RawChars); 3398 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3399 ArrayType::Normal, 3400 /*IndexTypeQuals*/ 0); 3401 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3402 /*Pascal*/ false, ResTy, Loc); 3403 } else { 3404 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3405 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3406 ArrayType::Normal, 3407 /*IndexTypeQuals*/ 0); 3408 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3409 /*Pascal*/ false, ResTy, Loc); 3410 } 3411 } 3412 3413 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3414 } 3415 3416 static std::pair<QualType, StringLiteral *> 3417 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3418 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3419 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3420 3421 if (OpType->isDependentType()) { 3422 Result.first = Context.DependentTy; 3423 return Result; 3424 } 3425 3426 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3427 llvm::APInt Length(32, Str.length() + 1); 3428 Result.first = 3429 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3430 Result.first = Context.getConstantArrayType( 3431 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3432 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3433 /*Pascal*/ false, Result.first, OpLoc); 3434 return Result; 3435 } 3436 3437 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3438 TypeSourceInfo *Operand) { 3439 QualType ResultTy; 3440 StringLiteral *SL; 3441 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3442 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3443 3444 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3445 PredefinedExpr::UniqueStableNameType, SL, 3446 Operand); 3447 } 3448 3449 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3450 Expr *E) { 3451 QualType ResultTy; 3452 StringLiteral *SL; 3453 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3454 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3455 3456 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3457 PredefinedExpr::UniqueStableNameExpr, SL, E); 3458 } 3459 3460 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3461 SourceLocation L, SourceLocation R, 3462 ParsedType Ty) { 3463 TypeSourceInfo *TInfo = nullptr; 3464 QualType T = GetTypeFromParser(Ty, &TInfo); 3465 3466 if (T.isNull()) 3467 return ExprError(); 3468 if (!TInfo) 3469 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3470 3471 return BuildUniqueStableName(OpLoc, TInfo); 3472 } 3473 3474 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3475 SourceLocation L, SourceLocation R, 3476 Expr *E) { 3477 return BuildUniqueStableName(OpLoc, E); 3478 } 3479 3480 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3481 PredefinedExpr::IdentKind IK; 3482 3483 switch (Kind) { 3484 default: llvm_unreachable("Unknown simple primary expr!"); 3485 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3486 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3487 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3488 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3489 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3490 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3491 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3492 } 3493 3494 return BuildPredefinedExpr(Loc, IK); 3495 } 3496 3497 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3498 SmallString<16> CharBuffer; 3499 bool Invalid = false; 3500 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3501 if (Invalid) 3502 return ExprError(); 3503 3504 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3505 PP, Tok.getKind()); 3506 if (Literal.hadError()) 3507 return ExprError(); 3508 3509 QualType Ty; 3510 if (Literal.isWide()) 3511 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3512 else if (Literal.isUTF8() && getLangOpts().Char8) 3513 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3514 else if (Literal.isUTF16()) 3515 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3516 else if (Literal.isUTF32()) 3517 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3518 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3519 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3520 else 3521 Ty = Context.CharTy; // 'x' -> char in C++ 3522 3523 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3524 if (Literal.isWide()) 3525 Kind = CharacterLiteral::Wide; 3526 else if (Literal.isUTF16()) 3527 Kind = CharacterLiteral::UTF16; 3528 else if (Literal.isUTF32()) 3529 Kind = CharacterLiteral::UTF32; 3530 else if (Literal.isUTF8()) 3531 Kind = CharacterLiteral::UTF8; 3532 3533 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3534 Tok.getLocation()); 3535 3536 if (Literal.getUDSuffix().empty()) 3537 return Lit; 3538 3539 // We're building a user-defined literal. 3540 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3541 SourceLocation UDSuffixLoc = 3542 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3543 3544 // Make sure we're allowed user-defined literals here. 3545 if (!UDLScope) 3546 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3547 3548 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3549 // operator "" X (ch) 3550 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3551 Lit, Tok.getLocation()); 3552 } 3553 3554 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3555 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3556 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3557 Context.IntTy, Loc); 3558 } 3559 3560 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3561 QualType Ty, SourceLocation Loc) { 3562 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3563 3564 using llvm::APFloat; 3565 APFloat Val(Format); 3566 3567 APFloat::opStatus result = Literal.GetFloatValue(Val); 3568 3569 // Overflow is always an error, but underflow is only an error if 3570 // we underflowed to zero (APFloat reports denormals as underflow). 3571 if ((result & APFloat::opOverflow) || 3572 ((result & APFloat::opUnderflow) && Val.isZero())) { 3573 unsigned diagnostic; 3574 SmallString<20> buffer; 3575 if (result & APFloat::opOverflow) { 3576 diagnostic = diag::warn_float_overflow; 3577 APFloat::getLargest(Format).toString(buffer); 3578 } else { 3579 diagnostic = diag::warn_float_underflow; 3580 APFloat::getSmallest(Format).toString(buffer); 3581 } 3582 3583 S.Diag(Loc, diagnostic) 3584 << Ty 3585 << StringRef(buffer.data(), buffer.size()); 3586 } 3587 3588 bool isExact = (result == APFloat::opOK); 3589 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3590 } 3591 3592 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3593 assert(E && "Invalid expression"); 3594 3595 if (E->isValueDependent()) 3596 return false; 3597 3598 QualType QT = E->getType(); 3599 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3600 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3601 return true; 3602 } 3603 3604 llvm::APSInt ValueAPS; 3605 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3606 3607 if (R.isInvalid()) 3608 return true; 3609 3610 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3611 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3612 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3613 << ValueAPS.toString(10) << ValueIsPositive; 3614 return true; 3615 } 3616 3617 return false; 3618 } 3619 3620 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3621 // Fast path for a single digit (which is quite common). A single digit 3622 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3623 if (Tok.getLength() == 1) { 3624 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3625 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3626 } 3627 3628 SmallString<128> SpellingBuffer; 3629 // NumericLiteralParser wants to overread by one character. Add padding to 3630 // the buffer in case the token is copied to the buffer. If getSpelling() 3631 // returns a StringRef to the memory buffer, it should have a null char at 3632 // the EOF, so it is also safe. 3633 SpellingBuffer.resize(Tok.getLength() + 1); 3634 3635 // Get the spelling of the token, which eliminates trigraphs, etc. 3636 bool Invalid = false; 3637 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3638 if (Invalid) 3639 return ExprError(); 3640 3641 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3642 PP.getSourceManager(), PP.getLangOpts(), 3643 PP.getTargetInfo(), PP.getDiagnostics()); 3644 if (Literal.hadError) 3645 return ExprError(); 3646 3647 if (Literal.hasUDSuffix()) { 3648 // We're building a user-defined literal. 3649 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3650 SourceLocation UDSuffixLoc = 3651 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3652 3653 // Make sure we're allowed user-defined literals here. 3654 if (!UDLScope) 3655 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3656 3657 QualType CookedTy; 3658 if (Literal.isFloatingLiteral()) { 3659 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3660 // long double, the literal is treated as a call of the form 3661 // operator "" X (f L) 3662 CookedTy = Context.LongDoubleTy; 3663 } else { 3664 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3665 // unsigned long long, the literal is treated as a call of the form 3666 // operator "" X (n ULL) 3667 CookedTy = Context.UnsignedLongLongTy; 3668 } 3669 3670 DeclarationName OpName = 3671 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3672 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3673 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3674 3675 SourceLocation TokLoc = Tok.getLocation(); 3676 3677 // Perform literal operator lookup to determine if we're building a raw 3678 // literal or a cooked one. 3679 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3680 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3681 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3682 /*AllowStringTemplate*/ false, 3683 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3684 case LOLR_ErrorNoDiagnostic: 3685 // Lookup failure for imaginary constants isn't fatal, there's still the 3686 // GNU extension producing _Complex types. 3687 break; 3688 case LOLR_Error: 3689 return ExprError(); 3690 case LOLR_Cooked: { 3691 Expr *Lit; 3692 if (Literal.isFloatingLiteral()) { 3693 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3694 } else { 3695 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3696 if (Literal.GetIntegerValue(ResultVal)) 3697 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3698 << /* Unsigned */ 1; 3699 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3700 Tok.getLocation()); 3701 } 3702 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3703 } 3704 3705 case LOLR_Raw: { 3706 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3707 // literal is treated as a call of the form 3708 // operator "" X ("n") 3709 unsigned Length = Literal.getUDSuffixOffset(); 3710 QualType StrTy = Context.getConstantArrayType( 3711 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3712 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3713 Expr *Lit = StringLiteral::Create( 3714 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3715 /*Pascal*/false, StrTy, &TokLoc, 1); 3716 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3717 } 3718 3719 case LOLR_Template: { 3720 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3721 // template), L is treated as a call fo the form 3722 // operator "" X <'c1', 'c2', ... 'ck'>() 3723 // where n is the source character sequence c1 c2 ... ck. 3724 TemplateArgumentListInfo ExplicitArgs; 3725 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3726 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3727 llvm::APSInt Value(CharBits, CharIsUnsigned); 3728 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3729 Value = TokSpelling[I]; 3730 TemplateArgument Arg(Context, Value, Context.CharTy); 3731 TemplateArgumentLocInfo ArgInfo; 3732 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3733 } 3734 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3735 &ExplicitArgs); 3736 } 3737 case LOLR_StringTemplate: 3738 llvm_unreachable("unexpected literal operator lookup result"); 3739 } 3740 } 3741 3742 Expr *Res; 3743 3744 if (Literal.isFixedPointLiteral()) { 3745 QualType Ty; 3746 3747 if (Literal.isAccum) { 3748 if (Literal.isHalf) { 3749 Ty = Context.ShortAccumTy; 3750 } else if (Literal.isLong) { 3751 Ty = Context.LongAccumTy; 3752 } else { 3753 Ty = Context.AccumTy; 3754 } 3755 } else if (Literal.isFract) { 3756 if (Literal.isHalf) { 3757 Ty = Context.ShortFractTy; 3758 } else if (Literal.isLong) { 3759 Ty = Context.LongFractTy; 3760 } else { 3761 Ty = Context.FractTy; 3762 } 3763 } 3764 3765 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3766 3767 bool isSigned = !Literal.isUnsigned; 3768 unsigned scale = Context.getFixedPointScale(Ty); 3769 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3770 3771 llvm::APInt Val(bit_width, 0, isSigned); 3772 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3773 bool ValIsZero = Val.isNullValue() && !Overflowed; 3774 3775 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3776 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3777 // Clause 6.4.4 - The value of a constant shall be in the range of 3778 // representable values for its type, with exception for constants of a 3779 // fract type with a value of exactly 1; such a constant shall denote 3780 // the maximal value for the type. 3781 --Val; 3782 else if (Val.ugt(MaxVal) || Overflowed) 3783 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3784 3785 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3786 Tok.getLocation(), scale); 3787 } else if (Literal.isFloatingLiteral()) { 3788 QualType Ty; 3789 if (Literal.isHalf){ 3790 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3791 Ty = Context.HalfTy; 3792 else { 3793 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3794 return ExprError(); 3795 } 3796 } else if (Literal.isFloat) 3797 Ty = Context.FloatTy; 3798 else if (Literal.isLong) 3799 Ty = Context.LongDoubleTy; 3800 else if (Literal.isFloat16) 3801 Ty = Context.Float16Ty; 3802 else if (Literal.isFloat128) 3803 Ty = Context.Float128Ty; 3804 else 3805 Ty = Context.DoubleTy; 3806 3807 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3808 3809 if (Ty == Context.DoubleTy) { 3810 if (getLangOpts().SinglePrecisionConstants) { 3811 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3812 if (BTy->getKind() != BuiltinType::Float) { 3813 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3814 } 3815 } else if (getLangOpts().OpenCL && 3816 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3817 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3818 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3819 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3820 } 3821 } 3822 } else if (!Literal.isIntegerLiteral()) { 3823 return ExprError(); 3824 } else { 3825 QualType Ty; 3826 3827 // 'long long' is a C99 or C++11 feature. 3828 if (!getLangOpts().C99 && Literal.isLongLong) { 3829 if (getLangOpts().CPlusPlus) 3830 Diag(Tok.getLocation(), 3831 getLangOpts().CPlusPlus11 ? 3832 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3833 else 3834 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3835 } 3836 3837 // Get the value in the widest-possible width. 3838 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3839 llvm::APInt ResultVal(MaxWidth, 0); 3840 3841 if (Literal.GetIntegerValue(ResultVal)) { 3842 // If this value didn't fit into uintmax_t, error and force to ull. 3843 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3844 << /* Unsigned */ 1; 3845 Ty = Context.UnsignedLongLongTy; 3846 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3847 "long long is not intmax_t?"); 3848 } else { 3849 // If this value fits into a ULL, try to figure out what else it fits into 3850 // according to the rules of C99 6.4.4.1p5. 3851 3852 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3853 // be an unsigned int. 3854 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3855 3856 // Check from smallest to largest, picking the smallest type we can. 3857 unsigned Width = 0; 3858 3859 // Microsoft specific integer suffixes are explicitly sized. 3860 if (Literal.MicrosoftInteger) { 3861 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3862 Width = 8; 3863 Ty = Context.CharTy; 3864 } else { 3865 Width = Literal.MicrosoftInteger; 3866 Ty = Context.getIntTypeForBitwidth(Width, 3867 /*Signed=*/!Literal.isUnsigned); 3868 } 3869 } 3870 3871 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3872 // Are int/unsigned possibilities? 3873 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3874 3875 // Does it fit in a unsigned int? 3876 if (ResultVal.isIntN(IntSize)) { 3877 // Does it fit in a signed int? 3878 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3879 Ty = Context.IntTy; 3880 else if (AllowUnsigned) 3881 Ty = Context.UnsignedIntTy; 3882 Width = IntSize; 3883 } 3884 } 3885 3886 // Are long/unsigned long possibilities? 3887 if (Ty.isNull() && !Literal.isLongLong) { 3888 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3889 3890 // Does it fit in a unsigned long? 3891 if (ResultVal.isIntN(LongSize)) { 3892 // Does it fit in a signed long? 3893 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3894 Ty = Context.LongTy; 3895 else if (AllowUnsigned) 3896 Ty = Context.UnsignedLongTy; 3897 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3898 // is compatible. 3899 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3900 const unsigned LongLongSize = 3901 Context.getTargetInfo().getLongLongWidth(); 3902 Diag(Tok.getLocation(), 3903 getLangOpts().CPlusPlus 3904 ? Literal.isLong 3905 ? diag::warn_old_implicitly_unsigned_long_cxx 3906 : /*C++98 UB*/ diag:: 3907 ext_old_implicitly_unsigned_long_cxx 3908 : diag::warn_old_implicitly_unsigned_long) 3909 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3910 : /*will be ill-formed*/ 1); 3911 Ty = Context.UnsignedLongTy; 3912 } 3913 Width = LongSize; 3914 } 3915 } 3916 3917 // Check long long if needed. 3918 if (Ty.isNull()) { 3919 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3920 3921 // Does it fit in a unsigned long long? 3922 if (ResultVal.isIntN(LongLongSize)) { 3923 // Does it fit in a signed long long? 3924 // To be compatible with MSVC, hex integer literals ending with the 3925 // LL or i64 suffix are always signed in Microsoft mode. 3926 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3927 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3928 Ty = Context.LongLongTy; 3929 else if (AllowUnsigned) 3930 Ty = Context.UnsignedLongLongTy; 3931 Width = LongLongSize; 3932 } 3933 } 3934 3935 // If we still couldn't decide a type, we probably have something that 3936 // does not fit in a signed long long, but has no U suffix. 3937 if (Ty.isNull()) { 3938 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3939 Ty = Context.UnsignedLongLongTy; 3940 Width = Context.getTargetInfo().getLongLongWidth(); 3941 } 3942 3943 if (ResultVal.getBitWidth() != Width) 3944 ResultVal = ResultVal.trunc(Width); 3945 } 3946 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3947 } 3948 3949 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3950 if (Literal.isImaginary) { 3951 Res = new (Context) ImaginaryLiteral(Res, 3952 Context.getComplexType(Res->getType())); 3953 3954 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3955 } 3956 return Res; 3957 } 3958 3959 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3960 assert(E && "ActOnParenExpr() missing expr"); 3961 return new (Context) ParenExpr(L, R, E); 3962 } 3963 3964 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3965 SourceLocation Loc, 3966 SourceRange ArgRange) { 3967 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3968 // scalar or vector data type argument..." 3969 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3970 // type (C99 6.2.5p18) or void. 3971 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3972 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3973 << T << ArgRange; 3974 return true; 3975 } 3976 3977 assert((T->isVoidType() || !T->isIncompleteType()) && 3978 "Scalar types should always be complete"); 3979 return false; 3980 } 3981 3982 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3983 SourceLocation Loc, 3984 SourceRange ArgRange, 3985 UnaryExprOrTypeTrait TraitKind) { 3986 // Invalid types must be hard errors for SFINAE in C++. 3987 if (S.LangOpts.CPlusPlus) 3988 return true; 3989 3990 // C99 6.5.3.4p1: 3991 if (T->isFunctionType() && 3992 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3993 TraitKind == UETT_PreferredAlignOf)) { 3994 // sizeof(function)/alignof(function) is allowed as an extension. 3995 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3996 << getTraitSpelling(TraitKind) << ArgRange; 3997 return false; 3998 } 3999 4000 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4001 // this is an error (OpenCL v1.1 s6.3.k) 4002 if (T->isVoidType()) { 4003 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4004 : diag::ext_sizeof_alignof_void_type; 4005 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4006 return false; 4007 } 4008 4009 return true; 4010 } 4011 4012 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4013 SourceLocation Loc, 4014 SourceRange ArgRange, 4015 UnaryExprOrTypeTrait TraitKind) { 4016 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4017 // runtime doesn't allow it. 4018 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4019 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4020 << T << (TraitKind == UETT_SizeOf) 4021 << ArgRange; 4022 return true; 4023 } 4024 4025 return false; 4026 } 4027 4028 /// Check whether E is a pointer from a decayed array type (the decayed 4029 /// pointer type is equal to T) and emit a warning if it is. 4030 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4031 Expr *E) { 4032 // Don't warn if the operation changed the type. 4033 if (T != E->getType()) 4034 return; 4035 4036 // Now look for array decays. 4037 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4038 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4039 return; 4040 4041 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4042 << ICE->getType() 4043 << ICE->getSubExpr()->getType(); 4044 } 4045 4046 /// Check the constraints on expression operands to unary type expression 4047 /// and type traits. 4048 /// 4049 /// Completes any types necessary and validates the constraints on the operand 4050 /// expression. The logic mostly mirrors the type-based overload, but may modify 4051 /// the expression as it completes the type for that expression through template 4052 /// instantiation, etc. 4053 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4054 UnaryExprOrTypeTrait ExprKind) { 4055 QualType ExprTy = E->getType(); 4056 assert(!ExprTy->isReferenceType()); 4057 4058 bool IsUnevaluatedOperand = 4059 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4060 ExprKind == UETT_PreferredAlignOf); 4061 if (IsUnevaluatedOperand) { 4062 ExprResult Result = CheckUnevaluatedOperand(E); 4063 if (Result.isInvalid()) 4064 return true; 4065 E = Result.get(); 4066 } 4067 4068 if (ExprKind == UETT_VecStep) 4069 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4070 E->getSourceRange()); 4071 4072 // Explicitly list some types as extensions. 4073 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4074 E->getSourceRange(), ExprKind)) 4075 return false; 4076 4077 // 'alignof' applied to an expression only requires the base element type of 4078 // the expression to be complete. 'sizeof' requires the expression's type to 4079 // be complete (and will attempt to complete it if it's an array of unknown 4080 // bound). 4081 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4082 if (RequireCompleteSizedType( 4083 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4084 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4085 getTraitSpelling(ExprKind), E->getSourceRange())) 4086 return true; 4087 } else { 4088 if (RequireCompleteSizedExprType( 4089 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4090 getTraitSpelling(ExprKind), E->getSourceRange())) 4091 return true; 4092 } 4093 4094 // Completing the expression's type may have changed it. 4095 ExprTy = E->getType(); 4096 assert(!ExprTy->isReferenceType()); 4097 4098 if (ExprTy->isFunctionType()) { 4099 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4100 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4101 return true; 4102 } 4103 4104 // The operand for sizeof and alignof is in an unevaluated expression context, 4105 // so side effects could result in unintended consequences. 4106 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4107 E->HasSideEffects(Context, false)) 4108 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4109 4110 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4111 E->getSourceRange(), ExprKind)) 4112 return true; 4113 4114 if (ExprKind == UETT_SizeOf) { 4115 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4116 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4117 QualType OType = PVD->getOriginalType(); 4118 QualType Type = PVD->getType(); 4119 if (Type->isPointerType() && OType->isArrayType()) { 4120 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4121 << Type << OType; 4122 Diag(PVD->getLocation(), diag::note_declared_at); 4123 } 4124 } 4125 } 4126 4127 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4128 // decays into a pointer and returns an unintended result. This is most 4129 // likely a typo for "sizeof(array) op x". 4130 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4131 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4132 BO->getLHS()); 4133 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4134 BO->getRHS()); 4135 } 4136 } 4137 4138 return false; 4139 } 4140 4141 /// Check the constraints on operands to unary expression and type 4142 /// traits. 4143 /// 4144 /// This will complete any types necessary, and validate the various constraints 4145 /// on those operands. 4146 /// 4147 /// The UsualUnaryConversions() function is *not* called by this routine. 4148 /// C99 6.3.2.1p[2-4] all state: 4149 /// Except when it is the operand of the sizeof operator ... 4150 /// 4151 /// C++ [expr.sizeof]p4 4152 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4153 /// standard conversions are not applied to the operand of sizeof. 4154 /// 4155 /// This policy is followed for all of the unary trait expressions. 4156 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4157 SourceLocation OpLoc, 4158 SourceRange ExprRange, 4159 UnaryExprOrTypeTrait ExprKind) { 4160 if (ExprType->isDependentType()) 4161 return false; 4162 4163 // C++ [expr.sizeof]p2: 4164 // When applied to a reference or a reference type, the result 4165 // is the size of the referenced type. 4166 // C++11 [expr.alignof]p3: 4167 // When alignof is applied to a reference type, the result 4168 // shall be the alignment of the referenced type. 4169 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4170 ExprType = Ref->getPointeeType(); 4171 4172 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4173 // When alignof or _Alignof is applied to an array type, the result 4174 // is the alignment of the element type. 4175 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4176 ExprKind == UETT_OpenMPRequiredSimdAlign) 4177 ExprType = Context.getBaseElementType(ExprType); 4178 4179 if (ExprKind == UETT_VecStep) 4180 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4181 4182 // Explicitly list some types as extensions. 4183 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4184 ExprKind)) 4185 return false; 4186 4187 if (RequireCompleteSizedType( 4188 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4189 getTraitSpelling(ExprKind), ExprRange)) 4190 return true; 4191 4192 if (ExprType->isFunctionType()) { 4193 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4194 << getTraitSpelling(ExprKind) << ExprRange; 4195 return true; 4196 } 4197 4198 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4199 ExprKind)) 4200 return true; 4201 4202 return false; 4203 } 4204 4205 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4206 // Cannot know anything else if the expression is dependent. 4207 if (E->isTypeDependent()) 4208 return false; 4209 4210 if (E->getObjectKind() == OK_BitField) { 4211 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4212 << 1 << E->getSourceRange(); 4213 return true; 4214 } 4215 4216 ValueDecl *D = nullptr; 4217 Expr *Inner = E->IgnoreParens(); 4218 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4219 D = DRE->getDecl(); 4220 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4221 D = ME->getMemberDecl(); 4222 } 4223 4224 // If it's a field, require the containing struct to have a 4225 // complete definition so that we can compute the layout. 4226 // 4227 // This can happen in C++11 onwards, either by naming the member 4228 // in a way that is not transformed into a member access expression 4229 // (in an unevaluated operand, for instance), or by naming the member 4230 // in a trailing-return-type. 4231 // 4232 // For the record, since __alignof__ on expressions is a GCC 4233 // extension, GCC seems to permit this but always gives the 4234 // nonsensical answer 0. 4235 // 4236 // We don't really need the layout here --- we could instead just 4237 // directly check for all the appropriate alignment-lowing 4238 // attributes --- but that would require duplicating a lot of 4239 // logic that just isn't worth duplicating for such a marginal 4240 // use-case. 4241 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4242 // Fast path this check, since we at least know the record has a 4243 // definition if we can find a member of it. 4244 if (!FD->getParent()->isCompleteDefinition()) { 4245 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4246 << E->getSourceRange(); 4247 return true; 4248 } 4249 4250 // Otherwise, if it's a field, and the field doesn't have 4251 // reference type, then it must have a complete type (or be a 4252 // flexible array member, which we explicitly want to 4253 // white-list anyway), which makes the following checks trivial. 4254 if (!FD->getType()->isReferenceType()) 4255 return false; 4256 } 4257 4258 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4259 } 4260 4261 bool Sema::CheckVecStepExpr(Expr *E) { 4262 E = E->IgnoreParens(); 4263 4264 // Cannot know anything else if the expression is dependent. 4265 if (E->isTypeDependent()) 4266 return false; 4267 4268 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4269 } 4270 4271 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4272 CapturingScopeInfo *CSI) { 4273 assert(T->isVariablyModifiedType()); 4274 assert(CSI != nullptr); 4275 4276 // We're going to walk down into the type and look for VLA expressions. 4277 do { 4278 const Type *Ty = T.getTypePtr(); 4279 switch (Ty->getTypeClass()) { 4280 #define TYPE(Class, Base) 4281 #define ABSTRACT_TYPE(Class, Base) 4282 #define NON_CANONICAL_TYPE(Class, Base) 4283 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4284 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4285 #include "clang/AST/TypeNodes.inc" 4286 T = QualType(); 4287 break; 4288 // These types are never variably-modified. 4289 case Type::Builtin: 4290 case Type::Complex: 4291 case Type::Vector: 4292 case Type::ExtVector: 4293 case Type::ConstantMatrix: 4294 case Type::Record: 4295 case Type::Enum: 4296 case Type::Elaborated: 4297 case Type::TemplateSpecialization: 4298 case Type::ObjCObject: 4299 case Type::ObjCInterface: 4300 case Type::ObjCObjectPointer: 4301 case Type::ObjCTypeParam: 4302 case Type::Pipe: 4303 case Type::ExtInt: 4304 llvm_unreachable("type class is never variably-modified!"); 4305 case Type::Adjusted: 4306 T = cast<AdjustedType>(Ty)->getOriginalType(); 4307 break; 4308 case Type::Decayed: 4309 T = cast<DecayedType>(Ty)->getPointeeType(); 4310 break; 4311 case Type::Pointer: 4312 T = cast<PointerType>(Ty)->getPointeeType(); 4313 break; 4314 case Type::BlockPointer: 4315 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4316 break; 4317 case Type::LValueReference: 4318 case Type::RValueReference: 4319 T = cast<ReferenceType>(Ty)->getPointeeType(); 4320 break; 4321 case Type::MemberPointer: 4322 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4323 break; 4324 case Type::ConstantArray: 4325 case Type::IncompleteArray: 4326 // Losing element qualification here is fine. 4327 T = cast<ArrayType>(Ty)->getElementType(); 4328 break; 4329 case Type::VariableArray: { 4330 // Losing element qualification here is fine. 4331 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4332 4333 // Unknown size indication requires no size computation. 4334 // Otherwise, evaluate and record it. 4335 auto Size = VAT->getSizeExpr(); 4336 if (Size && !CSI->isVLATypeCaptured(VAT) && 4337 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4338 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4339 4340 T = VAT->getElementType(); 4341 break; 4342 } 4343 case Type::FunctionProto: 4344 case Type::FunctionNoProto: 4345 T = cast<FunctionType>(Ty)->getReturnType(); 4346 break; 4347 case Type::Paren: 4348 case Type::TypeOf: 4349 case Type::UnaryTransform: 4350 case Type::Attributed: 4351 case Type::SubstTemplateTypeParm: 4352 case Type::MacroQualified: 4353 // Keep walking after single level desugaring. 4354 T = T.getSingleStepDesugaredType(Context); 4355 break; 4356 case Type::Typedef: 4357 T = cast<TypedefType>(Ty)->desugar(); 4358 break; 4359 case Type::Decltype: 4360 T = cast<DecltypeType>(Ty)->desugar(); 4361 break; 4362 case Type::Auto: 4363 case Type::DeducedTemplateSpecialization: 4364 T = cast<DeducedType>(Ty)->getDeducedType(); 4365 break; 4366 case Type::TypeOfExpr: 4367 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4368 break; 4369 case Type::Atomic: 4370 T = cast<AtomicType>(Ty)->getValueType(); 4371 break; 4372 } 4373 } while (!T.isNull() && T->isVariablyModifiedType()); 4374 } 4375 4376 /// Build a sizeof or alignof expression given a type operand. 4377 ExprResult 4378 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4379 SourceLocation OpLoc, 4380 UnaryExprOrTypeTrait ExprKind, 4381 SourceRange R) { 4382 if (!TInfo) 4383 return ExprError(); 4384 4385 QualType T = TInfo->getType(); 4386 4387 if (!T->isDependentType() && 4388 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4389 return ExprError(); 4390 4391 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4392 if (auto *TT = T->getAs<TypedefType>()) { 4393 for (auto I = FunctionScopes.rbegin(), 4394 E = std::prev(FunctionScopes.rend()); 4395 I != E; ++I) { 4396 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4397 if (CSI == nullptr) 4398 break; 4399 DeclContext *DC = nullptr; 4400 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4401 DC = LSI->CallOperator; 4402 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4403 DC = CRSI->TheCapturedDecl; 4404 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4405 DC = BSI->TheDecl; 4406 if (DC) { 4407 if (DC->containsDecl(TT->getDecl())) 4408 break; 4409 captureVariablyModifiedType(Context, T, CSI); 4410 } 4411 } 4412 } 4413 } 4414 4415 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4416 return new (Context) UnaryExprOrTypeTraitExpr( 4417 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4418 } 4419 4420 /// Build a sizeof or alignof expression given an expression 4421 /// operand. 4422 ExprResult 4423 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4424 UnaryExprOrTypeTrait ExprKind) { 4425 ExprResult PE = CheckPlaceholderExpr(E); 4426 if (PE.isInvalid()) 4427 return ExprError(); 4428 4429 E = PE.get(); 4430 4431 // Verify that the operand is valid. 4432 bool isInvalid = false; 4433 if (E->isTypeDependent()) { 4434 // Delay type-checking for type-dependent expressions. 4435 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4436 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4437 } else if (ExprKind == UETT_VecStep) { 4438 isInvalid = CheckVecStepExpr(E); 4439 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4440 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4441 isInvalid = true; 4442 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4443 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4444 isInvalid = true; 4445 } else { 4446 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4447 } 4448 4449 if (isInvalid) 4450 return ExprError(); 4451 4452 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4453 PE = TransformToPotentiallyEvaluated(E); 4454 if (PE.isInvalid()) return ExprError(); 4455 E = PE.get(); 4456 } 4457 4458 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4459 return new (Context) UnaryExprOrTypeTraitExpr( 4460 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4461 } 4462 4463 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4464 /// expr and the same for @c alignof and @c __alignof 4465 /// Note that the ArgRange is invalid if isType is false. 4466 ExprResult 4467 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4468 UnaryExprOrTypeTrait ExprKind, bool IsType, 4469 void *TyOrEx, SourceRange ArgRange) { 4470 // If error parsing type, ignore. 4471 if (!TyOrEx) return ExprError(); 4472 4473 if (IsType) { 4474 TypeSourceInfo *TInfo; 4475 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4476 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4477 } 4478 4479 Expr *ArgEx = (Expr *)TyOrEx; 4480 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4481 return Result; 4482 } 4483 4484 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4485 bool IsReal) { 4486 if (V.get()->isTypeDependent()) 4487 return S.Context.DependentTy; 4488 4489 // _Real and _Imag are only l-values for normal l-values. 4490 if (V.get()->getObjectKind() != OK_Ordinary) { 4491 V = S.DefaultLvalueConversion(V.get()); 4492 if (V.isInvalid()) 4493 return QualType(); 4494 } 4495 4496 // These operators return the element type of a complex type. 4497 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4498 return CT->getElementType(); 4499 4500 // Otherwise they pass through real integer and floating point types here. 4501 if (V.get()->getType()->isArithmeticType()) 4502 return V.get()->getType(); 4503 4504 // Test for placeholders. 4505 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4506 if (PR.isInvalid()) return QualType(); 4507 if (PR.get() != V.get()) { 4508 V = PR; 4509 return CheckRealImagOperand(S, V, Loc, IsReal); 4510 } 4511 4512 // Reject anything else. 4513 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4514 << (IsReal ? "__real" : "__imag"); 4515 return QualType(); 4516 } 4517 4518 4519 4520 ExprResult 4521 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4522 tok::TokenKind Kind, Expr *Input) { 4523 UnaryOperatorKind Opc; 4524 switch (Kind) { 4525 default: llvm_unreachable("Unknown unary op!"); 4526 case tok::plusplus: Opc = UO_PostInc; break; 4527 case tok::minusminus: Opc = UO_PostDec; break; 4528 } 4529 4530 // Since this might is a postfix expression, get rid of ParenListExprs. 4531 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4532 if (Result.isInvalid()) return ExprError(); 4533 Input = Result.get(); 4534 4535 return BuildUnaryOp(S, OpLoc, Opc, Input); 4536 } 4537 4538 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4539 /// 4540 /// \return true on error 4541 static bool checkArithmeticOnObjCPointer(Sema &S, 4542 SourceLocation opLoc, 4543 Expr *op) { 4544 assert(op->getType()->isObjCObjectPointerType()); 4545 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4546 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4547 return false; 4548 4549 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4550 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4551 << op->getSourceRange(); 4552 return true; 4553 } 4554 4555 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4556 auto *BaseNoParens = Base->IgnoreParens(); 4557 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4558 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4559 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4560 } 4561 4562 ExprResult 4563 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4564 Expr *idx, SourceLocation rbLoc) { 4565 if (base && !base->getType().isNull() && 4566 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4567 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4568 SourceLocation(), /*Length*/ nullptr, 4569 /*Stride=*/nullptr, rbLoc); 4570 4571 // Since this might be a postfix expression, get rid of ParenListExprs. 4572 if (isa<ParenListExpr>(base)) { 4573 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4574 if (result.isInvalid()) return ExprError(); 4575 base = result.get(); 4576 } 4577 4578 // Check if base and idx form a MatrixSubscriptExpr. 4579 // 4580 // Helper to check for comma expressions, which are not allowed as indices for 4581 // matrix subscript expressions. 4582 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4583 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4584 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4585 << SourceRange(base->getBeginLoc(), rbLoc); 4586 return true; 4587 } 4588 return false; 4589 }; 4590 // The matrix subscript operator ([][])is considered a single operator. 4591 // Separating the index expressions by parenthesis is not allowed. 4592 if (base->getType()->isSpecificPlaceholderType( 4593 BuiltinType::IncompleteMatrixIdx) && 4594 !isa<MatrixSubscriptExpr>(base)) { 4595 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4596 << SourceRange(base->getBeginLoc(), rbLoc); 4597 return ExprError(); 4598 } 4599 // If the base is either a MatrixSubscriptExpr or a matrix type, try to create 4600 // a new MatrixSubscriptExpr. 4601 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4602 if (matSubscriptE) { 4603 if (CheckAndReportCommaError(idx)) 4604 return ExprError(); 4605 4606 assert(matSubscriptE->isIncomplete() && 4607 "base has to be an incomplete matrix subscript"); 4608 return CreateBuiltinMatrixSubscriptExpr( 4609 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4610 } 4611 Expr *matrixBase = base; 4612 bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4613 if (!IsMSPropertySubscript) { 4614 ExprResult result = CheckPlaceholderExpr(base); 4615 if (!result.isInvalid()) 4616 matrixBase = result.get(); 4617 } 4618 if (matrixBase->getType()->isMatrixType()) { 4619 if (CheckAndReportCommaError(idx)) 4620 return ExprError(); 4621 4622 return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc); 4623 } 4624 4625 // A comma-expression as the index is deprecated in C++2a onwards. 4626 if (getLangOpts().CPlusPlus20 && 4627 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4628 (isa<CXXOperatorCallExpr>(idx) && 4629 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4630 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4631 << SourceRange(base->getBeginLoc(), rbLoc); 4632 } 4633 4634 // Handle any non-overload placeholder types in the base and index 4635 // expressions. We can't handle overloads here because the other 4636 // operand might be an overloadable type, in which case the overload 4637 // resolution for the operator overload should get the first crack 4638 // at the overload. 4639 if (base->getType()->isNonOverloadPlaceholderType()) { 4640 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4641 if (!IsMSPropertySubscript) { 4642 ExprResult result = CheckPlaceholderExpr(base); 4643 if (result.isInvalid()) 4644 return ExprError(); 4645 base = result.get(); 4646 } 4647 } 4648 if (idx->getType()->isNonOverloadPlaceholderType()) { 4649 ExprResult result = CheckPlaceholderExpr(idx); 4650 if (result.isInvalid()) return ExprError(); 4651 idx = result.get(); 4652 } 4653 4654 // Build an unanalyzed expression if either operand is type-dependent. 4655 if (getLangOpts().CPlusPlus && 4656 (base->isTypeDependent() || idx->isTypeDependent())) { 4657 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4658 VK_LValue, OK_Ordinary, rbLoc); 4659 } 4660 4661 // MSDN, property (C++) 4662 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4663 // This attribute can also be used in the declaration of an empty array in a 4664 // class or structure definition. For example: 4665 // __declspec(property(get=GetX, put=PutX)) int x[]; 4666 // The above statement indicates that x[] can be used with one or more array 4667 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4668 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4669 if (IsMSPropertySubscript) { 4670 // Build MS property subscript expression if base is MS property reference 4671 // or MS property subscript. 4672 return new (Context) MSPropertySubscriptExpr( 4673 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4674 } 4675 4676 // Use C++ overloaded-operator rules if either operand has record 4677 // type. The spec says to do this if either type is *overloadable*, 4678 // but enum types can't declare subscript operators or conversion 4679 // operators, so there's nothing interesting for overload resolution 4680 // to do if there aren't any record types involved. 4681 // 4682 // ObjC pointers have their own subscripting logic that is not tied 4683 // to overload resolution and so should not take this path. 4684 if (getLangOpts().CPlusPlus && 4685 (base->getType()->isRecordType() || 4686 (!base->getType()->isObjCObjectPointerType() && 4687 idx->getType()->isRecordType()))) { 4688 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4689 } 4690 4691 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4692 4693 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4694 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4695 4696 return Res; 4697 } 4698 4699 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4700 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4701 InitializationKind Kind = 4702 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4703 InitializationSequence InitSeq(*this, Entity, Kind, E); 4704 return InitSeq.Perform(*this, Entity, Kind, E); 4705 } 4706 4707 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4708 Expr *ColumnIdx, 4709 SourceLocation RBLoc) { 4710 ExprResult BaseR = CheckPlaceholderExpr(Base); 4711 if (BaseR.isInvalid()) 4712 return BaseR; 4713 Base = BaseR.get(); 4714 4715 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4716 if (RowR.isInvalid()) 4717 return RowR; 4718 RowIdx = RowR.get(); 4719 4720 if (!ColumnIdx) 4721 return new (Context) MatrixSubscriptExpr( 4722 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4723 4724 // Build an unanalyzed expression if any of the operands is type-dependent. 4725 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4726 ColumnIdx->isTypeDependent()) 4727 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4728 Context.DependentTy, RBLoc); 4729 4730 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4731 if (ColumnR.isInvalid()) 4732 return ColumnR; 4733 ColumnIdx = ColumnR.get(); 4734 4735 // Check that IndexExpr is an integer expression. If it is a constant 4736 // expression, check that it is less than Dim (= the number of elements in the 4737 // corresponding dimension). 4738 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4739 bool IsColumnIdx) -> Expr * { 4740 if (!IndexExpr->getType()->isIntegerType() && 4741 !IndexExpr->isTypeDependent()) { 4742 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4743 << IsColumnIdx; 4744 return nullptr; 4745 } 4746 4747 if (Optional<llvm::APSInt> Idx = 4748 IndexExpr->getIntegerConstantExpr(Context)) { 4749 if ((*Idx < 0 || *Idx >= Dim)) { 4750 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4751 << IsColumnIdx << Dim; 4752 return nullptr; 4753 } 4754 } 4755 4756 ExprResult ConvExpr = 4757 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4758 assert(!ConvExpr.isInvalid() && 4759 "should be able to convert any integer type to size type"); 4760 return ConvExpr.get(); 4761 }; 4762 4763 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4764 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4765 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4766 if (!RowIdx || !ColumnIdx) 4767 return ExprError(); 4768 4769 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4770 MTy->getElementType(), RBLoc); 4771 } 4772 4773 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4774 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4775 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4776 4777 // For expressions like `&(*s).b`, the base is recorded and what should be 4778 // checked. 4779 const MemberExpr *Member = nullptr; 4780 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4781 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4782 4783 LastRecord.PossibleDerefs.erase(StrippedExpr); 4784 } 4785 4786 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4787 QualType ResultTy = E->getType(); 4788 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4789 4790 // Bail if the element is an array since it is not memory access. 4791 if (isa<ArrayType>(ResultTy)) 4792 return; 4793 4794 if (ResultTy->hasAttr(attr::NoDeref)) { 4795 LastRecord.PossibleDerefs.insert(E); 4796 return; 4797 } 4798 4799 // Check if the base type is a pointer to a member access of a struct 4800 // marked with noderef. 4801 const Expr *Base = E->getBase(); 4802 QualType BaseTy = Base->getType(); 4803 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4804 // Not a pointer access 4805 return; 4806 4807 const MemberExpr *Member = nullptr; 4808 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4809 Member->isArrow()) 4810 Base = Member->getBase(); 4811 4812 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4813 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4814 LastRecord.PossibleDerefs.insert(E); 4815 } 4816 } 4817 4818 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4819 Expr *LowerBound, 4820 SourceLocation ColonLocFirst, 4821 SourceLocation ColonLocSecond, 4822 Expr *Length, Expr *Stride, 4823 SourceLocation RBLoc) { 4824 if (Base->getType()->isPlaceholderType() && 4825 !Base->getType()->isSpecificPlaceholderType( 4826 BuiltinType::OMPArraySection)) { 4827 ExprResult Result = CheckPlaceholderExpr(Base); 4828 if (Result.isInvalid()) 4829 return ExprError(); 4830 Base = Result.get(); 4831 } 4832 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4833 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4834 if (Result.isInvalid()) 4835 return ExprError(); 4836 Result = DefaultLvalueConversion(Result.get()); 4837 if (Result.isInvalid()) 4838 return ExprError(); 4839 LowerBound = Result.get(); 4840 } 4841 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4842 ExprResult Result = CheckPlaceholderExpr(Length); 4843 if (Result.isInvalid()) 4844 return ExprError(); 4845 Result = DefaultLvalueConversion(Result.get()); 4846 if (Result.isInvalid()) 4847 return ExprError(); 4848 Length = Result.get(); 4849 } 4850 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4851 ExprResult Result = CheckPlaceholderExpr(Stride); 4852 if (Result.isInvalid()) 4853 return ExprError(); 4854 Result = DefaultLvalueConversion(Result.get()); 4855 if (Result.isInvalid()) 4856 return ExprError(); 4857 Stride = Result.get(); 4858 } 4859 4860 // Build an unanalyzed expression if either operand is type-dependent. 4861 if (Base->isTypeDependent() || 4862 (LowerBound && 4863 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4864 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4865 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4866 return new (Context) OMPArraySectionExpr( 4867 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4868 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4869 } 4870 4871 // Perform default conversions. 4872 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4873 QualType ResultTy; 4874 if (OriginalTy->isAnyPointerType()) { 4875 ResultTy = OriginalTy->getPointeeType(); 4876 } else if (OriginalTy->isArrayType()) { 4877 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4878 } else { 4879 return ExprError( 4880 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4881 << Base->getSourceRange()); 4882 } 4883 // C99 6.5.2.1p1 4884 if (LowerBound) { 4885 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4886 LowerBound); 4887 if (Res.isInvalid()) 4888 return ExprError(Diag(LowerBound->getExprLoc(), 4889 diag::err_omp_typecheck_section_not_integer) 4890 << 0 << LowerBound->getSourceRange()); 4891 LowerBound = Res.get(); 4892 4893 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4894 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4895 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4896 << 0 << LowerBound->getSourceRange(); 4897 } 4898 if (Length) { 4899 auto Res = 4900 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4901 if (Res.isInvalid()) 4902 return ExprError(Diag(Length->getExprLoc(), 4903 diag::err_omp_typecheck_section_not_integer) 4904 << 1 << Length->getSourceRange()); 4905 Length = Res.get(); 4906 4907 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4908 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4909 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4910 << 1 << Length->getSourceRange(); 4911 } 4912 if (Stride) { 4913 ExprResult Res = 4914 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4915 if (Res.isInvalid()) 4916 return ExprError(Diag(Stride->getExprLoc(), 4917 diag::err_omp_typecheck_section_not_integer) 4918 << 1 << Stride->getSourceRange()); 4919 Stride = Res.get(); 4920 4921 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4922 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4923 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4924 << 1 << Stride->getSourceRange(); 4925 } 4926 4927 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4928 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4929 // type. Note that functions are not objects, and that (in C99 parlance) 4930 // incomplete types are not object types. 4931 if (ResultTy->isFunctionType()) { 4932 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4933 << ResultTy << Base->getSourceRange(); 4934 return ExprError(); 4935 } 4936 4937 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4938 diag::err_omp_section_incomplete_type, Base)) 4939 return ExprError(); 4940 4941 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4942 Expr::EvalResult Result; 4943 if (LowerBound->EvaluateAsInt(Result, Context)) { 4944 // OpenMP 5.0, [2.1.5 Array Sections] 4945 // The array section must be a subset of the original array. 4946 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4947 if (LowerBoundValue.isNegative()) { 4948 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4949 << LowerBound->getSourceRange(); 4950 return ExprError(); 4951 } 4952 } 4953 } 4954 4955 if (Length) { 4956 Expr::EvalResult Result; 4957 if (Length->EvaluateAsInt(Result, Context)) { 4958 // OpenMP 5.0, [2.1.5 Array Sections] 4959 // The length must evaluate to non-negative integers. 4960 llvm::APSInt LengthValue = Result.Val.getInt(); 4961 if (LengthValue.isNegative()) { 4962 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4963 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4964 << Length->getSourceRange(); 4965 return ExprError(); 4966 } 4967 } 4968 } else if (ColonLocFirst.isValid() && 4969 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4970 !OriginalTy->isVariableArrayType()))) { 4971 // OpenMP 5.0, [2.1.5 Array Sections] 4972 // When the size of the array dimension is not known, the length must be 4973 // specified explicitly. 4974 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 4975 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4976 return ExprError(); 4977 } 4978 4979 if (Stride) { 4980 Expr::EvalResult Result; 4981 if (Stride->EvaluateAsInt(Result, Context)) { 4982 // OpenMP 5.0, [2.1.5 Array Sections] 4983 // The stride must evaluate to a positive integer. 4984 llvm::APSInt StrideValue = Result.Val.getInt(); 4985 if (!StrideValue.isStrictlyPositive()) { 4986 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 4987 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 4988 << Stride->getSourceRange(); 4989 return ExprError(); 4990 } 4991 } 4992 } 4993 4994 if (!Base->getType()->isSpecificPlaceholderType( 4995 BuiltinType::OMPArraySection)) { 4996 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4997 if (Result.isInvalid()) 4998 return ExprError(); 4999 Base = Result.get(); 5000 } 5001 return new (Context) OMPArraySectionExpr( 5002 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5003 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5004 } 5005 5006 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5007 SourceLocation RParenLoc, 5008 ArrayRef<Expr *> Dims, 5009 ArrayRef<SourceRange> Brackets) { 5010 if (Base->getType()->isPlaceholderType()) { 5011 ExprResult Result = CheckPlaceholderExpr(Base); 5012 if (Result.isInvalid()) 5013 return ExprError(); 5014 Result = DefaultLvalueConversion(Result.get()); 5015 if (Result.isInvalid()) 5016 return ExprError(); 5017 Base = Result.get(); 5018 } 5019 QualType BaseTy = Base->getType(); 5020 // Delay analysis of the types/expressions if instantiation/specialization is 5021 // required. 5022 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5023 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5024 LParenLoc, RParenLoc, Dims, Brackets); 5025 if (!BaseTy->isPointerType() || 5026 (!Base->isTypeDependent() && 5027 BaseTy->getPointeeType()->isIncompleteType())) 5028 return ExprError(Diag(Base->getExprLoc(), 5029 diag::err_omp_non_pointer_type_array_shaping_base) 5030 << Base->getSourceRange()); 5031 5032 SmallVector<Expr *, 4> NewDims; 5033 bool ErrorFound = false; 5034 for (Expr *Dim : Dims) { 5035 if (Dim->getType()->isPlaceholderType()) { 5036 ExprResult Result = CheckPlaceholderExpr(Dim); 5037 if (Result.isInvalid()) { 5038 ErrorFound = true; 5039 continue; 5040 } 5041 Result = DefaultLvalueConversion(Result.get()); 5042 if (Result.isInvalid()) { 5043 ErrorFound = true; 5044 continue; 5045 } 5046 Dim = Result.get(); 5047 } 5048 if (!Dim->isTypeDependent()) { 5049 ExprResult Result = 5050 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5051 if (Result.isInvalid()) { 5052 ErrorFound = true; 5053 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5054 << Dim->getSourceRange(); 5055 continue; 5056 } 5057 Dim = Result.get(); 5058 Expr::EvalResult EvResult; 5059 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5060 // OpenMP 5.0, [2.1.4 Array Shaping] 5061 // Each si is an integral type expression that must evaluate to a 5062 // positive integer. 5063 llvm::APSInt Value = EvResult.Val.getInt(); 5064 if (!Value.isStrictlyPositive()) { 5065 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5066 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5067 << Dim->getSourceRange(); 5068 ErrorFound = true; 5069 continue; 5070 } 5071 } 5072 } 5073 NewDims.push_back(Dim); 5074 } 5075 if (ErrorFound) 5076 return ExprError(); 5077 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5078 LParenLoc, RParenLoc, NewDims, Brackets); 5079 } 5080 5081 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5082 SourceLocation LLoc, SourceLocation RLoc, 5083 ArrayRef<OMPIteratorData> Data) { 5084 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5085 bool IsCorrect = true; 5086 for (const OMPIteratorData &D : Data) { 5087 TypeSourceInfo *TInfo = nullptr; 5088 SourceLocation StartLoc; 5089 QualType DeclTy; 5090 if (!D.Type.getAsOpaquePtr()) { 5091 // OpenMP 5.0, 2.1.6 Iterators 5092 // In an iterator-specifier, if the iterator-type is not specified then 5093 // the type of that iterator is of int type. 5094 DeclTy = Context.IntTy; 5095 StartLoc = D.DeclIdentLoc; 5096 } else { 5097 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5098 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5099 } 5100 5101 bool IsDeclTyDependent = DeclTy->isDependentType() || 5102 DeclTy->containsUnexpandedParameterPack() || 5103 DeclTy->isInstantiationDependentType(); 5104 if (!IsDeclTyDependent) { 5105 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5106 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5107 // The iterator-type must be an integral or pointer type. 5108 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5109 << DeclTy; 5110 IsCorrect = false; 5111 continue; 5112 } 5113 if (DeclTy.isConstant(Context)) { 5114 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5115 // The iterator-type must not be const qualified. 5116 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5117 << DeclTy; 5118 IsCorrect = false; 5119 continue; 5120 } 5121 } 5122 5123 // Iterator declaration. 5124 assert(D.DeclIdent && "Identifier expected."); 5125 // Always try to create iterator declarator to avoid extra error messages 5126 // about unknown declarations use. 5127 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5128 D.DeclIdent, DeclTy, TInfo, SC_None); 5129 VD->setImplicit(); 5130 if (S) { 5131 // Check for conflicting previous declaration. 5132 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5133 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5134 ForVisibleRedeclaration); 5135 Previous.suppressDiagnostics(); 5136 LookupName(Previous, S); 5137 5138 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5139 /*AllowInlineNamespace=*/false); 5140 if (!Previous.empty()) { 5141 NamedDecl *Old = Previous.getRepresentativeDecl(); 5142 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5143 Diag(Old->getLocation(), diag::note_previous_definition); 5144 } else { 5145 PushOnScopeChains(VD, S); 5146 } 5147 } else { 5148 CurContext->addDecl(VD); 5149 } 5150 Expr *Begin = D.Range.Begin; 5151 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5152 ExprResult BeginRes = 5153 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5154 Begin = BeginRes.get(); 5155 } 5156 Expr *End = D.Range.End; 5157 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5158 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5159 End = EndRes.get(); 5160 } 5161 Expr *Step = D.Range.Step; 5162 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5163 if (!Step->getType()->isIntegralType(Context)) { 5164 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5165 << Step << Step->getSourceRange(); 5166 IsCorrect = false; 5167 continue; 5168 } 5169 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5170 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5171 // If the step expression of a range-specification equals zero, the 5172 // behavior is unspecified. 5173 if (Result && Result->isNullValue()) { 5174 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5175 << Step << Step->getSourceRange(); 5176 IsCorrect = false; 5177 continue; 5178 } 5179 } 5180 if (!Begin || !End || !IsCorrect) { 5181 IsCorrect = false; 5182 continue; 5183 } 5184 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5185 IDElem.IteratorDecl = VD; 5186 IDElem.AssignmentLoc = D.AssignLoc; 5187 IDElem.Range.Begin = Begin; 5188 IDElem.Range.End = End; 5189 IDElem.Range.Step = Step; 5190 IDElem.ColonLoc = D.ColonLoc; 5191 IDElem.SecondColonLoc = D.SecColonLoc; 5192 } 5193 if (!IsCorrect) { 5194 // Invalidate all created iterator declarations if error is found. 5195 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5196 if (Decl *ID = D.IteratorDecl) 5197 ID->setInvalidDecl(); 5198 } 5199 return ExprError(); 5200 } 5201 SmallVector<OMPIteratorHelperData, 4> Helpers; 5202 if (!CurContext->isDependentContext()) { 5203 // Build number of ityeration for each iteration range. 5204 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5205 // ((Begini-Stepi-1-Endi) / -Stepi); 5206 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5207 // (Endi - Begini) 5208 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5209 D.Range.Begin); 5210 if(!Res.isUsable()) { 5211 IsCorrect = false; 5212 continue; 5213 } 5214 ExprResult St, St1; 5215 if (D.Range.Step) { 5216 St = D.Range.Step; 5217 // (Endi - Begini) + Stepi 5218 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5219 if (!Res.isUsable()) { 5220 IsCorrect = false; 5221 continue; 5222 } 5223 // (Endi - Begini) + Stepi - 1 5224 Res = 5225 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5226 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5227 if (!Res.isUsable()) { 5228 IsCorrect = false; 5229 continue; 5230 } 5231 // ((Endi - Begini) + Stepi - 1) / Stepi 5232 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5233 if (!Res.isUsable()) { 5234 IsCorrect = false; 5235 continue; 5236 } 5237 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5238 // (Begini - Endi) 5239 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5240 D.Range.Begin, D.Range.End); 5241 if (!Res1.isUsable()) { 5242 IsCorrect = false; 5243 continue; 5244 } 5245 // (Begini - Endi) - Stepi 5246 Res1 = 5247 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5248 if (!Res1.isUsable()) { 5249 IsCorrect = false; 5250 continue; 5251 } 5252 // (Begini - Endi) - Stepi - 1 5253 Res1 = 5254 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5255 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5256 if (!Res1.isUsable()) { 5257 IsCorrect = false; 5258 continue; 5259 } 5260 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5261 Res1 = 5262 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5263 if (!Res1.isUsable()) { 5264 IsCorrect = false; 5265 continue; 5266 } 5267 // Stepi > 0. 5268 ExprResult CmpRes = 5269 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5270 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5271 if (!CmpRes.isUsable()) { 5272 IsCorrect = false; 5273 continue; 5274 } 5275 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5276 Res.get(), Res1.get()); 5277 if (!Res.isUsable()) { 5278 IsCorrect = false; 5279 continue; 5280 } 5281 } 5282 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5283 if (!Res.isUsable()) { 5284 IsCorrect = false; 5285 continue; 5286 } 5287 5288 // Build counter update. 5289 // Build counter. 5290 auto *CounterVD = 5291 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5292 D.IteratorDecl->getBeginLoc(), nullptr, 5293 Res.get()->getType(), nullptr, SC_None); 5294 CounterVD->setImplicit(); 5295 ExprResult RefRes = 5296 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5297 D.IteratorDecl->getBeginLoc()); 5298 // Build counter update. 5299 // I = Begini + counter * Stepi; 5300 ExprResult UpdateRes; 5301 if (D.Range.Step) { 5302 UpdateRes = CreateBuiltinBinOp( 5303 D.AssignmentLoc, BO_Mul, 5304 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5305 } else { 5306 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5307 } 5308 if (!UpdateRes.isUsable()) { 5309 IsCorrect = false; 5310 continue; 5311 } 5312 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5313 UpdateRes.get()); 5314 if (!UpdateRes.isUsable()) { 5315 IsCorrect = false; 5316 continue; 5317 } 5318 ExprResult VDRes = 5319 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5320 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5321 D.IteratorDecl->getBeginLoc()); 5322 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5323 UpdateRes.get()); 5324 if (!UpdateRes.isUsable()) { 5325 IsCorrect = false; 5326 continue; 5327 } 5328 UpdateRes = 5329 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5330 if (!UpdateRes.isUsable()) { 5331 IsCorrect = false; 5332 continue; 5333 } 5334 ExprResult CounterUpdateRes = 5335 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5336 if (!CounterUpdateRes.isUsable()) { 5337 IsCorrect = false; 5338 continue; 5339 } 5340 CounterUpdateRes = 5341 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5342 if (!CounterUpdateRes.isUsable()) { 5343 IsCorrect = false; 5344 continue; 5345 } 5346 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5347 HD.CounterVD = CounterVD; 5348 HD.Upper = Res.get(); 5349 HD.Update = UpdateRes.get(); 5350 HD.CounterUpdate = CounterUpdateRes.get(); 5351 } 5352 } else { 5353 Helpers.assign(ID.size(), {}); 5354 } 5355 if (!IsCorrect) { 5356 // Invalidate all created iterator declarations if error is found. 5357 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5358 if (Decl *ID = D.IteratorDecl) 5359 ID->setInvalidDecl(); 5360 } 5361 return ExprError(); 5362 } 5363 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5364 LLoc, RLoc, ID, Helpers); 5365 } 5366 5367 ExprResult 5368 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5369 Expr *Idx, SourceLocation RLoc) { 5370 Expr *LHSExp = Base; 5371 Expr *RHSExp = Idx; 5372 5373 ExprValueKind VK = VK_LValue; 5374 ExprObjectKind OK = OK_Ordinary; 5375 5376 // Per C++ core issue 1213, the result is an xvalue if either operand is 5377 // a non-lvalue array, and an lvalue otherwise. 5378 if (getLangOpts().CPlusPlus11) { 5379 for (auto *Op : {LHSExp, RHSExp}) { 5380 Op = Op->IgnoreImplicit(); 5381 if (Op->getType()->isArrayType() && !Op->isLValue()) 5382 VK = VK_XValue; 5383 } 5384 } 5385 5386 // Perform default conversions. 5387 if (!LHSExp->getType()->getAs<VectorType>()) { 5388 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5389 if (Result.isInvalid()) 5390 return ExprError(); 5391 LHSExp = Result.get(); 5392 } 5393 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5394 if (Result.isInvalid()) 5395 return ExprError(); 5396 RHSExp = Result.get(); 5397 5398 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5399 5400 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5401 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5402 // in the subscript position. As a result, we need to derive the array base 5403 // and index from the expression types. 5404 Expr *BaseExpr, *IndexExpr; 5405 QualType ResultType; 5406 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5407 BaseExpr = LHSExp; 5408 IndexExpr = RHSExp; 5409 ResultType = Context.DependentTy; 5410 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5411 BaseExpr = LHSExp; 5412 IndexExpr = RHSExp; 5413 ResultType = PTy->getPointeeType(); 5414 } else if (const ObjCObjectPointerType *PTy = 5415 LHSTy->getAs<ObjCObjectPointerType>()) { 5416 BaseExpr = LHSExp; 5417 IndexExpr = RHSExp; 5418 5419 // Use custom logic if this should be the pseudo-object subscript 5420 // expression. 5421 if (!LangOpts.isSubscriptPointerArithmetic()) 5422 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5423 nullptr); 5424 5425 ResultType = PTy->getPointeeType(); 5426 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5427 // Handle the uncommon case of "123[Ptr]". 5428 BaseExpr = RHSExp; 5429 IndexExpr = LHSExp; 5430 ResultType = PTy->getPointeeType(); 5431 } else if (const ObjCObjectPointerType *PTy = 5432 RHSTy->getAs<ObjCObjectPointerType>()) { 5433 // Handle the uncommon case of "123[Ptr]". 5434 BaseExpr = RHSExp; 5435 IndexExpr = LHSExp; 5436 ResultType = PTy->getPointeeType(); 5437 if (!LangOpts.isSubscriptPointerArithmetic()) { 5438 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5439 << ResultType << BaseExpr->getSourceRange(); 5440 return ExprError(); 5441 } 5442 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5443 BaseExpr = LHSExp; // vectors: V[123] 5444 IndexExpr = RHSExp; 5445 // We apply C++ DR1213 to vector subscripting too. 5446 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5447 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5448 if (Materialized.isInvalid()) 5449 return ExprError(); 5450 LHSExp = Materialized.get(); 5451 } 5452 VK = LHSExp->getValueKind(); 5453 if (VK != VK_RValue) 5454 OK = OK_VectorComponent; 5455 5456 ResultType = VTy->getElementType(); 5457 QualType BaseType = BaseExpr->getType(); 5458 Qualifiers BaseQuals = BaseType.getQualifiers(); 5459 Qualifiers MemberQuals = ResultType.getQualifiers(); 5460 Qualifiers Combined = BaseQuals + MemberQuals; 5461 if (Combined != MemberQuals) 5462 ResultType = Context.getQualifiedType(ResultType, Combined); 5463 } else if (LHSTy->isArrayType()) { 5464 // If we see an array that wasn't promoted by 5465 // DefaultFunctionArrayLvalueConversion, it must be an array that 5466 // wasn't promoted because of the C90 rule that doesn't 5467 // allow promoting non-lvalue arrays. Warn, then 5468 // force the promotion here. 5469 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5470 << LHSExp->getSourceRange(); 5471 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5472 CK_ArrayToPointerDecay).get(); 5473 LHSTy = LHSExp->getType(); 5474 5475 BaseExpr = LHSExp; 5476 IndexExpr = RHSExp; 5477 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5478 } else if (RHSTy->isArrayType()) { 5479 // Same as previous, except for 123[f().a] case 5480 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5481 << RHSExp->getSourceRange(); 5482 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5483 CK_ArrayToPointerDecay).get(); 5484 RHSTy = RHSExp->getType(); 5485 5486 BaseExpr = RHSExp; 5487 IndexExpr = LHSExp; 5488 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5489 } else { 5490 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5491 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5492 } 5493 // C99 6.5.2.1p1 5494 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5495 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5496 << IndexExpr->getSourceRange()); 5497 5498 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5499 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5500 && !IndexExpr->isTypeDependent()) 5501 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5502 5503 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5504 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5505 // type. Note that Functions are not objects, and that (in C99 parlance) 5506 // incomplete types are not object types. 5507 if (ResultType->isFunctionType()) { 5508 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5509 << ResultType << BaseExpr->getSourceRange(); 5510 return ExprError(); 5511 } 5512 5513 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5514 // GNU extension: subscripting on pointer to void 5515 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5516 << BaseExpr->getSourceRange(); 5517 5518 // C forbids expressions of unqualified void type from being l-values. 5519 // See IsCForbiddenLValueType. 5520 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5521 } else if (!ResultType->isDependentType() && 5522 RequireCompleteSizedType( 5523 LLoc, ResultType, 5524 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5525 return ExprError(); 5526 5527 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5528 !ResultType.isCForbiddenLValueType()); 5529 5530 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5531 FunctionScopes.size() > 1) { 5532 if (auto *TT = 5533 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5534 for (auto I = FunctionScopes.rbegin(), 5535 E = std::prev(FunctionScopes.rend()); 5536 I != E; ++I) { 5537 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5538 if (CSI == nullptr) 5539 break; 5540 DeclContext *DC = nullptr; 5541 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5542 DC = LSI->CallOperator; 5543 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5544 DC = CRSI->TheCapturedDecl; 5545 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5546 DC = BSI->TheDecl; 5547 if (DC) { 5548 if (DC->containsDecl(TT->getDecl())) 5549 break; 5550 captureVariablyModifiedType( 5551 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5552 } 5553 } 5554 } 5555 } 5556 5557 return new (Context) 5558 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5559 } 5560 5561 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5562 ParmVarDecl *Param) { 5563 if (Param->hasUnparsedDefaultArg()) { 5564 // If we've already cleared out the location for the default argument, 5565 // that means we're parsing it right now. 5566 if (!UnparsedDefaultArgLocs.count(Param)) { 5567 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5568 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5569 Param->setInvalidDecl(); 5570 return true; 5571 } 5572 5573 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5574 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5575 Diag(UnparsedDefaultArgLocs[Param], 5576 diag::note_default_argument_declared_here); 5577 return true; 5578 } 5579 5580 if (Param->hasUninstantiatedDefaultArg() && 5581 InstantiateDefaultArgument(CallLoc, FD, Param)) 5582 return true; 5583 5584 assert(Param->hasInit() && "default argument but no initializer?"); 5585 5586 // If the default expression creates temporaries, we need to 5587 // push them to the current stack of expression temporaries so they'll 5588 // be properly destroyed. 5589 // FIXME: We should really be rebuilding the default argument with new 5590 // bound temporaries; see the comment in PR5810. 5591 // We don't need to do that with block decls, though, because 5592 // blocks in default argument expression can never capture anything. 5593 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5594 // Set the "needs cleanups" bit regardless of whether there are 5595 // any explicit objects. 5596 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5597 5598 // Append all the objects to the cleanup list. Right now, this 5599 // should always be a no-op, because blocks in default argument 5600 // expressions should never be able to capture anything. 5601 assert(!Init->getNumObjects() && 5602 "default argument expression has capturing blocks?"); 5603 } 5604 5605 // We already type-checked the argument, so we know it works. 5606 // Just mark all of the declarations in this potentially-evaluated expression 5607 // as being "referenced". 5608 EnterExpressionEvaluationContext EvalContext( 5609 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5610 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5611 /*SkipLocalVariables=*/true); 5612 return false; 5613 } 5614 5615 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5616 FunctionDecl *FD, ParmVarDecl *Param) { 5617 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5618 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5619 return ExprError(); 5620 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5621 } 5622 5623 Sema::VariadicCallType 5624 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5625 Expr *Fn) { 5626 if (Proto && Proto->isVariadic()) { 5627 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5628 return VariadicConstructor; 5629 else if (Fn && Fn->getType()->isBlockPointerType()) 5630 return VariadicBlock; 5631 else if (FDecl) { 5632 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5633 if (Method->isInstance()) 5634 return VariadicMethod; 5635 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5636 return VariadicMethod; 5637 return VariadicFunction; 5638 } 5639 return VariadicDoesNotApply; 5640 } 5641 5642 namespace { 5643 class FunctionCallCCC final : public FunctionCallFilterCCC { 5644 public: 5645 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5646 unsigned NumArgs, MemberExpr *ME) 5647 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5648 FunctionName(FuncName) {} 5649 5650 bool ValidateCandidate(const TypoCorrection &candidate) override { 5651 if (!candidate.getCorrectionSpecifier() || 5652 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5653 return false; 5654 } 5655 5656 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5657 } 5658 5659 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5660 return std::make_unique<FunctionCallCCC>(*this); 5661 } 5662 5663 private: 5664 const IdentifierInfo *const FunctionName; 5665 }; 5666 } 5667 5668 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5669 FunctionDecl *FDecl, 5670 ArrayRef<Expr *> Args) { 5671 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5672 DeclarationName FuncName = FDecl->getDeclName(); 5673 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5674 5675 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5676 if (TypoCorrection Corrected = S.CorrectTypo( 5677 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5678 S.getScopeForContext(S.CurContext), nullptr, CCC, 5679 Sema::CTK_ErrorRecovery)) { 5680 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5681 if (Corrected.isOverloaded()) { 5682 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5683 OverloadCandidateSet::iterator Best; 5684 for (NamedDecl *CD : Corrected) { 5685 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5686 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5687 OCS); 5688 } 5689 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5690 case OR_Success: 5691 ND = Best->FoundDecl; 5692 Corrected.setCorrectionDecl(ND); 5693 break; 5694 default: 5695 break; 5696 } 5697 } 5698 ND = ND->getUnderlyingDecl(); 5699 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5700 return Corrected; 5701 } 5702 } 5703 return TypoCorrection(); 5704 } 5705 5706 /// ConvertArgumentsForCall - Converts the arguments specified in 5707 /// Args/NumArgs to the parameter types of the function FDecl with 5708 /// function prototype Proto. Call is the call expression itself, and 5709 /// Fn is the function expression. For a C++ member function, this 5710 /// routine does not attempt to convert the object argument. Returns 5711 /// true if the call is ill-formed. 5712 bool 5713 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5714 FunctionDecl *FDecl, 5715 const FunctionProtoType *Proto, 5716 ArrayRef<Expr *> Args, 5717 SourceLocation RParenLoc, 5718 bool IsExecConfig) { 5719 // Bail out early if calling a builtin with custom typechecking. 5720 if (FDecl) 5721 if (unsigned ID = FDecl->getBuiltinID()) 5722 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5723 return false; 5724 5725 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5726 // assignment, to the types of the corresponding parameter, ... 5727 unsigned NumParams = Proto->getNumParams(); 5728 bool Invalid = false; 5729 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5730 unsigned FnKind = Fn->getType()->isBlockPointerType() 5731 ? 1 /* block */ 5732 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5733 : 0 /* function */); 5734 5735 // If too few arguments are available (and we don't have default 5736 // arguments for the remaining parameters), don't make the call. 5737 if (Args.size() < NumParams) { 5738 if (Args.size() < MinArgs) { 5739 TypoCorrection TC; 5740 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5741 unsigned diag_id = 5742 MinArgs == NumParams && !Proto->isVariadic() 5743 ? diag::err_typecheck_call_too_few_args_suggest 5744 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5745 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5746 << static_cast<unsigned>(Args.size()) 5747 << TC.getCorrectionRange()); 5748 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5749 Diag(RParenLoc, 5750 MinArgs == NumParams && !Proto->isVariadic() 5751 ? diag::err_typecheck_call_too_few_args_one 5752 : diag::err_typecheck_call_too_few_args_at_least_one) 5753 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5754 else 5755 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5756 ? diag::err_typecheck_call_too_few_args 5757 : diag::err_typecheck_call_too_few_args_at_least) 5758 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5759 << Fn->getSourceRange(); 5760 5761 // Emit the location of the prototype. 5762 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5763 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5764 5765 return true; 5766 } 5767 // We reserve space for the default arguments when we create 5768 // the call expression, before calling ConvertArgumentsForCall. 5769 assert((Call->getNumArgs() == NumParams) && 5770 "We should have reserved space for the default arguments before!"); 5771 } 5772 5773 // If too many are passed and not variadic, error on the extras and drop 5774 // them. 5775 if (Args.size() > NumParams) { 5776 if (!Proto->isVariadic()) { 5777 TypoCorrection TC; 5778 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5779 unsigned diag_id = 5780 MinArgs == NumParams && !Proto->isVariadic() 5781 ? diag::err_typecheck_call_too_many_args_suggest 5782 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5783 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5784 << static_cast<unsigned>(Args.size()) 5785 << TC.getCorrectionRange()); 5786 } else if (NumParams == 1 && FDecl && 5787 FDecl->getParamDecl(0)->getDeclName()) 5788 Diag(Args[NumParams]->getBeginLoc(), 5789 MinArgs == NumParams 5790 ? diag::err_typecheck_call_too_many_args_one 5791 : diag::err_typecheck_call_too_many_args_at_most_one) 5792 << FnKind << FDecl->getParamDecl(0) 5793 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5794 << SourceRange(Args[NumParams]->getBeginLoc(), 5795 Args.back()->getEndLoc()); 5796 else 5797 Diag(Args[NumParams]->getBeginLoc(), 5798 MinArgs == NumParams 5799 ? diag::err_typecheck_call_too_many_args 5800 : diag::err_typecheck_call_too_many_args_at_most) 5801 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5802 << Fn->getSourceRange() 5803 << SourceRange(Args[NumParams]->getBeginLoc(), 5804 Args.back()->getEndLoc()); 5805 5806 // Emit the location of the prototype. 5807 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5808 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5809 5810 // This deletes the extra arguments. 5811 Call->shrinkNumArgs(NumParams); 5812 return true; 5813 } 5814 } 5815 SmallVector<Expr *, 8> AllArgs; 5816 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5817 5818 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5819 AllArgs, CallType); 5820 if (Invalid) 5821 return true; 5822 unsigned TotalNumArgs = AllArgs.size(); 5823 for (unsigned i = 0; i < TotalNumArgs; ++i) 5824 Call->setArg(i, AllArgs[i]); 5825 5826 return false; 5827 } 5828 5829 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5830 const FunctionProtoType *Proto, 5831 unsigned FirstParam, ArrayRef<Expr *> Args, 5832 SmallVectorImpl<Expr *> &AllArgs, 5833 VariadicCallType CallType, bool AllowExplicit, 5834 bool IsListInitialization) { 5835 unsigned NumParams = Proto->getNumParams(); 5836 bool Invalid = false; 5837 size_t ArgIx = 0; 5838 // Continue to check argument types (even if we have too few/many args). 5839 for (unsigned i = FirstParam; i < NumParams; i++) { 5840 QualType ProtoArgType = Proto->getParamType(i); 5841 5842 Expr *Arg; 5843 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5844 if (ArgIx < Args.size()) { 5845 Arg = Args[ArgIx++]; 5846 5847 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5848 diag::err_call_incomplete_argument, Arg)) 5849 return true; 5850 5851 // Strip the unbridged-cast placeholder expression off, if applicable. 5852 bool CFAudited = false; 5853 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5854 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5855 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5856 Arg = stripARCUnbridgedCast(Arg); 5857 else if (getLangOpts().ObjCAutoRefCount && 5858 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5859 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5860 CFAudited = true; 5861 5862 if (Proto->getExtParameterInfo(i).isNoEscape()) 5863 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5864 BE->getBlockDecl()->setDoesNotEscape(); 5865 5866 InitializedEntity Entity = 5867 Param ? InitializedEntity::InitializeParameter(Context, Param, 5868 ProtoArgType) 5869 : InitializedEntity::InitializeParameter( 5870 Context, ProtoArgType, Proto->isParamConsumed(i)); 5871 5872 // Remember that parameter belongs to a CF audited API. 5873 if (CFAudited) 5874 Entity.setParameterCFAudited(); 5875 5876 ExprResult ArgE = PerformCopyInitialization( 5877 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5878 if (ArgE.isInvalid()) 5879 return true; 5880 5881 Arg = ArgE.getAs<Expr>(); 5882 } else { 5883 assert(Param && "can't use default arguments without a known callee"); 5884 5885 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5886 if (ArgExpr.isInvalid()) 5887 return true; 5888 5889 Arg = ArgExpr.getAs<Expr>(); 5890 } 5891 5892 // Check for array bounds violations for each argument to the call. This 5893 // check only triggers warnings when the argument isn't a more complex Expr 5894 // with its own checking, such as a BinaryOperator. 5895 CheckArrayAccess(Arg); 5896 5897 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5898 CheckStaticArrayArgument(CallLoc, Param, Arg); 5899 5900 AllArgs.push_back(Arg); 5901 } 5902 5903 // If this is a variadic call, handle args passed through "...". 5904 if (CallType != VariadicDoesNotApply) { 5905 // Assume that extern "C" functions with variadic arguments that 5906 // return __unknown_anytype aren't *really* variadic. 5907 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5908 FDecl->isExternC()) { 5909 for (Expr *A : Args.slice(ArgIx)) { 5910 QualType paramType; // ignored 5911 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5912 Invalid |= arg.isInvalid(); 5913 AllArgs.push_back(arg.get()); 5914 } 5915 5916 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5917 } else { 5918 for (Expr *A : Args.slice(ArgIx)) { 5919 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5920 Invalid |= Arg.isInvalid(); 5921 AllArgs.push_back(Arg.get()); 5922 } 5923 } 5924 5925 // Check for array bounds violations. 5926 for (Expr *A : Args.slice(ArgIx)) 5927 CheckArrayAccess(A); 5928 } 5929 return Invalid; 5930 } 5931 5932 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5933 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5934 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5935 TL = DTL.getOriginalLoc(); 5936 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5937 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5938 << ATL.getLocalSourceRange(); 5939 } 5940 5941 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5942 /// array parameter, check that it is non-null, and that if it is formed by 5943 /// array-to-pointer decay, the underlying array is sufficiently large. 5944 /// 5945 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5946 /// array type derivation, then for each call to the function, the value of the 5947 /// corresponding actual argument shall provide access to the first element of 5948 /// an array with at least as many elements as specified by the size expression. 5949 void 5950 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5951 ParmVarDecl *Param, 5952 const Expr *ArgExpr) { 5953 // Static array parameters are not supported in C++. 5954 if (!Param || getLangOpts().CPlusPlus) 5955 return; 5956 5957 QualType OrigTy = Param->getOriginalType(); 5958 5959 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5960 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5961 return; 5962 5963 if (ArgExpr->isNullPointerConstant(Context, 5964 Expr::NPC_NeverValueDependent)) { 5965 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5966 DiagnoseCalleeStaticArrayParam(*this, Param); 5967 return; 5968 } 5969 5970 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5971 if (!CAT) 5972 return; 5973 5974 const ConstantArrayType *ArgCAT = 5975 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5976 if (!ArgCAT) 5977 return; 5978 5979 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5980 ArgCAT->getElementType())) { 5981 if (ArgCAT->getSize().ult(CAT->getSize())) { 5982 Diag(CallLoc, diag::warn_static_array_too_small) 5983 << ArgExpr->getSourceRange() 5984 << (unsigned)ArgCAT->getSize().getZExtValue() 5985 << (unsigned)CAT->getSize().getZExtValue() << 0; 5986 DiagnoseCalleeStaticArrayParam(*this, Param); 5987 } 5988 return; 5989 } 5990 5991 Optional<CharUnits> ArgSize = 5992 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5993 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5994 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5995 Diag(CallLoc, diag::warn_static_array_too_small) 5996 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5997 << (unsigned)ParmSize->getQuantity() << 1; 5998 DiagnoseCalleeStaticArrayParam(*this, Param); 5999 } 6000 } 6001 6002 /// Given a function expression of unknown-any type, try to rebuild it 6003 /// to have a function type. 6004 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6005 6006 /// Is the given type a placeholder that we need to lower out 6007 /// immediately during argument processing? 6008 static bool isPlaceholderToRemoveAsArg(QualType type) { 6009 // Placeholders are never sugared. 6010 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6011 if (!placeholder) return false; 6012 6013 switch (placeholder->getKind()) { 6014 // Ignore all the non-placeholder types. 6015 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6016 case BuiltinType::Id: 6017 #include "clang/Basic/OpenCLImageTypes.def" 6018 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6019 case BuiltinType::Id: 6020 #include "clang/Basic/OpenCLExtensionTypes.def" 6021 // In practice we'll never use this, since all SVE types are sugared 6022 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6023 #define SVE_TYPE(Name, Id, SingletonId) \ 6024 case BuiltinType::Id: 6025 #include "clang/Basic/AArch64SVEACLETypes.def" 6026 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6027 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6028 #include "clang/AST/BuiltinTypes.def" 6029 return false; 6030 6031 // We cannot lower out overload sets; they might validly be resolved 6032 // by the call machinery. 6033 case BuiltinType::Overload: 6034 return false; 6035 6036 // Unbridged casts in ARC can be handled in some call positions and 6037 // should be left in place. 6038 case BuiltinType::ARCUnbridgedCast: 6039 return false; 6040 6041 // Pseudo-objects should be converted as soon as possible. 6042 case BuiltinType::PseudoObject: 6043 return true; 6044 6045 // The debugger mode could theoretically but currently does not try 6046 // to resolve unknown-typed arguments based on known parameter types. 6047 case BuiltinType::UnknownAny: 6048 return true; 6049 6050 // These are always invalid as call arguments and should be reported. 6051 case BuiltinType::BoundMember: 6052 case BuiltinType::BuiltinFn: 6053 case BuiltinType::IncompleteMatrixIdx: 6054 case BuiltinType::OMPArraySection: 6055 case BuiltinType::OMPArrayShaping: 6056 case BuiltinType::OMPIterator: 6057 return true; 6058 6059 } 6060 llvm_unreachable("bad builtin type kind"); 6061 } 6062 6063 /// Check an argument list for placeholders that we won't try to 6064 /// handle later. 6065 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6066 // Apply this processing to all the arguments at once instead of 6067 // dying at the first failure. 6068 bool hasInvalid = false; 6069 for (size_t i = 0, e = args.size(); i != e; i++) { 6070 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6071 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6072 if (result.isInvalid()) hasInvalid = true; 6073 else args[i] = result.get(); 6074 } else if (hasInvalid) { 6075 (void)S.CorrectDelayedTyposInExpr(args[i]); 6076 } 6077 } 6078 return hasInvalid; 6079 } 6080 6081 /// If a builtin function has a pointer argument with no explicit address 6082 /// space, then it should be able to accept a pointer to any address 6083 /// space as input. In order to do this, we need to replace the 6084 /// standard builtin declaration with one that uses the same address space 6085 /// as the call. 6086 /// 6087 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6088 /// it does not contain any pointer arguments without 6089 /// an address space qualifer. Otherwise the rewritten 6090 /// FunctionDecl is returned. 6091 /// TODO: Handle pointer return types. 6092 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6093 FunctionDecl *FDecl, 6094 MultiExprArg ArgExprs) { 6095 6096 QualType DeclType = FDecl->getType(); 6097 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6098 6099 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6100 ArgExprs.size() < FT->getNumParams()) 6101 return nullptr; 6102 6103 bool NeedsNewDecl = false; 6104 unsigned i = 0; 6105 SmallVector<QualType, 8> OverloadParams; 6106 6107 for (QualType ParamType : FT->param_types()) { 6108 6109 // Convert array arguments to pointer to simplify type lookup. 6110 ExprResult ArgRes = 6111 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6112 if (ArgRes.isInvalid()) 6113 return nullptr; 6114 Expr *Arg = ArgRes.get(); 6115 QualType ArgType = Arg->getType(); 6116 if (!ParamType->isPointerType() || 6117 ParamType.hasAddressSpace() || 6118 !ArgType->isPointerType() || 6119 !ArgType->getPointeeType().hasAddressSpace()) { 6120 OverloadParams.push_back(ParamType); 6121 continue; 6122 } 6123 6124 QualType PointeeType = ParamType->getPointeeType(); 6125 if (PointeeType.hasAddressSpace()) 6126 continue; 6127 6128 NeedsNewDecl = true; 6129 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6130 6131 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6132 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6133 } 6134 6135 if (!NeedsNewDecl) 6136 return nullptr; 6137 6138 FunctionProtoType::ExtProtoInfo EPI; 6139 EPI.Variadic = FT->isVariadic(); 6140 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6141 OverloadParams, EPI); 6142 DeclContext *Parent = FDecl->getParent(); 6143 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6144 FDecl->getLocation(), 6145 FDecl->getLocation(), 6146 FDecl->getIdentifier(), 6147 OverloadTy, 6148 /*TInfo=*/nullptr, 6149 SC_Extern, false, 6150 /*hasPrototype=*/true); 6151 SmallVector<ParmVarDecl*, 16> Params; 6152 FT = cast<FunctionProtoType>(OverloadTy); 6153 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6154 QualType ParamType = FT->getParamType(i); 6155 ParmVarDecl *Parm = 6156 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6157 SourceLocation(), nullptr, ParamType, 6158 /*TInfo=*/nullptr, SC_None, nullptr); 6159 Parm->setScopeInfo(0, i); 6160 Params.push_back(Parm); 6161 } 6162 OverloadDecl->setParams(Params); 6163 return OverloadDecl; 6164 } 6165 6166 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6167 FunctionDecl *Callee, 6168 MultiExprArg ArgExprs) { 6169 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6170 // similar attributes) really don't like it when functions are called with an 6171 // invalid number of args. 6172 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6173 /*PartialOverloading=*/false) && 6174 !Callee->isVariadic()) 6175 return; 6176 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6177 return; 6178 6179 if (const EnableIfAttr *Attr = 6180 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6181 S.Diag(Fn->getBeginLoc(), 6182 isa<CXXMethodDecl>(Callee) 6183 ? diag::err_ovl_no_viable_member_function_in_call 6184 : diag::err_ovl_no_viable_function_in_call) 6185 << Callee << Callee->getSourceRange(); 6186 S.Diag(Callee->getLocation(), 6187 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6188 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6189 return; 6190 } 6191 } 6192 6193 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6194 const UnresolvedMemberExpr *const UME, Sema &S) { 6195 6196 const auto GetFunctionLevelDCIfCXXClass = 6197 [](Sema &S) -> const CXXRecordDecl * { 6198 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6199 if (!DC || !DC->getParent()) 6200 return nullptr; 6201 6202 // If the call to some member function was made from within a member 6203 // function body 'M' return return 'M's parent. 6204 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6205 return MD->getParent()->getCanonicalDecl(); 6206 // else the call was made from within a default member initializer of a 6207 // class, so return the class. 6208 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6209 return RD->getCanonicalDecl(); 6210 return nullptr; 6211 }; 6212 // If our DeclContext is neither a member function nor a class (in the 6213 // case of a lambda in a default member initializer), we can't have an 6214 // enclosing 'this'. 6215 6216 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6217 if (!CurParentClass) 6218 return false; 6219 6220 // The naming class for implicit member functions call is the class in which 6221 // name lookup starts. 6222 const CXXRecordDecl *const NamingClass = 6223 UME->getNamingClass()->getCanonicalDecl(); 6224 assert(NamingClass && "Must have naming class even for implicit access"); 6225 6226 // If the unresolved member functions were found in a 'naming class' that is 6227 // related (either the same or derived from) to the class that contains the 6228 // member function that itself contained the implicit member access. 6229 6230 return CurParentClass == NamingClass || 6231 CurParentClass->isDerivedFrom(NamingClass); 6232 } 6233 6234 static void 6235 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6236 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6237 6238 if (!UME) 6239 return; 6240 6241 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6242 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6243 // already been captured, or if this is an implicit member function call (if 6244 // it isn't, an attempt to capture 'this' should already have been made). 6245 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6246 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6247 return; 6248 6249 // Check if the naming class in which the unresolved members were found is 6250 // related (same as or is a base of) to the enclosing class. 6251 6252 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6253 return; 6254 6255 6256 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6257 // If the enclosing function is not dependent, then this lambda is 6258 // capture ready, so if we can capture this, do so. 6259 if (!EnclosingFunctionCtx->isDependentContext()) { 6260 // If the current lambda and all enclosing lambdas can capture 'this' - 6261 // then go ahead and capture 'this' (since our unresolved overload set 6262 // contains at least one non-static member function). 6263 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6264 S.CheckCXXThisCapture(CallLoc); 6265 } else if (S.CurContext->isDependentContext()) { 6266 // ... since this is an implicit member reference, that might potentially 6267 // involve a 'this' capture, mark 'this' for potential capture in 6268 // enclosing lambdas. 6269 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6270 CurLSI->addPotentialThisCapture(CallLoc); 6271 } 6272 } 6273 6274 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6275 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6276 Expr *ExecConfig) { 6277 ExprResult Call = 6278 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6279 if (Call.isInvalid()) 6280 return Call; 6281 6282 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6283 // language modes. 6284 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6285 if (ULE->hasExplicitTemplateArgs() && 6286 ULE->decls_begin() == ULE->decls_end()) { 6287 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6288 ? diag::warn_cxx17_compat_adl_only_template_id 6289 : diag::ext_adl_only_template_id) 6290 << ULE->getName(); 6291 } 6292 } 6293 6294 if (LangOpts.OpenMP) 6295 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6296 ExecConfig); 6297 6298 return Call; 6299 } 6300 6301 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6302 /// This provides the location of the left/right parens and a list of comma 6303 /// locations. 6304 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6305 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6306 Expr *ExecConfig, bool IsExecConfig) { 6307 // Since this might be a postfix expression, get rid of ParenListExprs. 6308 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6309 if (Result.isInvalid()) return ExprError(); 6310 Fn = Result.get(); 6311 6312 if (checkArgsForPlaceholders(*this, ArgExprs)) 6313 return ExprError(); 6314 6315 if (getLangOpts().CPlusPlus) { 6316 // If this is a pseudo-destructor expression, build the call immediately. 6317 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6318 if (!ArgExprs.empty()) { 6319 // Pseudo-destructor calls should not have any arguments. 6320 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6321 << FixItHint::CreateRemoval( 6322 SourceRange(ArgExprs.front()->getBeginLoc(), 6323 ArgExprs.back()->getEndLoc())); 6324 } 6325 6326 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6327 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6328 } 6329 if (Fn->getType() == Context.PseudoObjectTy) { 6330 ExprResult result = CheckPlaceholderExpr(Fn); 6331 if (result.isInvalid()) return ExprError(); 6332 Fn = result.get(); 6333 } 6334 6335 // Determine whether this is a dependent call inside a C++ template, 6336 // in which case we won't do any semantic analysis now. 6337 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6338 if (ExecConfig) { 6339 return CUDAKernelCallExpr::Create( 6340 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6341 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6342 } else { 6343 6344 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6345 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6346 Fn->getBeginLoc()); 6347 6348 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6349 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6350 } 6351 } 6352 6353 // Determine whether this is a call to an object (C++ [over.call.object]). 6354 if (Fn->getType()->isRecordType()) 6355 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6356 RParenLoc); 6357 6358 if (Fn->getType() == Context.UnknownAnyTy) { 6359 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6360 if (result.isInvalid()) return ExprError(); 6361 Fn = result.get(); 6362 } 6363 6364 if (Fn->getType() == Context.BoundMemberTy) { 6365 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6366 RParenLoc); 6367 } 6368 } 6369 6370 // Check for overloaded calls. This can happen even in C due to extensions. 6371 if (Fn->getType() == Context.OverloadTy) { 6372 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6373 6374 // We aren't supposed to apply this logic if there's an '&' involved. 6375 if (!find.HasFormOfMemberPointer) { 6376 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6377 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6378 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6379 OverloadExpr *ovl = find.Expression; 6380 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6381 return BuildOverloadedCallExpr( 6382 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6383 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6384 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6385 RParenLoc); 6386 } 6387 } 6388 6389 // If we're directly calling a function, get the appropriate declaration. 6390 if (Fn->getType() == Context.UnknownAnyTy) { 6391 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6392 if (result.isInvalid()) return ExprError(); 6393 Fn = result.get(); 6394 } 6395 6396 Expr *NakedFn = Fn->IgnoreParens(); 6397 6398 bool CallingNDeclIndirectly = false; 6399 NamedDecl *NDecl = nullptr; 6400 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6401 if (UnOp->getOpcode() == UO_AddrOf) { 6402 CallingNDeclIndirectly = true; 6403 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6404 } 6405 } 6406 6407 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6408 NDecl = DRE->getDecl(); 6409 6410 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6411 if (FDecl && FDecl->getBuiltinID()) { 6412 // Rewrite the function decl for this builtin by replacing parameters 6413 // with no explicit address space with the address space of the arguments 6414 // in ArgExprs. 6415 if ((FDecl = 6416 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6417 NDecl = FDecl; 6418 Fn = DeclRefExpr::Create( 6419 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6420 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6421 nullptr, DRE->isNonOdrUse()); 6422 } 6423 } 6424 } else if (isa<MemberExpr>(NakedFn)) 6425 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6426 6427 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6428 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6429 FD, /*Complain=*/true, Fn->getBeginLoc())) 6430 return ExprError(); 6431 6432 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6433 return ExprError(); 6434 6435 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6436 } 6437 6438 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6439 ExecConfig, IsExecConfig); 6440 } 6441 6442 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6443 /// 6444 /// __builtin_astype( value, dst type ) 6445 /// 6446 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6447 SourceLocation BuiltinLoc, 6448 SourceLocation RParenLoc) { 6449 ExprValueKind VK = VK_RValue; 6450 ExprObjectKind OK = OK_Ordinary; 6451 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6452 QualType SrcTy = E->getType(); 6453 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6454 return ExprError(Diag(BuiltinLoc, 6455 diag::err_invalid_astype_of_different_size) 6456 << DstTy 6457 << SrcTy 6458 << E->getSourceRange()); 6459 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6460 } 6461 6462 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6463 /// provided arguments. 6464 /// 6465 /// __builtin_convertvector( value, dst type ) 6466 /// 6467 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6468 SourceLocation BuiltinLoc, 6469 SourceLocation RParenLoc) { 6470 TypeSourceInfo *TInfo; 6471 GetTypeFromParser(ParsedDestTy, &TInfo); 6472 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6473 } 6474 6475 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6476 /// i.e. an expression not of \p OverloadTy. The expression should 6477 /// unary-convert to an expression of function-pointer or 6478 /// block-pointer type. 6479 /// 6480 /// \param NDecl the declaration being called, if available 6481 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6482 SourceLocation LParenLoc, 6483 ArrayRef<Expr *> Args, 6484 SourceLocation RParenLoc, Expr *Config, 6485 bool IsExecConfig, ADLCallKind UsesADL) { 6486 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6487 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6488 6489 // Functions with 'interrupt' attribute cannot be called directly. 6490 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6491 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6492 return ExprError(); 6493 } 6494 6495 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6496 // so there's some risk when calling out to non-interrupt handler functions 6497 // that the callee might not preserve them. This is easy to diagnose here, 6498 // but can be very challenging to debug. 6499 if (auto *Caller = getCurFunctionDecl()) 6500 if (Caller->hasAttr<ARMInterruptAttr>()) { 6501 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6502 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6503 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6504 } 6505 6506 // Promote the function operand. 6507 // We special-case function promotion here because we only allow promoting 6508 // builtin functions to function pointers in the callee of a call. 6509 ExprResult Result; 6510 QualType ResultTy; 6511 if (BuiltinID && 6512 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6513 // Extract the return type from the (builtin) function pointer type. 6514 // FIXME Several builtins still have setType in 6515 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6516 // Builtins.def to ensure they are correct before removing setType calls. 6517 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6518 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6519 ResultTy = FDecl->getCallResultType(); 6520 } else { 6521 Result = CallExprUnaryConversions(Fn); 6522 ResultTy = Context.BoolTy; 6523 } 6524 if (Result.isInvalid()) 6525 return ExprError(); 6526 Fn = Result.get(); 6527 6528 // Check for a valid function type, but only if it is not a builtin which 6529 // requires custom type checking. These will be handled by 6530 // CheckBuiltinFunctionCall below just after creation of the call expression. 6531 const FunctionType *FuncT = nullptr; 6532 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6533 retry: 6534 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6535 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6536 // have type pointer to function". 6537 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6538 if (!FuncT) 6539 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6540 << Fn->getType() << Fn->getSourceRange()); 6541 } else if (const BlockPointerType *BPT = 6542 Fn->getType()->getAs<BlockPointerType>()) { 6543 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6544 } else { 6545 // Handle calls to expressions of unknown-any type. 6546 if (Fn->getType() == Context.UnknownAnyTy) { 6547 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6548 if (rewrite.isInvalid()) 6549 return ExprError(); 6550 Fn = rewrite.get(); 6551 goto retry; 6552 } 6553 6554 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6555 << Fn->getType() << Fn->getSourceRange()); 6556 } 6557 } 6558 6559 // Get the number of parameters in the function prototype, if any. 6560 // We will allocate space for max(Args.size(), NumParams) arguments 6561 // in the call expression. 6562 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6563 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6564 6565 CallExpr *TheCall; 6566 if (Config) { 6567 assert(UsesADL == ADLCallKind::NotADL && 6568 "CUDAKernelCallExpr should not use ADL"); 6569 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6570 Args, ResultTy, VK_RValue, RParenLoc, 6571 CurFPFeatureOverrides(), NumParams); 6572 } else { 6573 TheCall = 6574 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6575 CurFPFeatureOverrides(), NumParams, UsesADL); 6576 } 6577 6578 if (!getLangOpts().CPlusPlus) { 6579 // Forget about the nulled arguments since typo correction 6580 // do not handle them well. 6581 TheCall->shrinkNumArgs(Args.size()); 6582 // C cannot always handle TypoExpr nodes in builtin calls and direct 6583 // function calls as their argument checking don't necessarily handle 6584 // dependent types properly, so make sure any TypoExprs have been 6585 // dealt with. 6586 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6587 if (!Result.isUsable()) return ExprError(); 6588 CallExpr *TheOldCall = TheCall; 6589 TheCall = dyn_cast<CallExpr>(Result.get()); 6590 bool CorrectedTypos = TheCall != TheOldCall; 6591 if (!TheCall) return Result; 6592 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6593 6594 // A new call expression node was created if some typos were corrected. 6595 // However it may not have been constructed with enough storage. In this 6596 // case, rebuild the node with enough storage. The waste of space is 6597 // immaterial since this only happens when some typos were corrected. 6598 if (CorrectedTypos && Args.size() < NumParams) { 6599 if (Config) 6600 TheCall = CUDAKernelCallExpr::Create( 6601 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6602 RParenLoc, CurFPFeatureOverrides(), NumParams); 6603 else 6604 TheCall = 6605 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6606 CurFPFeatureOverrides(), NumParams, UsesADL); 6607 } 6608 // We can now handle the nulled arguments for the default arguments. 6609 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6610 } 6611 6612 // Bail out early if calling a builtin with custom type checking. 6613 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6614 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6615 6616 if (getLangOpts().CUDA) { 6617 if (Config) { 6618 // CUDA: Kernel calls must be to global functions 6619 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6620 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6621 << FDecl << Fn->getSourceRange()); 6622 6623 // CUDA: Kernel function must have 'void' return type 6624 if (!FuncT->getReturnType()->isVoidType() && 6625 !FuncT->getReturnType()->getAs<AutoType>() && 6626 !FuncT->getReturnType()->isInstantiationDependentType()) 6627 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6628 << Fn->getType() << Fn->getSourceRange()); 6629 } else { 6630 // CUDA: Calls to global functions must be configured 6631 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6632 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6633 << FDecl << Fn->getSourceRange()); 6634 } 6635 } 6636 6637 // Check for a valid return type 6638 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6639 FDecl)) 6640 return ExprError(); 6641 6642 // We know the result type of the call, set it. 6643 TheCall->setType(FuncT->getCallResultType(Context)); 6644 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6645 6646 if (Proto) { 6647 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6648 IsExecConfig)) 6649 return ExprError(); 6650 } else { 6651 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6652 6653 if (FDecl) { 6654 // Check if we have too few/too many template arguments, based 6655 // on our knowledge of the function definition. 6656 const FunctionDecl *Def = nullptr; 6657 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6658 Proto = Def->getType()->getAs<FunctionProtoType>(); 6659 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6660 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6661 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6662 } 6663 6664 // If the function we're calling isn't a function prototype, but we have 6665 // a function prototype from a prior declaratiom, use that prototype. 6666 if (!FDecl->hasPrototype()) 6667 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6668 } 6669 6670 // Promote the arguments (C99 6.5.2.2p6). 6671 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6672 Expr *Arg = Args[i]; 6673 6674 if (Proto && i < Proto->getNumParams()) { 6675 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6676 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6677 ExprResult ArgE = 6678 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6679 if (ArgE.isInvalid()) 6680 return true; 6681 6682 Arg = ArgE.getAs<Expr>(); 6683 6684 } else { 6685 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6686 6687 if (ArgE.isInvalid()) 6688 return true; 6689 6690 Arg = ArgE.getAs<Expr>(); 6691 } 6692 6693 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6694 diag::err_call_incomplete_argument, Arg)) 6695 return ExprError(); 6696 6697 TheCall->setArg(i, Arg); 6698 } 6699 } 6700 6701 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6702 if (!Method->isStatic()) 6703 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6704 << Fn->getSourceRange()); 6705 6706 // Check for sentinels 6707 if (NDecl) 6708 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6709 6710 // Warn for unions passing across security boundary (CMSE). 6711 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6712 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6713 if (const auto *RT = 6714 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6715 if (RT->getDecl()->isOrContainsUnion()) 6716 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6717 << 0 << i; 6718 } 6719 } 6720 } 6721 6722 // Do special checking on direct calls to functions. 6723 if (FDecl) { 6724 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6725 return ExprError(); 6726 6727 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6728 6729 if (BuiltinID) 6730 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6731 } else if (NDecl) { 6732 if (CheckPointerCall(NDecl, TheCall, Proto)) 6733 return ExprError(); 6734 } else { 6735 if (CheckOtherCall(TheCall, Proto)) 6736 return ExprError(); 6737 } 6738 6739 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6740 } 6741 6742 ExprResult 6743 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6744 SourceLocation RParenLoc, Expr *InitExpr) { 6745 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6746 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6747 6748 TypeSourceInfo *TInfo; 6749 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6750 if (!TInfo) 6751 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6752 6753 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6754 } 6755 6756 ExprResult 6757 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6758 SourceLocation RParenLoc, Expr *LiteralExpr) { 6759 QualType literalType = TInfo->getType(); 6760 6761 if (literalType->isArrayType()) { 6762 if (RequireCompleteSizedType( 6763 LParenLoc, Context.getBaseElementType(literalType), 6764 diag::err_array_incomplete_or_sizeless_type, 6765 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6766 return ExprError(); 6767 if (literalType->isVariableArrayType()) 6768 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6769 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6770 } else if (!literalType->isDependentType() && 6771 RequireCompleteType(LParenLoc, literalType, 6772 diag::err_typecheck_decl_incomplete_type, 6773 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6774 return ExprError(); 6775 6776 InitializedEntity Entity 6777 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6778 InitializationKind Kind 6779 = InitializationKind::CreateCStyleCast(LParenLoc, 6780 SourceRange(LParenLoc, RParenLoc), 6781 /*InitList=*/true); 6782 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6783 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6784 &literalType); 6785 if (Result.isInvalid()) 6786 return ExprError(); 6787 LiteralExpr = Result.get(); 6788 6789 bool isFileScope = !CurContext->isFunctionOrMethod(); 6790 6791 // In C, compound literals are l-values for some reason. 6792 // For GCC compatibility, in C++, file-scope array compound literals with 6793 // constant initializers are also l-values, and compound literals are 6794 // otherwise prvalues. 6795 // 6796 // (GCC also treats C++ list-initialized file-scope array prvalues with 6797 // constant initializers as l-values, but that's non-conforming, so we don't 6798 // follow it there.) 6799 // 6800 // FIXME: It would be better to handle the lvalue cases as materializing and 6801 // lifetime-extending a temporary object, but our materialized temporaries 6802 // representation only supports lifetime extension from a variable, not "out 6803 // of thin air". 6804 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6805 // is bound to the result of applying array-to-pointer decay to the compound 6806 // literal. 6807 // FIXME: GCC supports compound literals of reference type, which should 6808 // obviously have a value kind derived from the kind of reference involved. 6809 ExprValueKind VK = 6810 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6811 ? VK_RValue 6812 : VK_LValue; 6813 6814 if (isFileScope) 6815 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6816 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6817 Expr *Init = ILE->getInit(i); 6818 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6819 } 6820 6821 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6822 VK, LiteralExpr, isFileScope); 6823 if (isFileScope) { 6824 if (!LiteralExpr->isTypeDependent() && 6825 !LiteralExpr->isValueDependent() && 6826 !literalType->isDependentType()) // C99 6.5.2.5p3 6827 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6828 return ExprError(); 6829 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6830 literalType.getAddressSpace() != LangAS::Default) { 6831 // Embedded-C extensions to C99 6.5.2.5: 6832 // "If the compound literal occurs inside the body of a function, the 6833 // type name shall not be qualified by an address-space qualifier." 6834 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6835 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6836 return ExprError(); 6837 } 6838 6839 if (!isFileScope && !getLangOpts().CPlusPlus) { 6840 // Compound literals that have automatic storage duration are destroyed at 6841 // the end of the scope in C; in C++, they're just temporaries. 6842 6843 // Emit diagnostics if it is or contains a C union type that is non-trivial 6844 // to destruct. 6845 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6846 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6847 NTCUC_CompoundLiteral, NTCUK_Destruct); 6848 6849 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6850 if (literalType.isDestructedType()) { 6851 Cleanup.setExprNeedsCleanups(true); 6852 ExprCleanupObjects.push_back(E); 6853 getCurFunction()->setHasBranchProtectedScope(); 6854 } 6855 } 6856 6857 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6858 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6859 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6860 E->getInitializer()->getExprLoc()); 6861 6862 return MaybeBindToTemporary(E); 6863 } 6864 6865 ExprResult 6866 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6867 SourceLocation RBraceLoc) { 6868 // Only produce each kind of designated initialization diagnostic once. 6869 SourceLocation FirstDesignator; 6870 bool DiagnosedArrayDesignator = false; 6871 bool DiagnosedNestedDesignator = false; 6872 bool DiagnosedMixedDesignator = false; 6873 6874 // Check that any designated initializers are syntactically valid in the 6875 // current language mode. 6876 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6877 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6878 if (FirstDesignator.isInvalid()) 6879 FirstDesignator = DIE->getBeginLoc(); 6880 6881 if (!getLangOpts().CPlusPlus) 6882 break; 6883 6884 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6885 DiagnosedNestedDesignator = true; 6886 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6887 << DIE->getDesignatorsSourceRange(); 6888 } 6889 6890 for (auto &Desig : DIE->designators()) { 6891 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6892 DiagnosedArrayDesignator = true; 6893 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6894 << Desig.getSourceRange(); 6895 } 6896 } 6897 6898 if (!DiagnosedMixedDesignator && 6899 !isa<DesignatedInitExpr>(InitArgList[0])) { 6900 DiagnosedMixedDesignator = true; 6901 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6902 << DIE->getSourceRange(); 6903 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6904 << InitArgList[0]->getSourceRange(); 6905 } 6906 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6907 isa<DesignatedInitExpr>(InitArgList[0])) { 6908 DiagnosedMixedDesignator = true; 6909 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6910 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6911 << DIE->getSourceRange(); 6912 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6913 << InitArgList[I]->getSourceRange(); 6914 } 6915 } 6916 6917 if (FirstDesignator.isValid()) { 6918 // Only diagnose designated initiaization as a C++20 extension if we didn't 6919 // already diagnose use of (non-C++20) C99 designator syntax. 6920 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6921 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6922 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6923 ? diag::warn_cxx17_compat_designated_init 6924 : diag::ext_cxx_designated_init); 6925 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6926 Diag(FirstDesignator, diag::ext_designated_init); 6927 } 6928 } 6929 6930 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6931 } 6932 6933 ExprResult 6934 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6935 SourceLocation RBraceLoc) { 6936 // Semantic analysis for initializers is done by ActOnDeclarator() and 6937 // CheckInitializer() - it requires knowledge of the object being initialized. 6938 6939 // Immediately handle non-overload placeholders. Overloads can be 6940 // resolved contextually, but everything else here can't. 6941 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6942 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6943 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6944 6945 // Ignore failures; dropping the entire initializer list because 6946 // of one failure would be terrible for indexing/etc. 6947 if (result.isInvalid()) continue; 6948 6949 InitArgList[I] = result.get(); 6950 } 6951 } 6952 6953 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6954 RBraceLoc); 6955 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6956 return E; 6957 } 6958 6959 /// Do an explicit extend of the given block pointer if we're in ARC. 6960 void Sema::maybeExtendBlockObject(ExprResult &E) { 6961 assert(E.get()->getType()->isBlockPointerType()); 6962 assert(E.get()->isRValue()); 6963 6964 // Only do this in an r-value context. 6965 if (!getLangOpts().ObjCAutoRefCount) return; 6966 6967 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6968 CK_ARCExtendBlockObject, E.get(), 6969 /*base path*/ nullptr, VK_RValue); 6970 Cleanup.setExprNeedsCleanups(true); 6971 } 6972 6973 /// Prepare a conversion of the given expression to an ObjC object 6974 /// pointer type. 6975 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6976 QualType type = E.get()->getType(); 6977 if (type->isObjCObjectPointerType()) { 6978 return CK_BitCast; 6979 } else if (type->isBlockPointerType()) { 6980 maybeExtendBlockObject(E); 6981 return CK_BlockPointerToObjCPointerCast; 6982 } else { 6983 assert(type->isPointerType()); 6984 return CK_CPointerToObjCPointerCast; 6985 } 6986 } 6987 6988 /// Prepares for a scalar cast, performing all the necessary stages 6989 /// except the final cast and returning the kind required. 6990 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6991 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6992 // Also, callers should have filtered out the invalid cases with 6993 // pointers. Everything else should be possible. 6994 6995 QualType SrcTy = Src.get()->getType(); 6996 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6997 return CK_NoOp; 6998 6999 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7000 case Type::STK_MemberPointer: 7001 llvm_unreachable("member pointer type in C"); 7002 7003 case Type::STK_CPointer: 7004 case Type::STK_BlockPointer: 7005 case Type::STK_ObjCObjectPointer: 7006 switch (DestTy->getScalarTypeKind()) { 7007 case Type::STK_CPointer: { 7008 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7009 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7010 if (SrcAS != DestAS) 7011 return CK_AddressSpaceConversion; 7012 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7013 return CK_NoOp; 7014 return CK_BitCast; 7015 } 7016 case Type::STK_BlockPointer: 7017 return (SrcKind == Type::STK_BlockPointer 7018 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7019 case Type::STK_ObjCObjectPointer: 7020 if (SrcKind == Type::STK_ObjCObjectPointer) 7021 return CK_BitCast; 7022 if (SrcKind == Type::STK_CPointer) 7023 return CK_CPointerToObjCPointerCast; 7024 maybeExtendBlockObject(Src); 7025 return CK_BlockPointerToObjCPointerCast; 7026 case Type::STK_Bool: 7027 return CK_PointerToBoolean; 7028 case Type::STK_Integral: 7029 return CK_PointerToIntegral; 7030 case Type::STK_Floating: 7031 case Type::STK_FloatingComplex: 7032 case Type::STK_IntegralComplex: 7033 case Type::STK_MemberPointer: 7034 case Type::STK_FixedPoint: 7035 llvm_unreachable("illegal cast from pointer"); 7036 } 7037 llvm_unreachable("Should have returned before this"); 7038 7039 case Type::STK_FixedPoint: 7040 switch (DestTy->getScalarTypeKind()) { 7041 case Type::STK_FixedPoint: 7042 return CK_FixedPointCast; 7043 case Type::STK_Bool: 7044 return CK_FixedPointToBoolean; 7045 case Type::STK_Integral: 7046 return CK_FixedPointToIntegral; 7047 case Type::STK_Floating: 7048 case Type::STK_IntegralComplex: 7049 case Type::STK_FloatingComplex: 7050 Diag(Src.get()->getExprLoc(), 7051 diag::err_unimplemented_conversion_with_fixed_point_type) 7052 << DestTy; 7053 return CK_IntegralCast; 7054 case Type::STK_CPointer: 7055 case Type::STK_ObjCObjectPointer: 7056 case Type::STK_BlockPointer: 7057 case Type::STK_MemberPointer: 7058 llvm_unreachable("illegal cast to pointer type"); 7059 } 7060 llvm_unreachable("Should have returned before this"); 7061 7062 case Type::STK_Bool: // casting from bool is like casting from an integer 7063 case Type::STK_Integral: 7064 switch (DestTy->getScalarTypeKind()) { 7065 case Type::STK_CPointer: 7066 case Type::STK_ObjCObjectPointer: 7067 case Type::STK_BlockPointer: 7068 if (Src.get()->isNullPointerConstant(Context, 7069 Expr::NPC_ValueDependentIsNull)) 7070 return CK_NullToPointer; 7071 return CK_IntegralToPointer; 7072 case Type::STK_Bool: 7073 return CK_IntegralToBoolean; 7074 case Type::STK_Integral: 7075 return CK_IntegralCast; 7076 case Type::STK_Floating: 7077 return CK_IntegralToFloating; 7078 case Type::STK_IntegralComplex: 7079 Src = ImpCastExprToType(Src.get(), 7080 DestTy->castAs<ComplexType>()->getElementType(), 7081 CK_IntegralCast); 7082 return CK_IntegralRealToComplex; 7083 case Type::STK_FloatingComplex: 7084 Src = ImpCastExprToType(Src.get(), 7085 DestTy->castAs<ComplexType>()->getElementType(), 7086 CK_IntegralToFloating); 7087 return CK_FloatingRealToComplex; 7088 case Type::STK_MemberPointer: 7089 llvm_unreachable("member pointer type in C"); 7090 case Type::STK_FixedPoint: 7091 return CK_IntegralToFixedPoint; 7092 } 7093 llvm_unreachable("Should have returned before this"); 7094 7095 case Type::STK_Floating: 7096 switch (DestTy->getScalarTypeKind()) { 7097 case Type::STK_Floating: 7098 return CK_FloatingCast; 7099 case Type::STK_Bool: 7100 return CK_FloatingToBoolean; 7101 case Type::STK_Integral: 7102 return CK_FloatingToIntegral; 7103 case Type::STK_FloatingComplex: 7104 Src = ImpCastExprToType(Src.get(), 7105 DestTy->castAs<ComplexType>()->getElementType(), 7106 CK_FloatingCast); 7107 return CK_FloatingRealToComplex; 7108 case Type::STK_IntegralComplex: 7109 Src = ImpCastExprToType(Src.get(), 7110 DestTy->castAs<ComplexType>()->getElementType(), 7111 CK_FloatingToIntegral); 7112 return CK_IntegralRealToComplex; 7113 case Type::STK_CPointer: 7114 case Type::STK_ObjCObjectPointer: 7115 case Type::STK_BlockPointer: 7116 llvm_unreachable("valid float->pointer cast?"); 7117 case Type::STK_MemberPointer: 7118 llvm_unreachable("member pointer type in C"); 7119 case Type::STK_FixedPoint: 7120 Diag(Src.get()->getExprLoc(), 7121 diag::err_unimplemented_conversion_with_fixed_point_type) 7122 << SrcTy; 7123 return CK_IntegralCast; 7124 } 7125 llvm_unreachable("Should have returned before this"); 7126 7127 case Type::STK_FloatingComplex: 7128 switch (DestTy->getScalarTypeKind()) { 7129 case Type::STK_FloatingComplex: 7130 return CK_FloatingComplexCast; 7131 case Type::STK_IntegralComplex: 7132 return CK_FloatingComplexToIntegralComplex; 7133 case Type::STK_Floating: { 7134 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7135 if (Context.hasSameType(ET, DestTy)) 7136 return CK_FloatingComplexToReal; 7137 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7138 return CK_FloatingCast; 7139 } 7140 case Type::STK_Bool: 7141 return CK_FloatingComplexToBoolean; 7142 case Type::STK_Integral: 7143 Src = ImpCastExprToType(Src.get(), 7144 SrcTy->castAs<ComplexType>()->getElementType(), 7145 CK_FloatingComplexToReal); 7146 return CK_FloatingToIntegral; 7147 case Type::STK_CPointer: 7148 case Type::STK_ObjCObjectPointer: 7149 case Type::STK_BlockPointer: 7150 llvm_unreachable("valid complex float->pointer cast?"); 7151 case Type::STK_MemberPointer: 7152 llvm_unreachable("member pointer type in C"); 7153 case Type::STK_FixedPoint: 7154 Diag(Src.get()->getExprLoc(), 7155 diag::err_unimplemented_conversion_with_fixed_point_type) 7156 << SrcTy; 7157 return CK_IntegralCast; 7158 } 7159 llvm_unreachable("Should have returned before this"); 7160 7161 case Type::STK_IntegralComplex: 7162 switch (DestTy->getScalarTypeKind()) { 7163 case Type::STK_FloatingComplex: 7164 return CK_IntegralComplexToFloatingComplex; 7165 case Type::STK_IntegralComplex: 7166 return CK_IntegralComplexCast; 7167 case Type::STK_Integral: { 7168 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7169 if (Context.hasSameType(ET, DestTy)) 7170 return CK_IntegralComplexToReal; 7171 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7172 return CK_IntegralCast; 7173 } 7174 case Type::STK_Bool: 7175 return CK_IntegralComplexToBoolean; 7176 case Type::STK_Floating: 7177 Src = ImpCastExprToType(Src.get(), 7178 SrcTy->castAs<ComplexType>()->getElementType(), 7179 CK_IntegralComplexToReal); 7180 return CK_IntegralToFloating; 7181 case Type::STK_CPointer: 7182 case Type::STK_ObjCObjectPointer: 7183 case Type::STK_BlockPointer: 7184 llvm_unreachable("valid complex int->pointer cast?"); 7185 case Type::STK_MemberPointer: 7186 llvm_unreachable("member pointer type in C"); 7187 case Type::STK_FixedPoint: 7188 Diag(Src.get()->getExprLoc(), 7189 diag::err_unimplemented_conversion_with_fixed_point_type) 7190 << SrcTy; 7191 return CK_IntegralCast; 7192 } 7193 llvm_unreachable("Should have returned before this"); 7194 } 7195 7196 llvm_unreachable("Unhandled scalar cast"); 7197 } 7198 7199 static bool breakDownVectorType(QualType type, uint64_t &len, 7200 QualType &eltType) { 7201 // Vectors are simple. 7202 if (const VectorType *vecType = type->getAs<VectorType>()) { 7203 len = vecType->getNumElements(); 7204 eltType = vecType->getElementType(); 7205 assert(eltType->isScalarType()); 7206 return true; 7207 } 7208 7209 // We allow lax conversion to and from non-vector types, but only if 7210 // they're real types (i.e. non-complex, non-pointer scalar types). 7211 if (!type->isRealType()) return false; 7212 7213 len = 1; 7214 eltType = type; 7215 return true; 7216 } 7217 7218 /// Are the two types lax-compatible vector types? That is, given 7219 /// that one of them is a vector, do they have equal storage sizes, 7220 /// where the storage size is the number of elements times the element 7221 /// size? 7222 /// 7223 /// This will also return false if either of the types is neither a 7224 /// vector nor a real type. 7225 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7226 assert(destTy->isVectorType() || srcTy->isVectorType()); 7227 7228 // Disallow lax conversions between scalars and ExtVectors (these 7229 // conversions are allowed for other vector types because common headers 7230 // depend on them). Most scalar OP ExtVector cases are handled by the 7231 // splat path anyway, which does what we want (convert, not bitcast). 7232 // What this rules out for ExtVectors is crazy things like char4*float. 7233 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7234 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7235 7236 uint64_t srcLen, destLen; 7237 QualType srcEltTy, destEltTy; 7238 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7239 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7240 7241 // ASTContext::getTypeSize will return the size rounded up to a 7242 // power of 2, so instead of using that, we need to use the raw 7243 // element size multiplied by the element count. 7244 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7245 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7246 7247 return (srcLen * srcEltSize == destLen * destEltSize); 7248 } 7249 7250 /// Is this a legal conversion between two types, one of which is 7251 /// known to be a vector type? 7252 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7253 assert(destTy->isVectorType() || srcTy->isVectorType()); 7254 7255 switch (Context.getLangOpts().getLaxVectorConversions()) { 7256 case LangOptions::LaxVectorConversionKind::None: 7257 return false; 7258 7259 case LangOptions::LaxVectorConversionKind::Integer: 7260 if (!srcTy->isIntegralOrEnumerationType()) { 7261 auto *Vec = srcTy->getAs<VectorType>(); 7262 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7263 return false; 7264 } 7265 if (!destTy->isIntegralOrEnumerationType()) { 7266 auto *Vec = destTy->getAs<VectorType>(); 7267 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7268 return false; 7269 } 7270 // OK, integer (vector) -> integer (vector) bitcast. 7271 break; 7272 7273 case LangOptions::LaxVectorConversionKind::All: 7274 break; 7275 } 7276 7277 return areLaxCompatibleVectorTypes(srcTy, destTy); 7278 } 7279 7280 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7281 CastKind &Kind) { 7282 assert(VectorTy->isVectorType() && "Not a vector type!"); 7283 7284 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7285 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7286 return Diag(R.getBegin(), 7287 Ty->isVectorType() ? 7288 diag::err_invalid_conversion_between_vectors : 7289 diag::err_invalid_conversion_between_vector_and_integer) 7290 << VectorTy << Ty << R; 7291 } else 7292 return Diag(R.getBegin(), 7293 diag::err_invalid_conversion_between_vector_and_scalar) 7294 << VectorTy << Ty << R; 7295 7296 Kind = CK_BitCast; 7297 return false; 7298 } 7299 7300 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7301 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7302 7303 if (DestElemTy == SplattedExpr->getType()) 7304 return SplattedExpr; 7305 7306 assert(DestElemTy->isFloatingType() || 7307 DestElemTy->isIntegralOrEnumerationType()); 7308 7309 CastKind CK; 7310 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7311 // OpenCL requires that we convert `true` boolean expressions to -1, but 7312 // only when splatting vectors. 7313 if (DestElemTy->isFloatingType()) { 7314 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7315 // in two steps: boolean to signed integral, then to floating. 7316 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7317 CK_BooleanToSignedIntegral); 7318 SplattedExpr = CastExprRes.get(); 7319 CK = CK_IntegralToFloating; 7320 } else { 7321 CK = CK_BooleanToSignedIntegral; 7322 } 7323 } else { 7324 ExprResult CastExprRes = SplattedExpr; 7325 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7326 if (CastExprRes.isInvalid()) 7327 return ExprError(); 7328 SplattedExpr = CastExprRes.get(); 7329 } 7330 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7331 } 7332 7333 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7334 Expr *CastExpr, CastKind &Kind) { 7335 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7336 7337 QualType SrcTy = CastExpr->getType(); 7338 7339 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7340 // an ExtVectorType. 7341 // In OpenCL, casts between vectors of different types are not allowed. 7342 // (See OpenCL 6.2). 7343 if (SrcTy->isVectorType()) { 7344 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7345 (getLangOpts().OpenCL && 7346 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7347 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7348 << DestTy << SrcTy << R; 7349 return ExprError(); 7350 } 7351 Kind = CK_BitCast; 7352 return CastExpr; 7353 } 7354 7355 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7356 // conversion will take place first from scalar to elt type, and then 7357 // splat from elt type to vector. 7358 if (SrcTy->isPointerType()) 7359 return Diag(R.getBegin(), 7360 diag::err_invalid_conversion_between_vector_and_scalar) 7361 << DestTy << SrcTy << R; 7362 7363 Kind = CK_VectorSplat; 7364 return prepareVectorSplat(DestTy, CastExpr); 7365 } 7366 7367 ExprResult 7368 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7369 Declarator &D, ParsedType &Ty, 7370 SourceLocation RParenLoc, Expr *CastExpr) { 7371 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7372 "ActOnCastExpr(): missing type or expr"); 7373 7374 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7375 if (D.isInvalidType()) 7376 return ExprError(); 7377 7378 if (getLangOpts().CPlusPlus) { 7379 // Check that there are no default arguments (C++ only). 7380 CheckExtraCXXDefaultArguments(D); 7381 } else { 7382 // Make sure any TypoExprs have been dealt with. 7383 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7384 if (!Res.isUsable()) 7385 return ExprError(); 7386 CastExpr = Res.get(); 7387 } 7388 7389 checkUnusedDeclAttributes(D); 7390 7391 QualType castType = castTInfo->getType(); 7392 Ty = CreateParsedType(castType, castTInfo); 7393 7394 bool isVectorLiteral = false; 7395 7396 // Check for an altivec or OpenCL literal, 7397 // i.e. all the elements are integer constants. 7398 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7399 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7400 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7401 && castType->isVectorType() && (PE || PLE)) { 7402 if (PLE && PLE->getNumExprs() == 0) { 7403 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7404 return ExprError(); 7405 } 7406 if (PE || PLE->getNumExprs() == 1) { 7407 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7408 if (!E->getType()->isVectorType()) 7409 isVectorLiteral = true; 7410 } 7411 else 7412 isVectorLiteral = true; 7413 } 7414 7415 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7416 // then handle it as such. 7417 if (isVectorLiteral) 7418 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7419 7420 // If the Expr being casted is a ParenListExpr, handle it specially. 7421 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7422 // sequence of BinOp comma operators. 7423 if (isa<ParenListExpr>(CastExpr)) { 7424 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7425 if (Result.isInvalid()) return ExprError(); 7426 CastExpr = Result.get(); 7427 } 7428 7429 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7430 !getSourceManager().isInSystemMacro(LParenLoc)) 7431 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7432 7433 CheckTollFreeBridgeCast(castType, CastExpr); 7434 7435 CheckObjCBridgeRelatedCast(castType, CastExpr); 7436 7437 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7438 7439 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7440 } 7441 7442 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7443 SourceLocation RParenLoc, Expr *E, 7444 TypeSourceInfo *TInfo) { 7445 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7446 "Expected paren or paren list expression"); 7447 7448 Expr **exprs; 7449 unsigned numExprs; 7450 Expr *subExpr; 7451 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7452 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7453 LiteralLParenLoc = PE->getLParenLoc(); 7454 LiteralRParenLoc = PE->getRParenLoc(); 7455 exprs = PE->getExprs(); 7456 numExprs = PE->getNumExprs(); 7457 } else { // isa<ParenExpr> by assertion at function entrance 7458 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7459 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7460 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7461 exprs = &subExpr; 7462 numExprs = 1; 7463 } 7464 7465 QualType Ty = TInfo->getType(); 7466 assert(Ty->isVectorType() && "Expected vector type"); 7467 7468 SmallVector<Expr *, 8> initExprs; 7469 const VectorType *VTy = Ty->castAs<VectorType>(); 7470 unsigned numElems = VTy->getNumElements(); 7471 7472 // '(...)' form of vector initialization in AltiVec: the number of 7473 // initializers must be one or must match the size of the vector. 7474 // If a single value is specified in the initializer then it will be 7475 // replicated to all the components of the vector 7476 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7477 // The number of initializers must be one or must match the size of the 7478 // vector. If a single value is specified in the initializer then it will 7479 // be replicated to all the components of the vector 7480 if (numExprs == 1) { 7481 QualType ElemTy = VTy->getElementType(); 7482 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7483 if (Literal.isInvalid()) 7484 return ExprError(); 7485 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7486 PrepareScalarCast(Literal, ElemTy)); 7487 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7488 } 7489 else if (numExprs < numElems) { 7490 Diag(E->getExprLoc(), 7491 diag::err_incorrect_number_of_vector_initializers); 7492 return ExprError(); 7493 } 7494 else 7495 initExprs.append(exprs, exprs + numExprs); 7496 } 7497 else { 7498 // For OpenCL, when the number of initializers is a single value, 7499 // it will be replicated to all components of the vector. 7500 if (getLangOpts().OpenCL && 7501 VTy->getVectorKind() == VectorType::GenericVector && 7502 numExprs == 1) { 7503 QualType ElemTy = VTy->getElementType(); 7504 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7505 if (Literal.isInvalid()) 7506 return ExprError(); 7507 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7508 PrepareScalarCast(Literal, ElemTy)); 7509 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7510 } 7511 7512 initExprs.append(exprs, exprs + numExprs); 7513 } 7514 // FIXME: This means that pretty-printing the final AST will produce curly 7515 // braces instead of the original commas. 7516 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7517 initExprs, LiteralRParenLoc); 7518 initE->setType(Ty); 7519 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7520 } 7521 7522 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7523 /// the ParenListExpr into a sequence of comma binary operators. 7524 ExprResult 7525 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7526 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7527 if (!E) 7528 return OrigExpr; 7529 7530 ExprResult Result(E->getExpr(0)); 7531 7532 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7533 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7534 E->getExpr(i)); 7535 7536 if (Result.isInvalid()) return ExprError(); 7537 7538 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7539 } 7540 7541 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7542 SourceLocation R, 7543 MultiExprArg Val) { 7544 return ParenListExpr::Create(Context, L, Val, R); 7545 } 7546 7547 /// Emit a specialized diagnostic when one expression is a null pointer 7548 /// constant and the other is not a pointer. Returns true if a diagnostic is 7549 /// emitted. 7550 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7551 SourceLocation QuestionLoc) { 7552 Expr *NullExpr = LHSExpr; 7553 Expr *NonPointerExpr = RHSExpr; 7554 Expr::NullPointerConstantKind NullKind = 7555 NullExpr->isNullPointerConstant(Context, 7556 Expr::NPC_ValueDependentIsNotNull); 7557 7558 if (NullKind == Expr::NPCK_NotNull) { 7559 NullExpr = RHSExpr; 7560 NonPointerExpr = LHSExpr; 7561 NullKind = 7562 NullExpr->isNullPointerConstant(Context, 7563 Expr::NPC_ValueDependentIsNotNull); 7564 } 7565 7566 if (NullKind == Expr::NPCK_NotNull) 7567 return false; 7568 7569 if (NullKind == Expr::NPCK_ZeroExpression) 7570 return false; 7571 7572 if (NullKind == Expr::NPCK_ZeroLiteral) { 7573 // In this case, check to make sure that we got here from a "NULL" 7574 // string in the source code. 7575 NullExpr = NullExpr->IgnoreParenImpCasts(); 7576 SourceLocation loc = NullExpr->getExprLoc(); 7577 if (!findMacroSpelling(loc, "NULL")) 7578 return false; 7579 } 7580 7581 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7582 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7583 << NonPointerExpr->getType() << DiagType 7584 << NonPointerExpr->getSourceRange(); 7585 return true; 7586 } 7587 7588 /// Return false if the condition expression is valid, true otherwise. 7589 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7590 QualType CondTy = Cond->getType(); 7591 7592 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7593 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7594 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7595 << CondTy << Cond->getSourceRange(); 7596 return true; 7597 } 7598 7599 // C99 6.5.15p2 7600 if (CondTy->isScalarType()) return false; 7601 7602 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7603 << CondTy << Cond->getSourceRange(); 7604 return true; 7605 } 7606 7607 /// Handle when one or both operands are void type. 7608 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7609 ExprResult &RHS) { 7610 Expr *LHSExpr = LHS.get(); 7611 Expr *RHSExpr = RHS.get(); 7612 7613 if (!LHSExpr->getType()->isVoidType()) 7614 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7615 << RHSExpr->getSourceRange(); 7616 if (!RHSExpr->getType()->isVoidType()) 7617 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7618 << LHSExpr->getSourceRange(); 7619 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7620 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7621 return S.Context.VoidTy; 7622 } 7623 7624 /// Return false if the NullExpr can be promoted to PointerTy, 7625 /// true otherwise. 7626 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7627 QualType PointerTy) { 7628 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7629 !NullExpr.get()->isNullPointerConstant(S.Context, 7630 Expr::NPC_ValueDependentIsNull)) 7631 return true; 7632 7633 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7634 return false; 7635 } 7636 7637 /// Checks compatibility between two pointers and return the resulting 7638 /// type. 7639 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7640 ExprResult &RHS, 7641 SourceLocation Loc) { 7642 QualType LHSTy = LHS.get()->getType(); 7643 QualType RHSTy = RHS.get()->getType(); 7644 7645 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7646 // Two identical pointers types are always compatible. 7647 return LHSTy; 7648 } 7649 7650 QualType lhptee, rhptee; 7651 7652 // Get the pointee types. 7653 bool IsBlockPointer = false; 7654 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7655 lhptee = LHSBTy->getPointeeType(); 7656 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7657 IsBlockPointer = true; 7658 } else { 7659 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7660 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7661 } 7662 7663 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7664 // differently qualified versions of compatible types, the result type is 7665 // a pointer to an appropriately qualified version of the composite 7666 // type. 7667 7668 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7669 // clause doesn't make sense for our extensions. E.g. address space 2 should 7670 // be incompatible with address space 3: they may live on different devices or 7671 // anything. 7672 Qualifiers lhQual = lhptee.getQualifiers(); 7673 Qualifiers rhQual = rhptee.getQualifiers(); 7674 7675 LangAS ResultAddrSpace = LangAS::Default; 7676 LangAS LAddrSpace = lhQual.getAddressSpace(); 7677 LangAS RAddrSpace = rhQual.getAddressSpace(); 7678 7679 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7680 // spaces is disallowed. 7681 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7682 ResultAddrSpace = LAddrSpace; 7683 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7684 ResultAddrSpace = RAddrSpace; 7685 else { 7686 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7687 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7688 << RHS.get()->getSourceRange(); 7689 return QualType(); 7690 } 7691 7692 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7693 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7694 lhQual.removeCVRQualifiers(); 7695 rhQual.removeCVRQualifiers(); 7696 7697 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7698 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7699 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7700 // qual types are compatible iff 7701 // * corresponded types are compatible 7702 // * CVR qualifiers are equal 7703 // * address spaces are equal 7704 // Thus for conditional operator we merge CVR and address space unqualified 7705 // pointees and if there is a composite type we return a pointer to it with 7706 // merged qualifiers. 7707 LHSCastKind = 7708 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7709 RHSCastKind = 7710 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7711 lhQual.removeAddressSpace(); 7712 rhQual.removeAddressSpace(); 7713 7714 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7715 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7716 7717 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7718 7719 if (CompositeTy.isNull()) { 7720 // In this situation, we assume void* type. No especially good 7721 // reason, but this is what gcc does, and we do have to pick 7722 // to get a consistent AST. 7723 QualType incompatTy; 7724 incompatTy = S.Context.getPointerType( 7725 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7726 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7727 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7728 7729 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7730 // for casts between types with incompatible address space qualifiers. 7731 // For the following code the compiler produces casts between global and 7732 // local address spaces of the corresponded innermost pointees: 7733 // local int *global *a; 7734 // global int *global *b; 7735 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7736 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7737 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7738 << RHS.get()->getSourceRange(); 7739 7740 return incompatTy; 7741 } 7742 7743 // The pointer types are compatible. 7744 // In case of OpenCL ResultTy should have the address space qualifier 7745 // which is a superset of address spaces of both the 2nd and the 3rd 7746 // operands of the conditional operator. 7747 QualType ResultTy = [&, ResultAddrSpace]() { 7748 if (S.getLangOpts().OpenCL) { 7749 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7750 CompositeQuals.setAddressSpace(ResultAddrSpace); 7751 return S.Context 7752 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7753 .withCVRQualifiers(MergedCVRQual); 7754 } 7755 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7756 }(); 7757 if (IsBlockPointer) 7758 ResultTy = S.Context.getBlockPointerType(ResultTy); 7759 else 7760 ResultTy = S.Context.getPointerType(ResultTy); 7761 7762 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7763 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7764 return ResultTy; 7765 } 7766 7767 /// Return the resulting type when the operands are both block pointers. 7768 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7769 ExprResult &LHS, 7770 ExprResult &RHS, 7771 SourceLocation Loc) { 7772 QualType LHSTy = LHS.get()->getType(); 7773 QualType RHSTy = RHS.get()->getType(); 7774 7775 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7776 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7777 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7778 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7779 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7780 return destType; 7781 } 7782 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7783 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7784 << RHS.get()->getSourceRange(); 7785 return QualType(); 7786 } 7787 7788 // We have 2 block pointer types. 7789 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7790 } 7791 7792 /// Return the resulting type when the operands are both pointers. 7793 static QualType 7794 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7795 ExprResult &RHS, 7796 SourceLocation Loc) { 7797 // get the pointer types 7798 QualType LHSTy = LHS.get()->getType(); 7799 QualType RHSTy = RHS.get()->getType(); 7800 7801 // get the "pointed to" types 7802 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7803 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7804 7805 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7806 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7807 // Figure out necessary qualifiers (C99 6.5.15p6) 7808 QualType destPointee 7809 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7810 QualType destType = S.Context.getPointerType(destPointee); 7811 // Add qualifiers if necessary. 7812 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7813 // Promote to void*. 7814 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7815 return destType; 7816 } 7817 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7818 QualType destPointee 7819 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7820 QualType destType = S.Context.getPointerType(destPointee); 7821 // Add qualifiers if necessary. 7822 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7823 // Promote to void*. 7824 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7825 return destType; 7826 } 7827 7828 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7829 } 7830 7831 /// Return false if the first expression is not an integer and the second 7832 /// expression is not a pointer, true otherwise. 7833 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7834 Expr* PointerExpr, SourceLocation Loc, 7835 bool IsIntFirstExpr) { 7836 if (!PointerExpr->getType()->isPointerType() || 7837 !Int.get()->getType()->isIntegerType()) 7838 return false; 7839 7840 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7841 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7842 7843 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7844 << Expr1->getType() << Expr2->getType() 7845 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7846 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7847 CK_IntegralToPointer); 7848 return true; 7849 } 7850 7851 /// Simple conversion between integer and floating point types. 7852 /// 7853 /// Used when handling the OpenCL conditional operator where the 7854 /// condition is a vector while the other operands are scalar. 7855 /// 7856 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7857 /// types are either integer or floating type. Between the two 7858 /// operands, the type with the higher rank is defined as the "result 7859 /// type". The other operand needs to be promoted to the same type. No 7860 /// other type promotion is allowed. We cannot use 7861 /// UsualArithmeticConversions() for this purpose, since it always 7862 /// promotes promotable types. 7863 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7864 ExprResult &RHS, 7865 SourceLocation QuestionLoc) { 7866 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7867 if (LHS.isInvalid()) 7868 return QualType(); 7869 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7870 if (RHS.isInvalid()) 7871 return QualType(); 7872 7873 // For conversion purposes, we ignore any qualifiers. 7874 // For example, "const float" and "float" are equivalent. 7875 QualType LHSType = 7876 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7877 QualType RHSType = 7878 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7879 7880 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7881 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7882 << LHSType << LHS.get()->getSourceRange(); 7883 return QualType(); 7884 } 7885 7886 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7887 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7888 << RHSType << RHS.get()->getSourceRange(); 7889 return QualType(); 7890 } 7891 7892 // If both types are identical, no conversion is needed. 7893 if (LHSType == RHSType) 7894 return LHSType; 7895 7896 // Now handle "real" floating types (i.e. float, double, long double). 7897 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7898 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7899 /*IsCompAssign = */ false); 7900 7901 // Finally, we have two differing integer types. 7902 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7903 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7904 } 7905 7906 /// Convert scalar operands to a vector that matches the 7907 /// condition in length. 7908 /// 7909 /// Used when handling the OpenCL conditional operator where the 7910 /// condition is a vector while the other operands are scalar. 7911 /// 7912 /// We first compute the "result type" for the scalar operands 7913 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7914 /// into a vector of that type where the length matches the condition 7915 /// vector type. s6.11.6 requires that the element types of the result 7916 /// and the condition must have the same number of bits. 7917 static QualType 7918 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7919 QualType CondTy, SourceLocation QuestionLoc) { 7920 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7921 if (ResTy.isNull()) return QualType(); 7922 7923 const VectorType *CV = CondTy->getAs<VectorType>(); 7924 assert(CV); 7925 7926 // Determine the vector result type 7927 unsigned NumElements = CV->getNumElements(); 7928 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7929 7930 // Ensure that all types have the same number of bits 7931 if (S.Context.getTypeSize(CV->getElementType()) 7932 != S.Context.getTypeSize(ResTy)) { 7933 // Since VectorTy is created internally, it does not pretty print 7934 // with an OpenCL name. Instead, we just print a description. 7935 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7936 SmallString<64> Str; 7937 llvm::raw_svector_ostream OS(Str); 7938 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7939 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7940 << CondTy << OS.str(); 7941 return QualType(); 7942 } 7943 7944 // Convert operands to the vector result type 7945 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7946 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7947 7948 return VectorTy; 7949 } 7950 7951 /// Return false if this is a valid OpenCL condition vector 7952 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7953 SourceLocation QuestionLoc) { 7954 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7955 // integral type. 7956 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7957 assert(CondTy); 7958 QualType EleTy = CondTy->getElementType(); 7959 if (EleTy->isIntegerType()) return false; 7960 7961 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7962 << Cond->getType() << Cond->getSourceRange(); 7963 return true; 7964 } 7965 7966 /// Return false if the vector condition type and the vector 7967 /// result type are compatible. 7968 /// 7969 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7970 /// number of elements, and their element types have the same number 7971 /// of bits. 7972 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7973 SourceLocation QuestionLoc) { 7974 const VectorType *CV = CondTy->getAs<VectorType>(); 7975 const VectorType *RV = VecResTy->getAs<VectorType>(); 7976 assert(CV && RV); 7977 7978 if (CV->getNumElements() != RV->getNumElements()) { 7979 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7980 << CondTy << VecResTy; 7981 return true; 7982 } 7983 7984 QualType CVE = CV->getElementType(); 7985 QualType RVE = RV->getElementType(); 7986 7987 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7988 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7989 << CondTy << VecResTy; 7990 return true; 7991 } 7992 7993 return false; 7994 } 7995 7996 /// Return the resulting type for the conditional operator in 7997 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7998 /// s6.3.i) when the condition is a vector type. 7999 static QualType 8000 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8001 ExprResult &LHS, ExprResult &RHS, 8002 SourceLocation QuestionLoc) { 8003 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8004 if (Cond.isInvalid()) 8005 return QualType(); 8006 QualType CondTy = Cond.get()->getType(); 8007 8008 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8009 return QualType(); 8010 8011 // If either operand is a vector then find the vector type of the 8012 // result as specified in OpenCL v1.1 s6.3.i. 8013 if (LHS.get()->getType()->isVectorType() || 8014 RHS.get()->getType()->isVectorType()) { 8015 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8016 /*isCompAssign*/false, 8017 /*AllowBothBool*/true, 8018 /*AllowBoolConversions*/false); 8019 if (VecResTy.isNull()) return QualType(); 8020 // The result type must match the condition type as specified in 8021 // OpenCL v1.1 s6.11.6. 8022 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8023 return QualType(); 8024 return VecResTy; 8025 } 8026 8027 // Both operands are scalar. 8028 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8029 } 8030 8031 /// Return true if the Expr is block type 8032 static bool checkBlockType(Sema &S, const Expr *E) { 8033 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8034 QualType Ty = CE->getCallee()->getType(); 8035 if (Ty->isBlockPointerType()) { 8036 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8037 return true; 8038 } 8039 } 8040 return false; 8041 } 8042 8043 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8044 /// In that case, LHS = cond. 8045 /// C99 6.5.15 8046 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8047 ExprResult &RHS, ExprValueKind &VK, 8048 ExprObjectKind &OK, 8049 SourceLocation QuestionLoc) { 8050 8051 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8052 if (!LHSResult.isUsable()) return QualType(); 8053 LHS = LHSResult; 8054 8055 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8056 if (!RHSResult.isUsable()) return QualType(); 8057 RHS = RHSResult; 8058 8059 // C++ is sufficiently different to merit its own checker. 8060 if (getLangOpts().CPlusPlus) 8061 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8062 8063 VK = VK_RValue; 8064 OK = OK_Ordinary; 8065 8066 // The OpenCL operator with a vector condition is sufficiently 8067 // different to merit its own checker. 8068 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8069 Cond.get()->getType()->isExtVectorType()) 8070 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8071 8072 // First, check the condition. 8073 Cond = UsualUnaryConversions(Cond.get()); 8074 if (Cond.isInvalid()) 8075 return QualType(); 8076 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8077 return QualType(); 8078 8079 // Now check the two expressions. 8080 if (LHS.get()->getType()->isVectorType() || 8081 RHS.get()->getType()->isVectorType()) 8082 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8083 /*AllowBothBool*/true, 8084 /*AllowBoolConversions*/false); 8085 8086 QualType ResTy = 8087 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8088 if (LHS.isInvalid() || RHS.isInvalid()) 8089 return QualType(); 8090 8091 QualType LHSTy = LHS.get()->getType(); 8092 QualType RHSTy = RHS.get()->getType(); 8093 8094 // Diagnose attempts to convert between __float128 and long double where 8095 // such conversions currently can't be handled. 8096 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8097 Diag(QuestionLoc, 8098 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8099 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8100 return QualType(); 8101 } 8102 8103 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8104 // selection operator (?:). 8105 if (getLangOpts().OpenCL && 8106 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8107 return QualType(); 8108 } 8109 8110 // If both operands have arithmetic type, do the usual arithmetic conversions 8111 // to find a common type: C99 6.5.15p3,5. 8112 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8113 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8114 // different sizes, or between ExtInts and other types. 8115 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8116 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8117 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8118 << RHS.get()->getSourceRange(); 8119 return QualType(); 8120 } 8121 8122 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8123 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8124 8125 return ResTy; 8126 } 8127 8128 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8129 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8130 return LHSTy; 8131 } 8132 8133 // If both operands are the same structure or union type, the result is that 8134 // type. 8135 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8136 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8137 if (LHSRT->getDecl() == RHSRT->getDecl()) 8138 // "If both the operands have structure or union type, the result has 8139 // that type." This implies that CV qualifiers are dropped. 8140 return LHSTy.getUnqualifiedType(); 8141 // FIXME: Type of conditional expression must be complete in C mode. 8142 } 8143 8144 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8145 // The following || allows only one side to be void (a GCC-ism). 8146 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8147 return checkConditionalVoidType(*this, LHS, RHS); 8148 } 8149 8150 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8151 // the type of the other operand." 8152 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8153 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8154 8155 // All objective-c pointer type analysis is done here. 8156 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8157 QuestionLoc); 8158 if (LHS.isInvalid() || RHS.isInvalid()) 8159 return QualType(); 8160 if (!compositeType.isNull()) 8161 return compositeType; 8162 8163 8164 // Handle block pointer types. 8165 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8166 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8167 QuestionLoc); 8168 8169 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8170 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8171 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8172 QuestionLoc); 8173 8174 // GCC compatibility: soften pointer/integer mismatch. Note that 8175 // null pointers have been filtered out by this point. 8176 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8177 /*IsIntFirstExpr=*/true)) 8178 return RHSTy; 8179 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8180 /*IsIntFirstExpr=*/false)) 8181 return LHSTy; 8182 8183 // Allow ?: operations in which both operands have the same 8184 // built-in sizeless type. 8185 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8186 return LHSTy; 8187 8188 // Emit a better diagnostic if one of the expressions is a null pointer 8189 // constant and the other is not a pointer type. In this case, the user most 8190 // likely forgot to take the address of the other expression. 8191 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8192 return QualType(); 8193 8194 // Otherwise, the operands are not compatible. 8195 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8196 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8197 << RHS.get()->getSourceRange(); 8198 return QualType(); 8199 } 8200 8201 /// FindCompositeObjCPointerType - Helper method to find composite type of 8202 /// two objective-c pointer types of the two input expressions. 8203 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8204 SourceLocation QuestionLoc) { 8205 QualType LHSTy = LHS.get()->getType(); 8206 QualType RHSTy = RHS.get()->getType(); 8207 8208 // Handle things like Class and struct objc_class*. Here we case the result 8209 // to the pseudo-builtin, because that will be implicitly cast back to the 8210 // redefinition type if an attempt is made to access its fields. 8211 if (LHSTy->isObjCClassType() && 8212 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8213 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8214 return LHSTy; 8215 } 8216 if (RHSTy->isObjCClassType() && 8217 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8218 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8219 return RHSTy; 8220 } 8221 // And the same for struct objc_object* / id 8222 if (LHSTy->isObjCIdType() && 8223 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8224 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8225 return LHSTy; 8226 } 8227 if (RHSTy->isObjCIdType() && 8228 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8229 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8230 return RHSTy; 8231 } 8232 // And the same for struct objc_selector* / SEL 8233 if (Context.isObjCSelType(LHSTy) && 8234 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8235 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8236 return LHSTy; 8237 } 8238 if (Context.isObjCSelType(RHSTy) && 8239 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8240 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8241 return RHSTy; 8242 } 8243 // Check constraints for Objective-C object pointers types. 8244 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8245 8246 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8247 // Two identical object pointer types are always compatible. 8248 return LHSTy; 8249 } 8250 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8251 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8252 QualType compositeType = LHSTy; 8253 8254 // If both operands are interfaces and either operand can be 8255 // assigned to the other, use that type as the composite 8256 // type. This allows 8257 // xxx ? (A*) a : (B*) b 8258 // where B is a subclass of A. 8259 // 8260 // Additionally, as for assignment, if either type is 'id' 8261 // allow silent coercion. Finally, if the types are 8262 // incompatible then make sure to use 'id' as the composite 8263 // type so the result is acceptable for sending messages to. 8264 8265 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8266 // It could return the composite type. 8267 if (!(compositeType = 8268 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8269 // Nothing more to do. 8270 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8271 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8272 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8273 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8274 } else if ((LHSOPT->isObjCQualifiedIdType() || 8275 RHSOPT->isObjCQualifiedIdType()) && 8276 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8277 true)) { 8278 // Need to handle "id<xx>" explicitly. 8279 // GCC allows qualified id and any Objective-C type to devolve to 8280 // id. Currently localizing to here until clear this should be 8281 // part of ObjCQualifiedIdTypesAreCompatible. 8282 compositeType = Context.getObjCIdType(); 8283 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8284 compositeType = Context.getObjCIdType(); 8285 } else { 8286 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8287 << LHSTy << RHSTy 8288 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8289 QualType incompatTy = Context.getObjCIdType(); 8290 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8291 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8292 return incompatTy; 8293 } 8294 // The object pointer types are compatible. 8295 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8296 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8297 return compositeType; 8298 } 8299 // Check Objective-C object pointer types and 'void *' 8300 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8301 if (getLangOpts().ObjCAutoRefCount) { 8302 // ARC forbids the implicit conversion of object pointers to 'void *', 8303 // so these types are not compatible. 8304 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8305 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8306 LHS = RHS = true; 8307 return QualType(); 8308 } 8309 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8310 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8311 QualType destPointee 8312 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8313 QualType destType = Context.getPointerType(destPointee); 8314 // Add qualifiers if necessary. 8315 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8316 // Promote to void*. 8317 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8318 return destType; 8319 } 8320 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8321 if (getLangOpts().ObjCAutoRefCount) { 8322 // ARC forbids the implicit conversion of object pointers to 'void *', 8323 // so these types are not compatible. 8324 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8325 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8326 LHS = RHS = true; 8327 return QualType(); 8328 } 8329 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8330 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8331 QualType destPointee 8332 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8333 QualType destType = Context.getPointerType(destPointee); 8334 // Add qualifiers if necessary. 8335 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8336 // Promote to void*. 8337 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8338 return destType; 8339 } 8340 return QualType(); 8341 } 8342 8343 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8344 /// ParenRange in parentheses. 8345 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8346 const PartialDiagnostic &Note, 8347 SourceRange ParenRange) { 8348 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8349 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8350 EndLoc.isValid()) { 8351 Self.Diag(Loc, Note) 8352 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8353 << FixItHint::CreateInsertion(EndLoc, ")"); 8354 } else { 8355 // We can't display the parentheses, so just show the bare note. 8356 Self.Diag(Loc, Note) << ParenRange; 8357 } 8358 } 8359 8360 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8361 return BinaryOperator::isAdditiveOp(Opc) || 8362 BinaryOperator::isMultiplicativeOp(Opc) || 8363 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8364 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8365 // not any of the logical operators. Bitwise-xor is commonly used as a 8366 // logical-xor because there is no logical-xor operator. The logical 8367 // operators, including uses of xor, have a high false positive rate for 8368 // precedence warnings. 8369 } 8370 8371 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8372 /// expression, either using a built-in or overloaded operator, 8373 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8374 /// expression. 8375 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8376 Expr **RHSExprs) { 8377 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8378 E = E->IgnoreImpCasts(); 8379 E = E->IgnoreConversionOperator(); 8380 E = E->IgnoreImpCasts(); 8381 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8382 E = MTE->getSubExpr(); 8383 E = E->IgnoreImpCasts(); 8384 } 8385 8386 // Built-in binary operator. 8387 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8388 if (IsArithmeticOp(OP->getOpcode())) { 8389 *Opcode = OP->getOpcode(); 8390 *RHSExprs = OP->getRHS(); 8391 return true; 8392 } 8393 } 8394 8395 // Overloaded operator. 8396 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8397 if (Call->getNumArgs() != 2) 8398 return false; 8399 8400 // Make sure this is really a binary operator that is safe to pass into 8401 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8402 OverloadedOperatorKind OO = Call->getOperator(); 8403 if (OO < OO_Plus || OO > OO_Arrow || 8404 OO == OO_PlusPlus || OO == OO_MinusMinus) 8405 return false; 8406 8407 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8408 if (IsArithmeticOp(OpKind)) { 8409 *Opcode = OpKind; 8410 *RHSExprs = Call->getArg(1); 8411 return true; 8412 } 8413 } 8414 8415 return false; 8416 } 8417 8418 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8419 /// or is a logical expression such as (x==y) which has int type, but is 8420 /// commonly interpreted as boolean. 8421 static bool ExprLooksBoolean(Expr *E) { 8422 E = E->IgnoreParenImpCasts(); 8423 8424 if (E->getType()->isBooleanType()) 8425 return true; 8426 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8427 return OP->isComparisonOp() || OP->isLogicalOp(); 8428 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8429 return OP->getOpcode() == UO_LNot; 8430 if (E->getType()->isPointerType()) 8431 return true; 8432 // FIXME: What about overloaded operator calls returning "unspecified boolean 8433 // type"s (commonly pointer-to-members)? 8434 8435 return false; 8436 } 8437 8438 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8439 /// and binary operator are mixed in a way that suggests the programmer assumed 8440 /// the conditional operator has higher precedence, for example: 8441 /// "int x = a + someBinaryCondition ? 1 : 2". 8442 static void DiagnoseConditionalPrecedence(Sema &Self, 8443 SourceLocation OpLoc, 8444 Expr *Condition, 8445 Expr *LHSExpr, 8446 Expr *RHSExpr) { 8447 BinaryOperatorKind CondOpcode; 8448 Expr *CondRHS; 8449 8450 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8451 return; 8452 if (!ExprLooksBoolean(CondRHS)) 8453 return; 8454 8455 // The condition is an arithmetic binary expression, with a right- 8456 // hand side that looks boolean, so warn. 8457 8458 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8459 ? diag::warn_precedence_bitwise_conditional 8460 : diag::warn_precedence_conditional; 8461 8462 Self.Diag(OpLoc, DiagID) 8463 << Condition->getSourceRange() 8464 << BinaryOperator::getOpcodeStr(CondOpcode); 8465 8466 SuggestParentheses( 8467 Self, OpLoc, 8468 Self.PDiag(diag::note_precedence_silence) 8469 << BinaryOperator::getOpcodeStr(CondOpcode), 8470 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8471 8472 SuggestParentheses(Self, OpLoc, 8473 Self.PDiag(diag::note_precedence_conditional_first), 8474 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8475 } 8476 8477 /// Compute the nullability of a conditional expression. 8478 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8479 QualType LHSTy, QualType RHSTy, 8480 ASTContext &Ctx) { 8481 if (!ResTy->isAnyPointerType()) 8482 return ResTy; 8483 8484 auto GetNullability = [&Ctx](QualType Ty) { 8485 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8486 if (Kind) 8487 return *Kind; 8488 return NullabilityKind::Unspecified; 8489 }; 8490 8491 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8492 NullabilityKind MergedKind; 8493 8494 // Compute nullability of a binary conditional expression. 8495 if (IsBin) { 8496 if (LHSKind == NullabilityKind::NonNull) 8497 MergedKind = NullabilityKind::NonNull; 8498 else 8499 MergedKind = RHSKind; 8500 // Compute nullability of a normal conditional expression. 8501 } else { 8502 if (LHSKind == NullabilityKind::Nullable || 8503 RHSKind == NullabilityKind::Nullable) 8504 MergedKind = NullabilityKind::Nullable; 8505 else if (LHSKind == NullabilityKind::NonNull) 8506 MergedKind = RHSKind; 8507 else if (RHSKind == NullabilityKind::NonNull) 8508 MergedKind = LHSKind; 8509 else 8510 MergedKind = NullabilityKind::Unspecified; 8511 } 8512 8513 // Return if ResTy already has the correct nullability. 8514 if (GetNullability(ResTy) == MergedKind) 8515 return ResTy; 8516 8517 // Strip all nullability from ResTy. 8518 while (ResTy->getNullability(Ctx)) 8519 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8520 8521 // Create a new AttributedType with the new nullability kind. 8522 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8523 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8524 } 8525 8526 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8527 /// in the case of a the GNU conditional expr extension. 8528 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8529 SourceLocation ColonLoc, 8530 Expr *CondExpr, Expr *LHSExpr, 8531 Expr *RHSExpr) { 8532 if (!getLangOpts().CPlusPlus) { 8533 // C cannot handle TypoExpr nodes in the condition because it 8534 // doesn't handle dependent types properly, so make sure any TypoExprs have 8535 // been dealt with before checking the operands. 8536 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8537 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8538 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8539 8540 if (!CondResult.isUsable()) 8541 return ExprError(); 8542 8543 if (LHSExpr) { 8544 if (!LHSResult.isUsable()) 8545 return ExprError(); 8546 } 8547 8548 if (!RHSResult.isUsable()) 8549 return ExprError(); 8550 8551 CondExpr = CondResult.get(); 8552 LHSExpr = LHSResult.get(); 8553 RHSExpr = RHSResult.get(); 8554 } 8555 8556 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8557 // was the condition. 8558 OpaqueValueExpr *opaqueValue = nullptr; 8559 Expr *commonExpr = nullptr; 8560 if (!LHSExpr) { 8561 commonExpr = CondExpr; 8562 // Lower out placeholder types first. This is important so that we don't 8563 // try to capture a placeholder. This happens in few cases in C++; such 8564 // as Objective-C++'s dictionary subscripting syntax. 8565 if (commonExpr->hasPlaceholderType()) { 8566 ExprResult result = CheckPlaceholderExpr(commonExpr); 8567 if (!result.isUsable()) return ExprError(); 8568 commonExpr = result.get(); 8569 } 8570 // We usually want to apply unary conversions *before* saving, except 8571 // in the special case of a C++ l-value conditional. 8572 if (!(getLangOpts().CPlusPlus 8573 && !commonExpr->isTypeDependent() 8574 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8575 && commonExpr->isGLValue() 8576 && commonExpr->isOrdinaryOrBitFieldObject() 8577 && RHSExpr->isOrdinaryOrBitFieldObject() 8578 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8579 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8580 if (commonRes.isInvalid()) 8581 return ExprError(); 8582 commonExpr = commonRes.get(); 8583 } 8584 8585 // If the common expression is a class or array prvalue, materialize it 8586 // so that we can safely refer to it multiple times. 8587 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8588 commonExpr->getType()->isArrayType())) { 8589 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8590 if (MatExpr.isInvalid()) 8591 return ExprError(); 8592 commonExpr = MatExpr.get(); 8593 } 8594 8595 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8596 commonExpr->getType(), 8597 commonExpr->getValueKind(), 8598 commonExpr->getObjectKind(), 8599 commonExpr); 8600 LHSExpr = CondExpr = opaqueValue; 8601 } 8602 8603 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8604 ExprValueKind VK = VK_RValue; 8605 ExprObjectKind OK = OK_Ordinary; 8606 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8607 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8608 VK, OK, QuestionLoc); 8609 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8610 RHS.isInvalid()) 8611 return ExprError(); 8612 8613 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8614 RHS.get()); 8615 8616 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8617 8618 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8619 Context); 8620 8621 if (!commonExpr) 8622 return new (Context) 8623 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8624 RHS.get(), result, VK, OK); 8625 8626 return new (Context) BinaryConditionalOperator( 8627 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8628 ColonLoc, result, VK, OK); 8629 } 8630 8631 // Check if we have a conversion between incompatible cmse function pointer 8632 // types, that is, a conversion between a function pointer with the 8633 // cmse_nonsecure_call attribute and one without. 8634 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8635 QualType ToType) { 8636 if (const auto *ToFn = 8637 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8638 if (const auto *FromFn = 8639 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8640 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8641 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8642 8643 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8644 } 8645 } 8646 return false; 8647 } 8648 8649 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8650 // being closely modeled after the C99 spec:-). The odd characteristic of this 8651 // routine is it effectively iqnores the qualifiers on the top level pointee. 8652 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8653 // FIXME: add a couple examples in this comment. 8654 static Sema::AssignConvertType 8655 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8656 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8657 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8658 8659 // get the "pointed to" type (ignoring qualifiers at the top level) 8660 const Type *lhptee, *rhptee; 8661 Qualifiers lhq, rhq; 8662 std::tie(lhptee, lhq) = 8663 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8664 std::tie(rhptee, rhq) = 8665 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8666 8667 Sema::AssignConvertType ConvTy = Sema::Compatible; 8668 8669 // C99 6.5.16.1p1: This following citation is common to constraints 8670 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8671 // qualifiers of the type *pointed to* by the right; 8672 8673 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8674 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8675 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8676 // Ignore lifetime for further calculation. 8677 lhq.removeObjCLifetime(); 8678 rhq.removeObjCLifetime(); 8679 } 8680 8681 if (!lhq.compatiblyIncludes(rhq)) { 8682 // Treat address-space mismatches as fatal. 8683 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8684 return Sema::IncompatiblePointerDiscardsQualifiers; 8685 8686 // It's okay to add or remove GC or lifetime qualifiers when converting to 8687 // and from void*. 8688 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8689 .compatiblyIncludes( 8690 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8691 && (lhptee->isVoidType() || rhptee->isVoidType())) 8692 ; // keep old 8693 8694 // Treat lifetime mismatches as fatal. 8695 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8696 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8697 8698 // For GCC/MS compatibility, other qualifier mismatches are treated 8699 // as still compatible in C. 8700 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8701 } 8702 8703 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8704 // incomplete type and the other is a pointer to a qualified or unqualified 8705 // version of void... 8706 if (lhptee->isVoidType()) { 8707 if (rhptee->isIncompleteOrObjectType()) 8708 return ConvTy; 8709 8710 // As an extension, we allow cast to/from void* to function pointer. 8711 assert(rhptee->isFunctionType()); 8712 return Sema::FunctionVoidPointer; 8713 } 8714 8715 if (rhptee->isVoidType()) { 8716 if (lhptee->isIncompleteOrObjectType()) 8717 return ConvTy; 8718 8719 // As an extension, we allow cast to/from void* to function pointer. 8720 assert(lhptee->isFunctionType()); 8721 return Sema::FunctionVoidPointer; 8722 } 8723 8724 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8725 // unqualified versions of compatible types, ... 8726 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8727 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8728 // Check if the pointee types are compatible ignoring the sign. 8729 // We explicitly check for char so that we catch "char" vs 8730 // "unsigned char" on systems where "char" is unsigned. 8731 if (lhptee->isCharType()) 8732 ltrans = S.Context.UnsignedCharTy; 8733 else if (lhptee->hasSignedIntegerRepresentation()) 8734 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8735 8736 if (rhptee->isCharType()) 8737 rtrans = S.Context.UnsignedCharTy; 8738 else if (rhptee->hasSignedIntegerRepresentation()) 8739 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8740 8741 if (ltrans == rtrans) { 8742 // Types are compatible ignoring the sign. Qualifier incompatibility 8743 // takes priority over sign incompatibility because the sign 8744 // warning can be disabled. 8745 if (ConvTy != Sema::Compatible) 8746 return ConvTy; 8747 8748 return Sema::IncompatiblePointerSign; 8749 } 8750 8751 // If we are a multi-level pointer, it's possible that our issue is simply 8752 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8753 // the eventual target type is the same and the pointers have the same 8754 // level of indirection, this must be the issue. 8755 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8756 do { 8757 std::tie(lhptee, lhq) = 8758 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8759 std::tie(rhptee, rhq) = 8760 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8761 8762 // Inconsistent address spaces at this point is invalid, even if the 8763 // address spaces would be compatible. 8764 // FIXME: This doesn't catch address space mismatches for pointers of 8765 // different nesting levels, like: 8766 // __local int *** a; 8767 // int ** b = a; 8768 // It's not clear how to actually determine when such pointers are 8769 // invalidly incompatible. 8770 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8771 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8772 8773 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8774 8775 if (lhptee == rhptee) 8776 return Sema::IncompatibleNestedPointerQualifiers; 8777 } 8778 8779 // General pointer incompatibility takes priority over qualifiers. 8780 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8781 return Sema::IncompatibleFunctionPointer; 8782 return Sema::IncompatiblePointer; 8783 } 8784 if (!S.getLangOpts().CPlusPlus && 8785 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8786 return Sema::IncompatibleFunctionPointer; 8787 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8788 return Sema::IncompatibleFunctionPointer; 8789 return ConvTy; 8790 } 8791 8792 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8793 /// block pointer types are compatible or whether a block and normal pointer 8794 /// are compatible. It is more restrict than comparing two function pointer 8795 // types. 8796 static Sema::AssignConvertType 8797 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8798 QualType RHSType) { 8799 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8800 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8801 8802 QualType lhptee, rhptee; 8803 8804 // get the "pointed to" type (ignoring qualifiers at the top level) 8805 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8806 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8807 8808 // In C++, the types have to match exactly. 8809 if (S.getLangOpts().CPlusPlus) 8810 return Sema::IncompatibleBlockPointer; 8811 8812 Sema::AssignConvertType ConvTy = Sema::Compatible; 8813 8814 // For blocks we enforce that qualifiers are identical. 8815 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8816 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8817 if (S.getLangOpts().OpenCL) { 8818 LQuals.removeAddressSpace(); 8819 RQuals.removeAddressSpace(); 8820 } 8821 if (LQuals != RQuals) 8822 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8823 8824 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8825 // assignment. 8826 // The current behavior is similar to C++ lambdas. A block might be 8827 // assigned to a variable iff its return type and parameters are compatible 8828 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8829 // an assignment. Presumably it should behave in way that a function pointer 8830 // assignment does in C, so for each parameter and return type: 8831 // * CVR and address space of LHS should be a superset of CVR and address 8832 // space of RHS. 8833 // * unqualified types should be compatible. 8834 if (S.getLangOpts().OpenCL) { 8835 if (!S.Context.typesAreBlockPointerCompatible( 8836 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8837 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8838 return Sema::IncompatibleBlockPointer; 8839 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8840 return Sema::IncompatibleBlockPointer; 8841 8842 return ConvTy; 8843 } 8844 8845 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8846 /// for assignment compatibility. 8847 static Sema::AssignConvertType 8848 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8849 QualType RHSType) { 8850 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8851 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8852 8853 if (LHSType->isObjCBuiltinType()) { 8854 // Class is not compatible with ObjC object pointers. 8855 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8856 !RHSType->isObjCQualifiedClassType()) 8857 return Sema::IncompatiblePointer; 8858 return Sema::Compatible; 8859 } 8860 if (RHSType->isObjCBuiltinType()) { 8861 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8862 !LHSType->isObjCQualifiedClassType()) 8863 return Sema::IncompatiblePointer; 8864 return Sema::Compatible; 8865 } 8866 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8867 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8868 8869 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8870 // make an exception for id<P> 8871 !LHSType->isObjCQualifiedIdType()) 8872 return Sema::CompatiblePointerDiscardsQualifiers; 8873 8874 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8875 return Sema::Compatible; 8876 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8877 return Sema::IncompatibleObjCQualifiedId; 8878 return Sema::IncompatiblePointer; 8879 } 8880 8881 Sema::AssignConvertType 8882 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8883 QualType LHSType, QualType RHSType) { 8884 // Fake up an opaque expression. We don't actually care about what 8885 // cast operations are required, so if CheckAssignmentConstraints 8886 // adds casts to this they'll be wasted, but fortunately that doesn't 8887 // usually happen on valid code. 8888 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8889 ExprResult RHSPtr = &RHSExpr; 8890 CastKind K; 8891 8892 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8893 } 8894 8895 /// This helper function returns true if QT is a vector type that has element 8896 /// type ElementType. 8897 static bool isVector(QualType QT, QualType ElementType) { 8898 if (const VectorType *VT = QT->getAs<VectorType>()) 8899 return VT->getElementType().getCanonicalType() == ElementType; 8900 return false; 8901 } 8902 8903 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8904 /// has code to accommodate several GCC extensions when type checking 8905 /// pointers. Here are some objectionable examples that GCC considers warnings: 8906 /// 8907 /// int a, *pint; 8908 /// short *pshort; 8909 /// struct foo *pfoo; 8910 /// 8911 /// pint = pshort; // warning: assignment from incompatible pointer type 8912 /// a = pint; // warning: assignment makes integer from pointer without a cast 8913 /// pint = a; // warning: assignment makes pointer from integer without a cast 8914 /// pint = pfoo; // warning: assignment from incompatible pointer type 8915 /// 8916 /// As a result, the code for dealing with pointers is more complex than the 8917 /// C99 spec dictates. 8918 /// 8919 /// Sets 'Kind' for any result kind except Incompatible. 8920 Sema::AssignConvertType 8921 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8922 CastKind &Kind, bool ConvertRHS) { 8923 QualType RHSType = RHS.get()->getType(); 8924 QualType OrigLHSType = LHSType; 8925 8926 // Get canonical types. We're not formatting these types, just comparing 8927 // them. 8928 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8929 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8930 8931 // Common case: no conversion required. 8932 if (LHSType == RHSType) { 8933 Kind = CK_NoOp; 8934 return Compatible; 8935 } 8936 8937 // If we have an atomic type, try a non-atomic assignment, then just add an 8938 // atomic qualification step. 8939 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8940 Sema::AssignConvertType result = 8941 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8942 if (result != Compatible) 8943 return result; 8944 if (Kind != CK_NoOp && ConvertRHS) 8945 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8946 Kind = CK_NonAtomicToAtomic; 8947 return Compatible; 8948 } 8949 8950 // If the left-hand side is a reference type, then we are in a 8951 // (rare!) case where we've allowed the use of references in C, 8952 // e.g., as a parameter type in a built-in function. In this case, 8953 // just make sure that the type referenced is compatible with the 8954 // right-hand side type. The caller is responsible for adjusting 8955 // LHSType so that the resulting expression does not have reference 8956 // type. 8957 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8958 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8959 Kind = CK_LValueBitCast; 8960 return Compatible; 8961 } 8962 return Incompatible; 8963 } 8964 8965 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8966 // to the same ExtVector type. 8967 if (LHSType->isExtVectorType()) { 8968 if (RHSType->isExtVectorType()) 8969 return Incompatible; 8970 if (RHSType->isArithmeticType()) { 8971 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8972 if (ConvertRHS) 8973 RHS = prepareVectorSplat(LHSType, RHS.get()); 8974 Kind = CK_VectorSplat; 8975 return Compatible; 8976 } 8977 } 8978 8979 // Conversions to or from vector type. 8980 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8981 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8982 // Allow assignments of an AltiVec vector type to an equivalent GCC 8983 // vector type and vice versa 8984 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8985 Kind = CK_BitCast; 8986 return Compatible; 8987 } 8988 8989 // If we are allowing lax vector conversions, and LHS and RHS are both 8990 // vectors, the total size only needs to be the same. This is a bitcast; 8991 // no bits are changed but the result type is different. 8992 if (isLaxVectorConversion(RHSType, LHSType)) { 8993 Kind = CK_BitCast; 8994 return IncompatibleVectors; 8995 } 8996 } 8997 8998 // When the RHS comes from another lax conversion (e.g. binops between 8999 // scalars and vectors) the result is canonicalized as a vector. When the 9000 // LHS is also a vector, the lax is allowed by the condition above. Handle 9001 // the case where LHS is a scalar. 9002 if (LHSType->isScalarType()) { 9003 const VectorType *VecType = RHSType->getAs<VectorType>(); 9004 if (VecType && VecType->getNumElements() == 1 && 9005 isLaxVectorConversion(RHSType, LHSType)) { 9006 ExprResult *VecExpr = &RHS; 9007 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9008 Kind = CK_BitCast; 9009 return Compatible; 9010 } 9011 } 9012 9013 return Incompatible; 9014 } 9015 9016 // Diagnose attempts to convert between __float128 and long double where 9017 // such conversions currently can't be handled. 9018 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9019 return Incompatible; 9020 9021 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9022 // discards the imaginary part. 9023 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9024 !LHSType->getAs<ComplexType>()) 9025 return Incompatible; 9026 9027 // Arithmetic conversions. 9028 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9029 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9030 if (ConvertRHS) 9031 Kind = PrepareScalarCast(RHS, LHSType); 9032 return Compatible; 9033 } 9034 9035 // Conversions to normal pointers. 9036 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9037 // U* -> T* 9038 if (isa<PointerType>(RHSType)) { 9039 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9040 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9041 if (AddrSpaceL != AddrSpaceR) 9042 Kind = CK_AddressSpaceConversion; 9043 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9044 Kind = CK_NoOp; 9045 else 9046 Kind = CK_BitCast; 9047 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9048 } 9049 9050 // int -> T* 9051 if (RHSType->isIntegerType()) { 9052 Kind = CK_IntegralToPointer; // FIXME: null? 9053 return IntToPointer; 9054 } 9055 9056 // C pointers are not compatible with ObjC object pointers, 9057 // with two exceptions: 9058 if (isa<ObjCObjectPointerType>(RHSType)) { 9059 // - conversions to void* 9060 if (LHSPointer->getPointeeType()->isVoidType()) { 9061 Kind = CK_BitCast; 9062 return Compatible; 9063 } 9064 9065 // - conversions from 'Class' to the redefinition type 9066 if (RHSType->isObjCClassType() && 9067 Context.hasSameType(LHSType, 9068 Context.getObjCClassRedefinitionType())) { 9069 Kind = CK_BitCast; 9070 return Compatible; 9071 } 9072 9073 Kind = CK_BitCast; 9074 return IncompatiblePointer; 9075 } 9076 9077 // U^ -> void* 9078 if (RHSType->getAs<BlockPointerType>()) { 9079 if (LHSPointer->getPointeeType()->isVoidType()) { 9080 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9081 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9082 ->getPointeeType() 9083 .getAddressSpace(); 9084 Kind = 9085 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9086 return Compatible; 9087 } 9088 } 9089 9090 return Incompatible; 9091 } 9092 9093 // Conversions to block pointers. 9094 if (isa<BlockPointerType>(LHSType)) { 9095 // U^ -> T^ 9096 if (RHSType->isBlockPointerType()) { 9097 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9098 ->getPointeeType() 9099 .getAddressSpace(); 9100 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9101 ->getPointeeType() 9102 .getAddressSpace(); 9103 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9104 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9105 } 9106 9107 // int or null -> T^ 9108 if (RHSType->isIntegerType()) { 9109 Kind = CK_IntegralToPointer; // FIXME: null 9110 return IntToBlockPointer; 9111 } 9112 9113 // id -> T^ 9114 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9115 Kind = CK_AnyPointerToBlockPointerCast; 9116 return Compatible; 9117 } 9118 9119 // void* -> T^ 9120 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9121 if (RHSPT->getPointeeType()->isVoidType()) { 9122 Kind = CK_AnyPointerToBlockPointerCast; 9123 return Compatible; 9124 } 9125 9126 return Incompatible; 9127 } 9128 9129 // Conversions to Objective-C pointers. 9130 if (isa<ObjCObjectPointerType>(LHSType)) { 9131 // A* -> B* 9132 if (RHSType->isObjCObjectPointerType()) { 9133 Kind = CK_BitCast; 9134 Sema::AssignConvertType result = 9135 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9136 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9137 result == Compatible && 9138 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9139 result = IncompatibleObjCWeakRef; 9140 return result; 9141 } 9142 9143 // int or null -> A* 9144 if (RHSType->isIntegerType()) { 9145 Kind = CK_IntegralToPointer; // FIXME: null 9146 return IntToPointer; 9147 } 9148 9149 // In general, C pointers are not compatible with ObjC object pointers, 9150 // with two exceptions: 9151 if (isa<PointerType>(RHSType)) { 9152 Kind = CK_CPointerToObjCPointerCast; 9153 9154 // - conversions from 'void*' 9155 if (RHSType->isVoidPointerType()) { 9156 return Compatible; 9157 } 9158 9159 // - conversions to 'Class' from its redefinition type 9160 if (LHSType->isObjCClassType() && 9161 Context.hasSameType(RHSType, 9162 Context.getObjCClassRedefinitionType())) { 9163 return Compatible; 9164 } 9165 9166 return IncompatiblePointer; 9167 } 9168 9169 // Only under strict condition T^ is compatible with an Objective-C pointer. 9170 if (RHSType->isBlockPointerType() && 9171 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9172 if (ConvertRHS) 9173 maybeExtendBlockObject(RHS); 9174 Kind = CK_BlockPointerToObjCPointerCast; 9175 return Compatible; 9176 } 9177 9178 return Incompatible; 9179 } 9180 9181 // Conversions from pointers that are not covered by the above. 9182 if (isa<PointerType>(RHSType)) { 9183 // T* -> _Bool 9184 if (LHSType == Context.BoolTy) { 9185 Kind = CK_PointerToBoolean; 9186 return Compatible; 9187 } 9188 9189 // T* -> int 9190 if (LHSType->isIntegerType()) { 9191 Kind = CK_PointerToIntegral; 9192 return PointerToInt; 9193 } 9194 9195 return Incompatible; 9196 } 9197 9198 // Conversions from Objective-C pointers that are not covered by the above. 9199 if (isa<ObjCObjectPointerType>(RHSType)) { 9200 // T* -> _Bool 9201 if (LHSType == Context.BoolTy) { 9202 Kind = CK_PointerToBoolean; 9203 return Compatible; 9204 } 9205 9206 // T* -> int 9207 if (LHSType->isIntegerType()) { 9208 Kind = CK_PointerToIntegral; 9209 return PointerToInt; 9210 } 9211 9212 return Incompatible; 9213 } 9214 9215 // struct A -> struct B 9216 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9217 if (Context.typesAreCompatible(LHSType, RHSType)) { 9218 Kind = CK_NoOp; 9219 return Compatible; 9220 } 9221 } 9222 9223 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9224 Kind = CK_IntToOCLSampler; 9225 return Compatible; 9226 } 9227 9228 return Incompatible; 9229 } 9230 9231 /// Constructs a transparent union from an expression that is 9232 /// used to initialize the transparent union. 9233 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9234 ExprResult &EResult, QualType UnionType, 9235 FieldDecl *Field) { 9236 // Build an initializer list that designates the appropriate member 9237 // of the transparent union. 9238 Expr *E = EResult.get(); 9239 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9240 E, SourceLocation()); 9241 Initializer->setType(UnionType); 9242 Initializer->setInitializedFieldInUnion(Field); 9243 9244 // Build a compound literal constructing a value of the transparent 9245 // union type from this initializer list. 9246 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9247 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9248 VK_RValue, Initializer, false); 9249 } 9250 9251 Sema::AssignConvertType 9252 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9253 ExprResult &RHS) { 9254 QualType RHSType = RHS.get()->getType(); 9255 9256 // If the ArgType is a Union type, we want to handle a potential 9257 // transparent_union GCC extension. 9258 const RecordType *UT = ArgType->getAsUnionType(); 9259 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9260 return Incompatible; 9261 9262 // The field to initialize within the transparent union. 9263 RecordDecl *UD = UT->getDecl(); 9264 FieldDecl *InitField = nullptr; 9265 // It's compatible if the expression matches any of the fields. 9266 for (auto *it : UD->fields()) { 9267 if (it->getType()->isPointerType()) { 9268 // If the transparent union contains a pointer type, we allow: 9269 // 1) void pointer 9270 // 2) null pointer constant 9271 if (RHSType->isPointerType()) 9272 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9273 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9274 InitField = it; 9275 break; 9276 } 9277 9278 if (RHS.get()->isNullPointerConstant(Context, 9279 Expr::NPC_ValueDependentIsNull)) { 9280 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9281 CK_NullToPointer); 9282 InitField = it; 9283 break; 9284 } 9285 } 9286 9287 CastKind Kind; 9288 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9289 == Compatible) { 9290 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9291 InitField = it; 9292 break; 9293 } 9294 } 9295 9296 if (!InitField) 9297 return Incompatible; 9298 9299 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9300 return Compatible; 9301 } 9302 9303 Sema::AssignConvertType 9304 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9305 bool Diagnose, 9306 bool DiagnoseCFAudited, 9307 bool ConvertRHS) { 9308 // We need to be able to tell the caller whether we diagnosed a problem, if 9309 // they ask us to issue diagnostics. 9310 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9311 9312 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9313 // we can't avoid *all* modifications at the moment, so we need some somewhere 9314 // to put the updated value. 9315 ExprResult LocalRHS = CallerRHS; 9316 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9317 9318 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9319 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9320 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9321 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9322 Diag(RHS.get()->getExprLoc(), 9323 diag::warn_noderef_to_dereferenceable_pointer) 9324 << RHS.get()->getSourceRange(); 9325 } 9326 } 9327 } 9328 9329 if (getLangOpts().CPlusPlus) { 9330 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9331 // C++ 5.17p3: If the left operand is not of class type, the 9332 // expression is implicitly converted (C++ 4) to the 9333 // cv-unqualified type of the left operand. 9334 QualType RHSType = RHS.get()->getType(); 9335 if (Diagnose) { 9336 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9337 AA_Assigning); 9338 } else { 9339 ImplicitConversionSequence ICS = 9340 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9341 /*SuppressUserConversions=*/false, 9342 AllowedExplicit::None, 9343 /*InOverloadResolution=*/false, 9344 /*CStyle=*/false, 9345 /*AllowObjCWritebackConversion=*/false); 9346 if (ICS.isFailure()) 9347 return Incompatible; 9348 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9349 ICS, AA_Assigning); 9350 } 9351 if (RHS.isInvalid()) 9352 return Incompatible; 9353 Sema::AssignConvertType result = Compatible; 9354 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9355 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9356 result = IncompatibleObjCWeakRef; 9357 return result; 9358 } 9359 9360 // FIXME: Currently, we fall through and treat C++ classes like C 9361 // structures. 9362 // FIXME: We also fall through for atomics; not sure what should 9363 // happen there, though. 9364 } else if (RHS.get()->getType() == Context.OverloadTy) { 9365 // As a set of extensions to C, we support overloading on functions. These 9366 // functions need to be resolved here. 9367 DeclAccessPair DAP; 9368 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9369 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9370 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9371 else 9372 return Incompatible; 9373 } 9374 9375 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9376 // a null pointer constant. 9377 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9378 LHSType->isBlockPointerType()) && 9379 RHS.get()->isNullPointerConstant(Context, 9380 Expr::NPC_ValueDependentIsNull)) { 9381 if (Diagnose || ConvertRHS) { 9382 CastKind Kind; 9383 CXXCastPath Path; 9384 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9385 /*IgnoreBaseAccess=*/false, Diagnose); 9386 if (ConvertRHS) 9387 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9388 } 9389 return Compatible; 9390 } 9391 9392 // OpenCL queue_t type assignment. 9393 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9394 Context, Expr::NPC_ValueDependentIsNull)) { 9395 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9396 return Compatible; 9397 } 9398 9399 // This check seems unnatural, however it is necessary to ensure the proper 9400 // conversion of functions/arrays. If the conversion were done for all 9401 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9402 // expressions that suppress this implicit conversion (&, sizeof). 9403 // 9404 // Suppress this for references: C++ 8.5.3p5. 9405 if (!LHSType->isReferenceType()) { 9406 // FIXME: We potentially allocate here even if ConvertRHS is false. 9407 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9408 if (RHS.isInvalid()) 9409 return Incompatible; 9410 } 9411 CastKind Kind; 9412 Sema::AssignConvertType result = 9413 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9414 9415 // C99 6.5.16.1p2: The value of the right operand is converted to the 9416 // type of the assignment expression. 9417 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9418 // so that we can use references in built-in functions even in C. 9419 // The getNonReferenceType() call makes sure that the resulting expression 9420 // does not have reference type. 9421 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9422 QualType Ty = LHSType.getNonLValueExprType(Context); 9423 Expr *E = RHS.get(); 9424 9425 // Check for various Objective-C errors. If we are not reporting 9426 // diagnostics and just checking for errors, e.g., during overload 9427 // resolution, return Incompatible to indicate the failure. 9428 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9429 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9430 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9431 if (!Diagnose) 9432 return Incompatible; 9433 } 9434 if (getLangOpts().ObjC && 9435 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9436 E->getType(), E, Diagnose) || 9437 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9438 if (!Diagnose) 9439 return Incompatible; 9440 // Replace the expression with a corrected version and continue so we 9441 // can find further errors. 9442 RHS = E; 9443 return Compatible; 9444 } 9445 9446 if (ConvertRHS) 9447 RHS = ImpCastExprToType(E, Ty, Kind); 9448 } 9449 9450 return result; 9451 } 9452 9453 namespace { 9454 /// The original operand to an operator, prior to the application of the usual 9455 /// arithmetic conversions and converting the arguments of a builtin operator 9456 /// candidate. 9457 struct OriginalOperand { 9458 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9459 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9460 Op = MTE->getSubExpr(); 9461 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9462 Op = BTE->getSubExpr(); 9463 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9464 Orig = ICE->getSubExprAsWritten(); 9465 Conversion = ICE->getConversionFunction(); 9466 } 9467 } 9468 9469 QualType getType() const { return Orig->getType(); } 9470 9471 Expr *Orig; 9472 NamedDecl *Conversion; 9473 }; 9474 } 9475 9476 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9477 ExprResult &RHS) { 9478 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9479 9480 Diag(Loc, diag::err_typecheck_invalid_operands) 9481 << OrigLHS.getType() << OrigRHS.getType() 9482 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9483 9484 // If a user-defined conversion was applied to either of the operands prior 9485 // to applying the built-in operator rules, tell the user about it. 9486 if (OrigLHS.Conversion) { 9487 Diag(OrigLHS.Conversion->getLocation(), 9488 diag::note_typecheck_invalid_operands_converted) 9489 << 0 << LHS.get()->getType(); 9490 } 9491 if (OrigRHS.Conversion) { 9492 Diag(OrigRHS.Conversion->getLocation(), 9493 diag::note_typecheck_invalid_operands_converted) 9494 << 1 << RHS.get()->getType(); 9495 } 9496 9497 return QualType(); 9498 } 9499 9500 // Diagnose cases where a scalar was implicitly converted to a vector and 9501 // diagnose the underlying types. Otherwise, diagnose the error 9502 // as invalid vector logical operands for non-C++ cases. 9503 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9504 ExprResult &RHS) { 9505 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9506 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9507 9508 bool LHSNatVec = LHSType->isVectorType(); 9509 bool RHSNatVec = RHSType->isVectorType(); 9510 9511 if (!(LHSNatVec && RHSNatVec)) { 9512 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9513 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9514 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9515 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9516 << Vector->getSourceRange(); 9517 return QualType(); 9518 } 9519 9520 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9521 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9522 << RHS.get()->getSourceRange(); 9523 9524 return QualType(); 9525 } 9526 9527 /// Try to convert a value of non-vector type to a vector type by converting 9528 /// the type to the element type of the vector and then performing a splat. 9529 /// If the language is OpenCL, we only use conversions that promote scalar 9530 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9531 /// for float->int. 9532 /// 9533 /// OpenCL V2.0 6.2.6.p2: 9534 /// An error shall occur if any scalar operand type has greater rank 9535 /// than the type of the vector element. 9536 /// 9537 /// \param scalar - if non-null, actually perform the conversions 9538 /// \return true if the operation fails (but without diagnosing the failure) 9539 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9540 QualType scalarTy, 9541 QualType vectorEltTy, 9542 QualType vectorTy, 9543 unsigned &DiagID) { 9544 // The conversion to apply to the scalar before splatting it, 9545 // if necessary. 9546 CastKind scalarCast = CK_NoOp; 9547 9548 if (vectorEltTy->isIntegralType(S.Context)) { 9549 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9550 (scalarTy->isIntegerType() && 9551 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9552 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9553 return true; 9554 } 9555 if (!scalarTy->isIntegralType(S.Context)) 9556 return true; 9557 scalarCast = CK_IntegralCast; 9558 } else if (vectorEltTy->isRealFloatingType()) { 9559 if (scalarTy->isRealFloatingType()) { 9560 if (S.getLangOpts().OpenCL && 9561 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9562 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9563 return true; 9564 } 9565 scalarCast = CK_FloatingCast; 9566 } 9567 else if (scalarTy->isIntegralType(S.Context)) 9568 scalarCast = CK_IntegralToFloating; 9569 else 9570 return true; 9571 } else { 9572 return true; 9573 } 9574 9575 // Adjust scalar if desired. 9576 if (scalar) { 9577 if (scalarCast != CK_NoOp) 9578 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9579 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9580 } 9581 return false; 9582 } 9583 9584 /// Convert vector E to a vector with the same number of elements but different 9585 /// element type. 9586 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9587 const auto *VecTy = E->getType()->getAs<VectorType>(); 9588 assert(VecTy && "Expression E must be a vector"); 9589 QualType NewVecTy = S.Context.getVectorType(ElementType, 9590 VecTy->getNumElements(), 9591 VecTy->getVectorKind()); 9592 9593 // Look through the implicit cast. Return the subexpression if its type is 9594 // NewVecTy. 9595 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9596 if (ICE->getSubExpr()->getType() == NewVecTy) 9597 return ICE->getSubExpr(); 9598 9599 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9600 return S.ImpCastExprToType(E, NewVecTy, Cast); 9601 } 9602 9603 /// Test if a (constant) integer Int can be casted to another integer type 9604 /// IntTy without losing precision. 9605 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9606 QualType OtherIntTy) { 9607 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9608 9609 // Reject cases where the value of the Int is unknown as that would 9610 // possibly cause truncation, but accept cases where the scalar can be 9611 // demoted without loss of precision. 9612 Expr::EvalResult EVResult; 9613 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9614 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9615 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9616 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9617 9618 if (CstInt) { 9619 // If the scalar is constant and is of a higher order and has more active 9620 // bits that the vector element type, reject it. 9621 llvm::APSInt Result = EVResult.Val.getInt(); 9622 unsigned NumBits = IntSigned 9623 ? (Result.isNegative() ? Result.getMinSignedBits() 9624 : Result.getActiveBits()) 9625 : Result.getActiveBits(); 9626 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9627 return true; 9628 9629 // If the signedness of the scalar type and the vector element type 9630 // differs and the number of bits is greater than that of the vector 9631 // element reject it. 9632 return (IntSigned != OtherIntSigned && 9633 NumBits > S.Context.getIntWidth(OtherIntTy)); 9634 } 9635 9636 // Reject cases where the value of the scalar is not constant and it's 9637 // order is greater than that of the vector element type. 9638 return (Order < 0); 9639 } 9640 9641 /// Test if a (constant) integer Int can be casted to floating point type 9642 /// FloatTy without losing precision. 9643 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9644 QualType FloatTy) { 9645 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9646 9647 // Determine if the integer constant can be expressed as a floating point 9648 // number of the appropriate type. 9649 Expr::EvalResult EVResult; 9650 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9651 9652 uint64_t Bits = 0; 9653 if (CstInt) { 9654 // Reject constants that would be truncated if they were converted to 9655 // the floating point type. Test by simple to/from conversion. 9656 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9657 // could be avoided if there was a convertFromAPInt method 9658 // which could signal back if implicit truncation occurred. 9659 llvm::APSInt Result = EVResult.Val.getInt(); 9660 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9661 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9662 llvm::APFloat::rmTowardZero); 9663 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9664 !IntTy->hasSignedIntegerRepresentation()); 9665 bool Ignored = false; 9666 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9667 &Ignored); 9668 if (Result != ConvertBack) 9669 return true; 9670 } else { 9671 // Reject types that cannot be fully encoded into the mantissa of 9672 // the float. 9673 Bits = S.Context.getTypeSize(IntTy); 9674 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9675 S.Context.getFloatTypeSemantics(FloatTy)); 9676 if (Bits > FloatPrec) 9677 return true; 9678 } 9679 9680 return false; 9681 } 9682 9683 /// Attempt to convert and splat Scalar into a vector whose types matches 9684 /// Vector following GCC conversion rules. The rule is that implicit 9685 /// conversion can occur when Scalar can be casted to match Vector's element 9686 /// type without causing truncation of Scalar. 9687 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9688 ExprResult *Vector) { 9689 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9690 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9691 const VectorType *VT = VectorTy->getAs<VectorType>(); 9692 9693 assert(!isa<ExtVectorType>(VT) && 9694 "ExtVectorTypes should not be handled here!"); 9695 9696 QualType VectorEltTy = VT->getElementType(); 9697 9698 // Reject cases where the vector element type or the scalar element type are 9699 // not integral or floating point types. 9700 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9701 return true; 9702 9703 // The conversion to apply to the scalar before splatting it, 9704 // if necessary. 9705 CastKind ScalarCast = CK_NoOp; 9706 9707 // Accept cases where the vector elements are integers and the scalar is 9708 // an integer. 9709 // FIXME: Notionally if the scalar was a floating point value with a precise 9710 // integral representation, we could cast it to an appropriate integer 9711 // type and then perform the rest of the checks here. GCC will perform 9712 // this conversion in some cases as determined by the input language. 9713 // We should accept it on a language independent basis. 9714 if (VectorEltTy->isIntegralType(S.Context) && 9715 ScalarTy->isIntegralType(S.Context) && 9716 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9717 9718 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9719 return true; 9720 9721 ScalarCast = CK_IntegralCast; 9722 } else if (VectorEltTy->isIntegralType(S.Context) && 9723 ScalarTy->isRealFloatingType()) { 9724 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9725 ScalarCast = CK_FloatingToIntegral; 9726 else 9727 return true; 9728 } else if (VectorEltTy->isRealFloatingType()) { 9729 if (ScalarTy->isRealFloatingType()) { 9730 9731 // Reject cases where the scalar type is not a constant and has a higher 9732 // Order than the vector element type. 9733 llvm::APFloat Result(0.0); 9734 9735 // Determine whether this is a constant scalar. In the event that the 9736 // value is dependent (and thus cannot be evaluated by the constant 9737 // evaluator), skip the evaluation. This will then diagnose once the 9738 // expression is instantiated. 9739 bool CstScalar = Scalar->get()->isValueDependent() || 9740 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9741 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9742 if (!CstScalar && Order < 0) 9743 return true; 9744 9745 // If the scalar cannot be safely casted to the vector element type, 9746 // reject it. 9747 if (CstScalar) { 9748 bool Truncated = false; 9749 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9750 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9751 if (Truncated) 9752 return true; 9753 } 9754 9755 ScalarCast = CK_FloatingCast; 9756 } else if (ScalarTy->isIntegralType(S.Context)) { 9757 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9758 return true; 9759 9760 ScalarCast = CK_IntegralToFloating; 9761 } else 9762 return true; 9763 } else if (ScalarTy->isEnumeralType()) 9764 return true; 9765 9766 // Adjust scalar if desired. 9767 if (Scalar) { 9768 if (ScalarCast != CK_NoOp) 9769 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9770 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9771 } 9772 return false; 9773 } 9774 9775 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9776 SourceLocation Loc, bool IsCompAssign, 9777 bool AllowBothBool, 9778 bool AllowBoolConversions) { 9779 if (!IsCompAssign) { 9780 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9781 if (LHS.isInvalid()) 9782 return QualType(); 9783 } 9784 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9785 if (RHS.isInvalid()) 9786 return QualType(); 9787 9788 // For conversion purposes, we ignore any qualifiers. 9789 // For example, "const float" and "float" are equivalent. 9790 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9791 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9792 9793 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9794 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9795 assert(LHSVecType || RHSVecType); 9796 9797 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9798 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9799 return InvalidOperands(Loc, LHS, RHS); 9800 9801 // AltiVec-style "vector bool op vector bool" combinations are allowed 9802 // for some operators but not others. 9803 if (!AllowBothBool && 9804 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9805 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9806 return InvalidOperands(Loc, LHS, RHS); 9807 9808 // If the vector types are identical, return. 9809 if (Context.hasSameType(LHSType, RHSType)) 9810 return LHSType; 9811 9812 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9813 if (LHSVecType && RHSVecType && 9814 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9815 if (isa<ExtVectorType>(LHSVecType)) { 9816 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9817 return LHSType; 9818 } 9819 9820 if (!IsCompAssign) 9821 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9822 return RHSType; 9823 } 9824 9825 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9826 // can be mixed, with the result being the non-bool type. The non-bool 9827 // operand must have integer element type. 9828 if (AllowBoolConversions && LHSVecType && RHSVecType && 9829 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9830 (Context.getTypeSize(LHSVecType->getElementType()) == 9831 Context.getTypeSize(RHSVecType->getElementType()))) { 9832 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9833 LHSVecType->getElementType()->isIntegerType() && 9834 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9835 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9836 return LHSType; 9837 } 9838 if (!IsCompAssign && 9839 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9840 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9841 RHSVecType->getElementType()->isIntegerType()) { 9842 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9843 return RHSType; 9844 } 9845 } 9846 9847 // If there's a vector type and a scalar, try to convert the scalar to 9848 // the vector element type and splat. 9849 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9850 if (!RHSVecType) { 9851 if (isa<ExtVectorType>(LHSVecType)) { 9852 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9853 LHSVecType->getElementType(), LHSType, 9854 DiagID)) 9855 return LHSType; 9856 } else { 9857 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9858 return LHSType; 9859 } 9860 } 9861 if (!LHSVecType) { 9862 if (isa<ExtVectorType>(RHSVecType)) { 9863 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9864 LHSType, RHSVecType->getElementType(), 9865 RHSType, DiagID)) 9866 return RHSType; 9867 } else { 9868 if (LHS.get()->getValueKind() == VK_LValue || 9869 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9870 return RHSType; 9871 } 9872 } 9873 9874 // FIXME: The code below also handles conversion between vectors and 9875 // non-scalars, we should break this down into fine grained specific checks 9876 // and emit proper diagnostics. 9877 QualType VecType = LHSVecType ? LHSType : RHSType; 9878 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9879 QualType OtherType = LHSVecType ? RHSType : LHSType; 9880 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9881 if (isLaxVectorConversion(OtherType, VecType)) { 9882 // If we're allowing lax vector conversions, only the total (data) size 9883 // needs to be the same. For non compound assignment, if one of the types is 9884 // scalar, the result is always the vector type. 9885 if (!IsCompAssign) { 9886 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9887 return VecType; 9888 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9889 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9890 // type. Note that this is already done by non-compound assignments in 9891 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9892 // <1 x T> -> T. The result is also a vector type. 9893 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9894 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9895 ExprResult *RHSExpr = &RHS; 9896 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9897 return VecType; 9898 } 9899 } 9900 9901 // Okay, the expression is invalid. 9902 9903 // If there's a non-vector, non-real operand, diagnose that. 9904 if ((!RHSVecType && !RHSType->isRealType()) || 9905 (!LHSVecType && !LHSType->isRealType())) { 9906 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9907 << LHSType << RHSType 9908 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9909 return QualType(); 9910 } 9911 9912 // OpenCL V1.1 6.2.6.p1: 9913 // If the operands are of more than one vector type, then an error shall 9914 // occur. Implicit conversions between vector types are not permitted, per 9915 // section 6.2.1. 9916 if (getLangOpts().OpenCL && 9917 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9918 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9919 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9920 << RHSType; 9921 return QualType(); 9922 } 9923 9924 9925 // If there is a vector type that is not a ExtVector and a scalar, we reach 9926 // this point if scalar could not be converted to the vector's element type 9927 // without truncation. 9928 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9929 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9930 QualType Scalar = LHSVecType ? RHSType : LHSType; 9931 QualType Vector = LHSVecType ? LHSType : RHSType; 9932 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9933 Diag(Loc, 9934 diag::err_typecheck_vector_not_convertable_implict_truncation) 9935 << ScalarOrVector << Scalar << Vector; 9936 9937 return QualType(); 9938 } 9939 9940 // Otherwise, use the generic diagnostic. 9941 Diag(Loc, DiagID) 9942 << LHSType << RHSType 9943 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9944 return QualType(); 9945 } 9946 9947 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9948 // expression. These are mainly cases where the null pointer is used as an 9949 // integer instead of a pointer. 9950 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9951 SourceLocation Loc, bool IsCompare) { 9952 // The canonical way to check for a GNU null is with isNullPointerConstant, 9953 // but we use a bit of a hack here for speed; this is a relatively 9954 // hot path, and isNullPointerConstant is slow. 9955 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9956 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9957 9958 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9959 9960 // Avoid analyzing cases where the result will either be invalid (and 9961 // diagnosed as such) or entirely valid and not something to warn about. 9962 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9963 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9964 return; 9965 9966 // Comparison operations would not make sense with a null pointer no matter 9967 // what the other expression is. 9968 if (!IsCompare) { 9969 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9970 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9971 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9972 return; 9973 } 9974 9975 // The rest of the operations only make sense with a null pointer 9976 // if the other expression is a pointer. 9977 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9978 NonNullType->canDecayToPointerType()) 9979 return; 9980 9981 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9982 << LHSNull /* LHS is NULL */ << NonNullType 9983 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9984 } 9985 9986 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9987 SourceLocation Loc) { 9988 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9989 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9990 if (!LUE || !RUE) 9991 return; 9992 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9993 RUE->getKind() != UETT_SizeOf) 9994 return; 9995 9996 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9997 QualType LHSTy = LHSArg->getType(); 9998 QualType RHSTy; 9999 10000 if (RUE->isArgumentType()) 10001 RHSTy = RUE->getArgumentType(); 10002 else 10003 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10004 10005 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10006 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10007 return; 10008 10009 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10010 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10011 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10012 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10013 << LHSArgDecl; 10014 } 10015 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10016 QualType ArrayElemTy = ArrayTy->getElementType(); 10017 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10018 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10019 ArrayElemTy->isCharType() || 10020 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10021 return; 10022 S.Diag(Loc, diag::warn_division_sizeof_array) 10023 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10024 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10025 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10026 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10027 << LHSArgDecl; 10028 } 10029 10030 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10031 } 10032 } 10033 10034 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10035 ExprResult &RHS, 10036 SourceLocation Loc, bool IsDiv) { 10037 // Check for division/remainder by zero. 10038 Expr::EvalResult RHSValue; 10039 if (!RHS.get()->isValueDependent() && 10040 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10041 RHSValue.Val.getInt() == 0) 10042 S.DiagRuntimeBehavior(Loc, RHS.get(), 10043 S.PDiag(diag::warn_remainder_division_by_zero) 10044 << IsDiv << RHS.get()->getSourceRange()); 10045 } 10046 10047 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10048 SourceLocation Loc, 10049 bool IsCompAssign, bool IsDiv) { 10050 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10051 10052 if (LHS.get()->getType()->isVectorType() || 10053 RHS.get()->getType()->isVectorType()) 10054 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10055 /*AllowBothBool*/getLangOpts().AltiVec, 10056 /*AllowBoolConversions*/false); 10057 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10058 RHS.get()->getType()->isConstantMatrixType())) 10059 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10060 10061 QualType compType = UsualArithmeticConversions( 10062 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10063 if (LHS.isInvalid() || RHS.isInvalid()) 10064 return QualType(); 10065 10066 10067 if (compType.isNull() || !compType->isArithmeticType()) 10068 return InvalidOperands(Loc, LHS, RHS); 10069 if (IsDiv) { 10070 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10071 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10072 } 10073 return compType; 10074 } 10075 10076 QualType Sema::CheckRemainderOperands( 10077 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10078 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10079 10080 if (LHS.get()->getType()->isVectorType() || 10081 RHS.get()->getType()->isVectorType()) { 10082 if (LHS.get()->getType()->hasIntegerRepresentation() && 10083 RHS.get()->getType()->hasIntegerRepresentation()) 10084 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10085 /*AllowBothBool*/getLangOpts().AltiVec, 10086 /*AllowBoolConversions*/false); 10087 return InvalidOperands(Loc, LHS, RHS); 10088 } 10089 10090 QualType compType = UsualArithmeticConversions( 10091 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10092 if (LHS.isInvalid() || RHS.isInvalid()) 10093 return QualType(); 10094 10095 if (compType.isNull() || !compType->isIntegerType()) 10096 return InvalidOperands(Loc, LHS, RHS); 10097 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10098 return compType; 10099 } 10100 10101 /// Diagnose invalid arithmetic on two void pointers. 10102 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10103 Expr *LHSExpr, Expr *RHSExpr) { 10104 S.Diag(Loc, S.getLangOpts().CPlusPlus 10105 ? diag::err_typecheck_pointer_arith_void_type 10106 : diag::ext_gnu_void_ptr) 10107 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10108 << RHSExpr->getSourceRange(); 10109 } 10110 10111 /// Diagnose invalid arithmetic on a void pointer. 10112 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10113 Expr *Pointer) { 10114 S.Diag(Loc, S.getLangOpts().CPlusPlus 10115 ? diag::err_typecheck_pointer_arith_void_type 10116 : diag::ext_gnu_void_ptr) 10117 << 0 /* one pointer */ << Pointer->getSourceRange(); 10118 } 10119 10120 /// Diagnose invalid arithmetic on a null pointer. 10121 /// 10122 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10123 /// idiom, which we recognize as a GNU extension. 10124 /// 10125 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10126 Expr *Pointer, bool IsGNUIdiom) { 10127 if (IsGNUIdiom) 10128 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10129 << Pointer->getSourceRange(); 10130 else 10131 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10132 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10133 } 10134 10135 /// Diagnose invalid arithmetic on two function pointers. 10136 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10137 Expr *LHS, Expr *RHS) { 10138 assert(LHS->getType()->isAnyPointerType()); 10139 assert(RHS->getType()->isAnyPointerType()); 10140 S.Diag(Loc, S.getLangOpts().CPlusPlus 10141 ? diag::err_typecheck_pointer_arith_function_type 10142 : diag::ext_gnu_ptr_func_arith) 10143 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10144 // We only show the second type if it differs from the first. 10145 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10146 RHS->getType()) 10147 << RHS->getType()->getPointeeType() 10148 << LHS->getSourceRange() << RHS->getSourceRange(); 10149 } 10150 10151 /// Diagnose invalid arithmetic on a function pointer. 10152 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10153 Expr *Pointer) { 10154 assert(Pointer->getType()->isAnyPointerType()); 10155 S.Diag(Loc, S.getLangOpts().CPlusPlus 10156 ? diag::err_typecheck_pointer_arith_function_type 10157 : diag::ext_gnu_ptr_func_arith) 10158 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10159 << 0 /* one pointer, so only one type */ 10160 << Pointer->getSourceRange(); 10161 } 10162 10163 /// Emit error if Operand is incomplete pointer type 10164 /// 10165 /// \returns True if pointer has incomplete type 10166 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10167 Expr *Operand) { 10168 QualType ResType = Operand->getType(); 10169 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10170 ResType = ResAtomicType->getValueType(); 10171 10172 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10173 QualType PointeeTy = ResType->getPointeeType(); 10174 return S.RequireCompleteSizedType( 10175 Loc, PointeeTy, 10176 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10177 Operand->getSourceRange()); 10178 } 10179 10180 /// Check the validity of an arithmetic pointer operand. 10181 /// 10182 /// If the operand has pointer type, this code will check for pointer types 10183 /// which are invalid in arithmetic operations. These will be diagnosed 10184 /// appropriately, including whether or not the use is supported as an 10185 /// extension. 10186 /// 10187 /// \returns True when the operand is valid to use (even if as an extension). 10188 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10189 Expr *Operand) { 10190 QualType ResType = Operand->getType(); 10191 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10192 ResType = ResAtomicType->getValueType(); 10193 10194 if (!ResType->isAnyPointerType()) return true; 10195 10196 QualType PointeeTy = ResType->getPointeeType(); 10197 if (PointeeTy->isVoidType()) { 10198 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10199 return !S.getLangOpts().CPlusPlus; 10200 } 10201 if (PointeeTy->isFunctionType()) { 10202 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10203 return !S.getLangOpts().CPlusPlus; 10204 } 10205 10206 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10207 10208 return true; 10209 } 10210 10211 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10212 /// operands. 10213 /// 10214 /// This routine will diagnose any invalid arithmetic on pointer operands much 10215 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10216 /// for emitting a single diagnostic even for operations where both LHS and RHS 10217 /// are (potentially problematic) pointers. 10218 /// 10219 /// \returns True when the operand is valid to use (even if as an extension). 10220 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10221 Expr *LHSExpr, Expr *RHSExpr) { 10222 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10223 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10224 if (!isLHSPointer && !isRHSPointer) return true; 10225 10226 QualType LHSPointeeTy, RHSPointeeTy; 10227 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10228 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10229 10230 // if both are pointers check if operation is valid wrt address spaces 10231 if (isLHSPointer && isRHSPointer) { 10232 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10233 S.Diag(Loc, 10234 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10235 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10236 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10237 return false; 10238 } 10239 } 10240 10241 // Check for arithmetic on pointers to incomplete types. 10242 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10243 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10244 if (isLHSVoidPtr || isRHSVoidPtr) { 10245 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10246 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10247 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10248 10249 return !S.getLangOpts().CPlusPlus; 10250 } 10251 10252 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10253 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10254 if (isLHSFuncPtr || isRHSFuncPtr) { 10255 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10256 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10257 RHSExpr); 10258 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10259 10260 return !S.getLangOpts().CPlusPlus; 10261 } 10262 10263 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10264 return false; 10265 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10266 return false; 10267 10268 return true; 10269 } 10270 10271 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10272 /// literal. 10273 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10274 Expr *LHSExpr, Expr *RHSExpr) { 10275 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10276 Expr* IndexExpr = RHSExpr; 10277 if (!StrExpr) { 10278 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10279 IndexExpr = LHSExpr; 10280 } 10281 10282 bool IsStringPlusInt = StrExpr && 10283 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10284 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10285 return; 10286 10287 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10288 Self.Diag(OpLoc, diag::warn_string_plus_int) 10289 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10290 10291 // Only print a fixit for "str" + int, not for int + "str". 10292 if (IndexExpr == RHSExpr) { 10293 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10294 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10295 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10296 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10297 << FixItHint::CreateInsertion(EndLoc, "]"); 10298 } else 10299 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10300 } 10301 10302 /// Emit a warning when adding a char literal to a string. 10303 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10304 Expr *LHSExpr, Expr *RHSExpr) { 10305 const Expr *StringRefExpr = LHSExpr; 10306 const CharacterLiteral *CharExpr = 10307 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10308 10309 if (!CharExpr) { 10310 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10311 StringRefExpr = RHSExpr; 10312 } 10313 10314 if (!CharExpr || !StringRefExpr) 10315 return; 10316 10317 const QualType StringType = StringRefExpr->getType(); 10318 10319 // Return if not a PointerType. 10320 if (!StringType->isAnyPointerType()) 10321 return; 10322 10323 // Return if not a CharacterType. 10324 if (!StringType->getPointeeType()->isAnyCharacterType()) 10325 return; 10326 10327 ASTContext &Ctx = Self.getASTContext(); 10328 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10329 10330 const QualType CharType = CharExpr->getType(); 10331 if (!CharType->isAnyCharacterType() && 10332 CharType->isIntegerType() && 10333 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10334 Self.Diag(OpLoc, diag::warn_string_plus_char) 10335 << DiagRange << Ctx.CharTy; 10336 } else { 10337 Self.Diag(OpLoc, diag::warn_string_plus_char) 10338 << DiagRange << CharExpr->getType(); 10339 } 10340 10341 // Only print a fixit for str + char, not for char + str. 10342 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10343 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10344 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10345 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10346 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10347 << FixItHint::CreateInsertion(EndLoc, "]"); 10348 } else { 10349 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10350 } 10351 } 10352 10353 /// Emit error when two pointers are incompatible. 10354 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10355 Expr *LHSExpr, Expr *RHSExpr) { 10356 assert(LHSExpr->getType()->isAnyPointerType()); 10357 assert(RHSExpr->getType()->isAnyPointerType()); 10358 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10359 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10360 << RHSExpr->getSourceRange(); 10361 } 10362 10363 // C99 6.5.6 10364 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10365 SourceLocation Loc, BinaryOperatorKind Opc, 10366 QualType* CompLHSTy) { 10367 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10368 10369 if (LHS.get()->getType()->isVectorType() || 10370 RHS.get()->getType()->isVectorType()) { 10371 QualType compType = CheckVectorOperands( 10372 LHS, RHS, Loc, CompLHSTy, 10373 /*AllowBothBool*/getLangOpts().AltiVec, 10374 /*AllowBoolConversions*/getLangOpts().ZVector); 10375 if (CompLHSTy) *CompLHSTy = compType; 10376 return compType; 10377 } 10378 10379 if (LHS.get()->getType()->isConstantMatrixType() || 10380 RHS.get()->getType()->isConstantMatrixType()) { 10381 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10382 } 10383 10384 QualType compType = UsualArithmeticConversions( 10385 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10386 if (LHS.isInvalid() || RHS.isInvalid()) 10387 return QualType(); 10388 10389 // Diagnose "string literal" '+' int and string '+' "char literal". 10390 if (Opc == BO_Add) { 10391 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10392 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10393 } 10394 10395 // handle the common case first (both operands are arithmetic). 10396 if (!compType.isNull() && compType->isArithmeticType()) { 10397 if (CompLHSTy) *CompLHSTy = compType; 10398 return compType; 10399 } 10400 10401 // Type-checking. Ultimately the pointer's going to be in PExp; 10402 // note that we bias towards the LHS being the pointer. 10403 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10404 10405 bool isObjCPointer; 10406 if (PExp->getType()->isPointerType()) { 10407 isObjCPointer = false; 10408 } else if (PExp->getType()->isObjCObjectPointerType()) { 10409 isObjCPointer = true; 10410 } else { 10411 std::swap(PExp, IExp); 10412 if (PExp->getType()->isPointerType()) { 10413 isObjCPointer = false; 10414 } else if (PExp->getType()->isObjCObjectPointerType()) { 10415 isObjCPointer = true; 10416 } else { 10417 return InvalidOperands(Loc, LHS, RHS); 10418 } 10419 } 10420 assert(PExp->getType()->isAnyPointerType()); 10421 10422 if (!IExp->getType()->isIntegerType()) 10423 return InvalidOperands(Loc, LHS, RHS); 10424 10425 // Adding to a null pointer results in undefined behavior. 10426 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10427 Context, Expr::NPC_ValueDependentIsNotNull)) { 10428 // In C++ adding zero to a null pointer is defined. 10429 Expr::EvalResult KnownVal; 10430 if (!getLangOpts().CPlusPlus || 10431 (!IExp->isValueDependent() && 10432 (!IExp->EvaluateAsInt(KnownVal, Context) || 10433 KnownVal.Val.getInt() != 0))) { 10434 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10435 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10436 Context, BO_Add, PExp, IExp); 10437 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10438 } 10439 } 10440 10441 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10442 return QualType(); 10443 10444 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10445 return QualType(); 10446 10447 // Check array bounds for pointer arithemtic 10448 CheckArrayAccess(PExp, IExp); 10449 10450 if (CompLHSTy) { 10451 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10452 if (LHSTy.isNull()) { 10453 LHSTy = LHS.get()->getType(); 10454 if (LHSTy->isPromotableIntegerType()) 10455 LHSTy = Context.getPromotedIntegerType(LHSTy); 10456 } 10457 *CompLHSTy = LHSTy; 10458 } 10459 10460 return PExp->getType(); 10461 } 10462 10463 // C99 6.5.6 10464 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10465 SourceLocation Loc, 10466 QualType* CompLHSTy) { 10467 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10468 10469 if (LHS.get()->getType()->isVectorType() || 10470 RHS.get()->getType()->isVectorType()) { 10471 QualType compType = CheckVectorOperands( 10472 LHS, RHS, Loc, CompLHSTy, 10473 /*AllowBothBool*/getLangOpts().AltiVec, 10474 /*AllowBoolConversions*/getLangOpts().ZVector); 10475 if (CompLHSTy) *CompLHSTy = compType; 10476 return compType; 10477 } 10478 10479 if (LHS.get()->getType()->isConstantMatrixType() || 10480 RHS.get()->getType()->isConstantMatrixType()) { 10481 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10482 } 10483 10484 QualType compType = UsualArithmeticConversions( 10485 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10486 if (LHS.isInvalid() || RHS.isInvalid()) 10487 return QualType(); 10488 10489 // Enforce type constraints: C99 6.5.6p3. 10490 10491 // Handle the common case first (both operands are arithmetic). 10492 if (!compType.isNull() && compType->isArithmeticType()) { 10493 if (CompLHSTy) *CompLHSTy = compType; 10494 return compType; 10495 } 10496 10497 // Either ptr - int or ptr - ptr. 10498 if (LHS.get()->getType()->isAnyPointerType()) { 10499 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10500 10501 // Diagnose bad cases where we step over interface counts. 10502 if (LHS.get()->getType()->isObjCObjectPointerType() && 10503 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10504 return QualType(); 10505 10506 // The result type of a pointer-int computation is the pointer type. 10507 if (RHS.get()->getType()->isIntegerType()) { 10508 // Subtracting from a null pointer should produce a warning. 10509 // The last argument to the diagnose call says this doesn't match the 10510 // GNU int-to-pointer idiom. 10511 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10512 Expr::NPC_ValueDependentIsNotNull)) { 10513 // In C++ adding zero to a null pointer is defined. 10514 Expr::EvalResult KnownVal; 10515 if (!getLangOpts().CPlusPlus || 10516 (!RHS.get()->isValueDependent() && 10517 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10518 KnownVal.Val.getInt() != 0))) { 10519 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10520 } 10521 } 10522 10523 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10524 return QualType(); 10525 10526 // Check array bounds for pointer arithemtic 10527 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10528 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10529 10530 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10531 return LHS.get()->getType(); 10532 } 10533 10534 // Handle pointer-pointer subtractions. 10535 if (const PointerType *RHSPTy 10536 = RHS.get()->getType()->getAs<PointerType>()) { 10537 QualType rpointee = RHSPTy->getPointeeType(); 10538 10539 if (getLangOpts().CPlusPlus) { 10540 // Pointee types must be the same: C++ [expr.add] 10541 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10542 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10543 } 10544 } else { 10545 // Pointee types must be compatible C99 6.5.6p3 10546 if (!Context.typesAreCompatible( 10547 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10548 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10549 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10550 return QualType(); 10551 } 10552 } 10553 10554 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10555 LHS.get(), RHS.get())) 10556 return QualType(); 10557 10558 // FIXME: Add warnings for nullptr - ptr. 10559 10560 // The pointee type may have zero size. As an extension, a structure or 10561 // union may have zero size or an array may have zero length. In this 10562 // case subtraction does not make sense. 10563 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10564 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10565 if (ElementSize.isZero()) { 10566 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10567 << rpointee.getUnqualifiedType() 10568 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10569 } 10570 } 10571 10572 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10573 return Context.getPointerDiffType(); 10574 } 10575 } 10576 10577 return InvalidOperands(Loc, LHS, RHS); 10578 } 10579 10580 static bool isScopedEnumerationType(QualType T) { 10581 if (const EnumType *ET = T->getAs<EnumType>()) 10582 return ET->getDecl()->isScoped(); 10583 return false; 10584 } 10585 10586 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10587 SourceLocation Loc, BinaryOperatorKind Opc, 10588 QualType LHSType) { 10589 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10590 // so skip remaining warnings as we don't want to modify values within Sema. 10591 if (S.getLangOpts().OpenCL) 10592 return; 10593 10594 // Check right/shifter operand 10595 Expr::EvalResult RHSResult; 10596 if (RHS.get()->isValueDependent() || 10597 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10598 return; 10599 llvm::APSInt Right = RHSResult.Val.getInt(); 10600 10601 if (Right.isNegative()) { 10602 S.DiagRuntimeBehavior(Loc, RHS.get(), 10603 S.PDiag(diag::warn_shift_negative) 10604 << RHS.get()->getSourceRange()); 10605 return; 10606 } 10607 10608 QualType LHSExprType = LHS.get()->getType(); 10609 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10610 if (LHSExprType->isExtIntType()) 10611 LeftSize = S.Context.getIntWidth(LHSExprType); 10612 else if (LHSExprType->isFixedPointType()) { 10613 FixedPointSemantics FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10614 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10615 } 10616 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10617 if (Right.uge(LeftBits)) { 10618 S.DiagRuntimeBehavior(Loc, RHS.get(), 10619 S.PDiag(diag::warn_shift_gt_typewidth) 10620 << RHS.get()->getSourceRange()); 10621 return; 10622 } 10623 10624 // FIXME: We probably need to handle fixed point types specially here. 10625 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10626 return; 10627 10628 // When left shifting an ICE which is signed, we can check for overflow which 10629 // according to C++ standards prior to C++2a has undefined behavior 10630 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10631 // more than the maximum value representable in the result type, so never 10632 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10633 // expression is still probably a bug.) 10634 Expr::EvalResult LHSResult; 10635 if (LHS.get()->isValueDependent() || 10636 LHSType->hasUnsignedIntegerRepresentation() || 10637 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10638 return; 10639 llvm::APSInt Left = LHSResult.Val.getInt(); 10640 10641 // If LHS does not have a signed type and non-negative value 10642 // then, the behavior is undefined before C++2a. Warn about it. 10643 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10644 !S.getLangOpts().CPlusPlus20) { 10645 S.DiagRuntimeBehavior(Loc, LHS.get(), 10646 S.PDiag(diag::warn_shift_lhs_negative) 10647 << LHS.get()->getSourceRange()); 10648 return; 10649 } 10650 10651 llvm::APInt ResultBits = 10652 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10653 if (LeftBits.uge(ResultBits)) 10654 return; 10655 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10656 Result = Result.shl(Right); 10657 10658 // Print the bit representation of the signed integer as an unsigned 10659 // hexadecimal number. 10660 SmallString<40> HexResult; 10661 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10662 10663 // If we are only missing a sign bit, this is less likely to result in actual 10664 // bugs -- if the result is cast back to an unsigned type, it will have the 10665 // expected value. Thus we place this behind a different warning that can be 10666 // turned off separately if needed. 10667 if (LeftBits == ResultBits - 1) { 10668 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10669 << HexResult << LHSType 10670 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10671 return; 10672 } 10673 10674 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10675 << HexResult.str() << Result.getMinSignedBits() << LHSType 10676 << Left.getBitWidth() << LHS.get()->getSourceRange() 10677 << RHS.get()->getSourceRange(); 10678 } 10679 10680 /// Return the resulting type when a vector is shifted 10681 /// by a scalar or vector shift amount. 10682 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10683 SourceLocation Loc, bool IsCompAssign) { 10684 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10685 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10686 !LHS.get()->getType()->isVectorType()) { 10687 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10688 << RHS.get()->getType() << LHS.get()->getType() 10689 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10690 return QualType(); 10691 } 10692 10693 if (!IsCompAssign) { 10694 LHS = S.UsualUnaryConversions(LHS.get()); 10695 if (LHS.isInvalid()) return QualType(); 10696 } 10697 10698 RHS = S.UsualUnaryConversions(RHS.get()); 10699 if (RHS.isInvalid()) return QualType(); 10700 10701 QualType LHSType = LHS.get()->getType(); 10702 // Note that LHS might be a scalar because the routine calls not only in 10703 // OpenCL case. 10704 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10705 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10706 10707 // Note that RHS might not be a vector. 10708 QualType RHSType = RHS.get()->getType(); 10709 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10710 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10711 10712 // The operands need to be integers. 10713 if (!LHSEleType->isIntegerType()) { 10714 S.Diag(Loc, diag::err_typecheck_expect_int) 10715 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10716 return QualType(); 10717 } 10718 10719 if (!RHSEleType->isIntegerType()) { 10720 S.Diag(Loc, diag::err_typecheck_expect_int) 10721 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10722 return QualType(); 10723 } 10724 10725 if (!LHSVecTy) { 10726 assert(RHSVecTy); 10727 if (IsCompAssign) 10728 return RHSType; 10729 if (LHSEleType != RHSEleType) { 10730 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10731 LHSEleType = RHSEleType; 10732 } 10733 QualType VecTy = 10734 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10735 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10736 LHSType = VecTy; 10737 } else if (RHSVecTy) { 10738 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10739 // are applied component-wise. So if RHS is a vector, then ensure 10740 // that the number of elements is the same as LHS... 10741 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10742 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10743 << LHS.get()->getType() << RHS.get()->getType() 10744 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10745 return QualType(); 10746 } 10747 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10748 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10749 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10750 if (LHSBT != RHSBT && 10751 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10752 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10753 << LHS.get()->getType() << RHS.get()->getType() 10754 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10755 } 10756 } 10757 } else { 10758 // ...else expand RHS to match the number of elements in LHS. 10759 QualType VecTy = 10760 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10761 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10762 } 10763 10764 return LHSType; 10765 } 10766 10767 // C99 6.5.7 10768 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10769 SourceLocation Loc, BinaryOperatorKind Opc, 10770 bool IsCompAssign) { 10771 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10772 10773 // Vector shifts promote their scalar inputs to vector type. 10774 if (LHS.get()->getType()->isVectorType() || 10775 RHS.get()->getType()->isVectorType()) { 10776 if (LangOpts.ZVector) { 10777 // The shift operators for the z vector extensions work basically 10778 // like general shifts, except that neither the LHS nor the RHS is 10779 // allowed to be a "vector bool". 10780 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10781 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10782 return InvalidOperands(Loc, LHS, RHS); 10783 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10784 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10785 return InvalidOperands(Loc, LHS, RHS); 10786 } 10787 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10788 } 10789 10790 // Shifts don't perform usual arithmetic conversions, they just do integer 10791 // promotions on each operand. C99 6.5.7p3 10792 10793 // For the LHS, do usual unary conversions, but then reset them away 10794 // if this is a compound assignment. 10795 ExprResult OldLHS = LHS; 10796 LHS = UsualUnaryConversions(LHS.get()); 10797 if (LHS.isInvalid()) 10798 return QualType(); 10799 QualType LHSType = LHS.get()->getType(); 10800 if (IsCompAssign) LHS = OldLHS; 10801 10802 // The RHS is simpler. 10803 RHS = UsualUnaryConversions(RHS.get()); 10804 if (RHS.isInvalid()) 10805 return QualType(); 10806 QualType RHSType = RHS.get()->getType(); 10807 10808 // C99 6.5.7p2: Each of the operands shall have integer type. 10809 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10810 if ((!LHSType->isFixedPointOrIntegerType() && 10811 !LHSType->hasIntegerRepresentation()) || 10812 !RHSType->hasIntegerRepresentation()) 10813 return InvalidOperands(Loc, LHS, RHS); 10814 10815 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10816 // hasIntegerRepresentation() above instead of this. 10817 if (isScopedEnumerationType(LHSType) || 10818 isScopedEnumerationType(RHSType)) { 10819 return InvalidOperands(Loc, LHS, RHS); 10820 } 10821 // Sanity-check shift operands 10822 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10823 10824 // "The type of the result is that of the promoted left operand." 10825 return LHSType; 10826 } 10827 10828 /// Diagnose bad pointer comparisons. 10829 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10830 ExprResult &LHS, ExprResult &RHS, 10831 bool IsError) { 10832 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10833 : diag::ext_typecheck_comparison_of_distinct_pointers) 10834 << LHS.get()->getType() << RHS.get()->getType() 10835 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10836 } 10837 10838 /// Returns false if the pointers are converted to a composite type, 10839 /// true otherwise. 10840 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10841 ExprResult &LHS, ExprResult &RHS) { 10842 // C++ [expr.rel]p2: 10843 // [...] Pointer conversions (4.10) and qualification 10844 // conversions (4.4) are performed on pointer operands (or on 10845 // a pointer operand and a null pointer constant) to bring 10846 // them to their composite pointer type. [...] 10847 // 10848 // C++ [expr.eq]p1 uses the same notion for (in)equality 10849 // comparisons of pointers. 10850 10851 QualType LHSType = LHS.get()->getType(); 10852 QualType RHSType = RHS.get()->getType(); 10853 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10854 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10855 10856 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10857 if (T.isNull()) { 10858 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10859 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10860 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10861 else 10862 S.InvalidOperands(Loc, LHS, RHS); 10863 return true; 10864 } 10865 10866 return false; 10867 } 10868 10869 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10870 ExprResult &LHS, 10871 ExprResult &RHS, 10872 bool IsError) { 10873 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10874 : diag::ext_typecheck_comparison_of_fptr_to_void) 10875 << LHS.get()->getType() << RHS.get()->getType() 10876 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10877 } 10878 10879 static bool isObjCObjectLiteral(ExprResult &E) { 10880 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10881 case Stmt::ObjCArrayLiteralClass: 10882 case Stmt::ObjCDictionaryLiteralClass: 10883 case Stmt::ObjCStringLiteralClass: 10884 case Stmt::ObjCBoxedExprClass: 10885 return true; 10886 default: 10887 // Note that ObjCBoolLiteral is NOT an object literal! 10888 return false; 10889 } 10890 } 10891 10892 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10893 const ObjCObjectPointerType *Type = 10894 LHS->getType()->getAs<ObjCObjectPointerType>(); 10895 10896 // If this is not actually an Objective-C object, bail out. 10897 if (!Type) 10898 return false; 10899 10900 // Get the LHS object's interface type. 10901 QualType InterfaceType = Type->getPointeeType(); 10902 10903 // If the RHS isn't an Objective-C object, bail out. 10904 if (!RHS->getType()->isObjCObjectPointerType()) 10905 return false; 10906 10907 // Try to find the -isEqual: method. 10908 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10909 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10910 InterfaceType, 10911 /*IsInstance=*/true); 10912 if (!Method) { 10913 if (Type->isObjCIdType()) { 10914 // For 'id', just check the global pool. 10915 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10916 /*receiverId=*/true); 10917 } else { 10918 // Check protocols. 10919 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10920 /*IsInstance=*/true); 10921 } 10922 } 10923 10924 if (!Method) 10925 return false; 10926 10927 QualType T = Method->parameters()[0]->getType(); 10928 if (!T->isObjCObjectPointerType()) 10929 return false; 10930 10931 QualType R = Method->getReturnType(); 10932 if (!R->isScalarType()) 10933 return false; 10934 10935 return true; 10936 } 10937 10938 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10939 FromE = FromE->IgnoreParenImpCasts(); 10940 switch (FromE->getStmtClass()) { 10941 default: 10942 break; 10943 case Stmt::ObjCStringLiteralClass: 10944 // "string literal" 10945 return LK_String; 10946 case Stmt::ObjCArrayLiteralClass: 10947 // "array literal" 10948 return LK_Array; 10949 case Stmt::ObjCDictionaryLiteralClass: 10950 // "dictionary literal" 10951 return LK_Dictionary; 10952 case Stmt::BlockExprClass: 10953 return LK_Block; 10954 case Stmt::ObjCBoxedExprClass: { 10955 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10956 switch (Inner->getStmtClass()) { 10957 case Stmt::IntegerLiteralClass: 10958 case Stmt::FloatingLiteralClass: 10959 case Stmt::CharacterLiteralClass: 10960 case Stmt::ObjCBoolLiteralExprClass: 10961 case Stmt::CXXBoolLiteralExprClass: 10962 // "numeric literal" 10963 return LK_Numeric; 10964 case Stmt::ImplicitCastExprClass: { 10965 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10966 // Boolean literals can be represented by implicit casts. 10967 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10968 return LK_Numeric; 10969 break; 10970 } 10971 default: 10972 break; 10973 } 10974 return LK_Boxed; 10975 } 10976 } 10977 return LK_None; 10978 } 10979 10980 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10981 ExprResult &LHS, ExprResult &RHS, 10982 BinaryOperator::Opcode Opc){ 10983 Expr *Literal; 10984 Expr *Other; 10985 if (isObjCObjectLiteral(LHS)) { 10986 Literal = LHS.get(); 10987 Other = RHS.get(); 10988 } else { 10989 Literal = RHS.get(); 10990 Other = LHS.get(); 10991 } 10992 10993 // Don't warn on comparisons against nil. 10994 Other = Other->IgnoreParenCasts(); 10995 if (Other->isNullPointerConstant(S.getASTContext(), 10996 Expr::NPC_ValueDependentIsNotNull)) 10997 return; 10998 10999 // This should be kept in sync with warn_objc_literal_comparison. 11000 // LK_String should always be after the other literals, since it has its own 11001 // warning flag. 11002 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11003 assert(LiteralKind != Sema::LK_Block); 11004 if (LiteralKind == Sema::LK_None) { 11005 llvm_unreachable("Unknown Objective-C object literal kind"); 11006 } 11007 11008 if (LiteralKind == Sema::LK_String) 11009 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11010 << Literal->getSourceRange(); 11011 else 11012 S.Diag(Loc, diag::warn_objc_literal_comparison) 11013 << LiteralKind << Literal->getSourceRange(); 11014 11015 if (BinaryOperator::isEqualityOp(Opc) && 11016 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11017 SourceLocation Start = LHS.get()->getBeginLoc(); 11018 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11019 CharSourceRange OpRange = 11020 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11021 11022 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11023 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11024 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11025 << FixItHint::CreateInsertion(End, "]"); 11026 } 11027 } 11028 11029 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11030 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11031 ExprResult &RHS, SourceLocation Loc, 11032 BinaryOperatorKind Opc) { 11033 // Check that left hand side is !something. 11034 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11035 if (!UO || UO->getOpcode() != UO_LNot) return; 11036 11037 // Only check if the right hand side is non-bool arithmetic type. 11038 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11039 11040 // Make sure that the something in !something is not bool. 11041 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11042 if (SubExpr->isKnownToHaveBooleanValue()) return; 11043 11044 // Emit warning. 11045 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11046 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11047 << Loc << IsBitwiseOp; 11048 11049 // First note suggest !(x < y) 11050 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11051 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11052 FirstClose = S.getLocForEndOfToken(FirstClose); 11053 if (FirstClose.isInvalid()) 11054 FirstOpen = SourceLocation(); 11055 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11056 << IsBitwiseOp 11057 << FixItHint::CreateInsertion(FirstOpen, "(") 11058 << FixItHint::CreateInsertion(FirstClose, ")"); 11059 11060 // Second note suggests (!x) < y 11061 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11062 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11063 SecondClose = S.getLocForEndOfToken(SecondClose); 11064 if (SecondClose.isInvalid()) 11065 SecondOpen = SourceLocation(); 11066 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11067 << FixItHint::CreateInsertion(SecondOpen, "(") 11068 << FixItHint::CreateInsertion(SecondClose, ")"); 11069 } 11070 11071 // Returns true if E refers to a non-weak array. 11072 static bool checkForArray(const Expr *E) { 11073 const ValueDecl *D = nullptr; 11074 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11075 D = DR->getDecl(); 11076 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11077 if (Mem->isImplicitAccess()) 11078 D = Mem->getMemberDecl(); 11079 } 11080 if (!D) 11081 return false; 11082 return D->getType()->isArrayType() && !D->isWeak(); 11083 } 11084 11085 /// Diagnose some forms of syntactically-obvious tautological comparison. 11086 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11087 Expr *LHS, Expr *RHS, 11088 BinaryOperatorKind Opc) { 11089 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11090 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11091 11092 QualType LHSType = LHS->getType(); 11093 QualType RHSType = RHS->getType(); 11094 if (LHSType->hasFloatingRepresentation() || 11095 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11096 S.inTemplateInstantiation()) 11097 return; 11098 11099 // Comparisons between two array types are ill-formed for operator<=>, so 11100 // we shouldn't emit any additional warnings about it. 11101 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11102 return; 11103 11104 // For non-floating point types, check for self-comparisons of the form 11105 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11106 // often indicate logic errors in the program. 11107 // 11108 // NOTE: Don't warn about comparison expressions resulting from macro 11109 // expansion. Also don't warn about comparisons which are only self 11110 // comparisons within a template instantiation. The warnings should catch 11111 // obvious cases in the definition of the template anyways. The idea is to 11112 // warn when the typed comparison operator will always evaluate to the same 11113 // result. 11114 11115 // Used for indexing into %select in warn_comparison_always 11116 enum { 11117 AlwaysConstant, 11118 AlwaysTrue, 11119 AlwaysFalse, 11120 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11121 }; 11122 11123 // C++2a [depr.array.comp]: 11124 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11125 // operands of array type are deprecated. 11126 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11127 RHSStripped->getType()->isArrayType()) { 11128 S.Diag(Loc, diag::warn_depr_array_comparison) 11129 << LHS->getSourceRange() << RHS->getSourceRange() 11130 << LHSStripped->getType() << RHSStripped->getType(); 11131 // Carry on to produce the tautological comparison warning, if this 11132 // expression is potentially-evaluated, we can resolve the array to a 11133 // non-weak declaration, and so on. 11134 } 11135 11136 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11137 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11138 unsigned Result; 11139 switch (Opc) { 11140 case BO_EQ: 11141 case BO_LE: 11142 case BO_GE: 11143 Result = AlwaysTrue; 11144 break; 11145 case BO_NE: 11146 case BO_LT: 11147 case BO_GT: 11148 Result = AlwaysFalse; 11149 break; 11150 case BO_Cmp: 11151 Result = AlwaysEqual; 11152 break; 11153 default: 11154 Result = AlwaysConstant; 11155 break; 11156 } 11157 S.DiagRuntimeBehavior(Loc, nullptr, 11158 S.PDiag(diag::warn_comparison_always) 11159 << 0 /*self-comparison*/ 11160 << Result); 11161 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11162 // What is it always going to evaluate to? 11163 unsigned Result; 11164 switch (Opc) { 11165 case BO_EQ: // e.g. array1 == array2 11166 Result = AlwaysFalse; 11167 break; 11168 case BO_NE: // e.g. array1 != array2 11169 Result = AlwaysTrue; 11170 break; 11171 default: // e.g. array1 <= array2 11172 // The best we can say is 'a constant' 11173 Result = AlwaysConstant; 11174 break; 11175 } 11176 S.DiagRuntimeBehavior(Loc, nullptr, 11177 S.PDiag(diag::warn_comparison_always) 11178 << 1 /*array comparison*/ 11179 << Result); 11180 } 11181 } 11182 11183 if (isa<CastExpr>(LHSStripped)) 11184 LHSStripped = LHSStripped->IgnoreParenCasts(); 11185 if (isa<CastExpr>(RHSStripped)) 11186 RHSStripped = RHSStripped->IgnoreParenCasts(); 11187 11188 // Warn about comparisons against a string constant (unless the other 11189 // operand is null); the user probably wants string comparison function. 11190 Expr *LiteralString = nullptr; 11191 Expr *LiteralStringStripped = nullptr; 11192 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11193 !RHSStripped->isNullPointerConstant(S.Context, 11194 Expr::NPC_ValueDependentIsNull)) { 11195 LiteralString = LHS; 11196 LiteralStringStripped = LHSStripped; 11197 } else if ((isa<StringLiteral>(RHSStripped) || 11198 isa<ObjCEncodeExpr>(RHSStripped)) && 11199 !LHSStripped->isNullPointerConstant(S.Context, 11200 Expr::NPC_ValueDependentIsNull)) { 11201 LiteralString = RHS; 11202 LiteralStringStripped = RHSStripped; 11203 } 11204 11205 if (LiteralString) { 11206 S.DiagRuntimeBehavior(Loc, nullptr, 11207 S.PDiag(diag::warn_stringcompare) 11208 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11209 << LiteralString->getSourceRange()); 11210 } 11211 } 11212 11213 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11214 switch (CK) { 11215 default: { 11216 #ifndef NDEBUG 11217 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11218 << "\n"; 11219 #endif 11220 llvm_unreachable("unhandled cast kind"); 11221 } 11222 case CK_UserDefinedConversion: 11223 return ICK_Identity; 11224 case CK_LValueToRValue: 11225 return ICK_Lvalue_To_Rvalue; 11226 case CK_ArrayToPointerDecay: 11227 return ICK_Array_To_Pointer; 11228 case CK_FunctionToPointerDecay: 11229 return ICK_Function_To_Pointer; 11230 case CK_IntegralCast: 11231 return ICK_Integral_Conversion; 11232 case CK_FloatingCast: 11233 return ICK_Floating_Conversion; 11234 case CK_IntegralToFloating: 11235 case CK_FloatingToIntegral: 11236 return ICK_Floating_Integral; 11237 case CK_IntegralComplexCast: 11238 case CK_FloatingComplexCast: 11239 case CK_FloatingComplexToIntegralComplex: 11240 case CK_IntegralComplexToFloatingComplex: 11241 return ICK_Complex_Conversion; 11242 case CK_FloatingComplexToReal: 11243 case CK_FloatingRealToComplex: 11244 case CK_IntegralComplexToReal: 11245 case CK_IntegralRealToComplex: 11246 return ICK_Complex_Real; 11247 } 11248 } 11249 11250 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11251 QualType FromType, 11252 SourceLocation Loc) { 11253 // Check for a narrowing implicit conversion. 11254 StandardConversionSequence SCS; 11255 SCS.setAsIdentityConversion(); 11256 SCS.setToType(0, FromType); 11257 SCS.setToType(1, ToType); 11258 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11259 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11260 11261 APValue PreNarrowingValue; 11262 QualType PreNarrowingType; 11263 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11264 PreNarrowingType, 11265 /*IgnoreFloatToIntegralConversion*/ true)) { 11266 case NK_Dependent_Narrowing: 11267 // Implicit conversion to a narrower type, but the expression is 11268 // value-dependent so we can't tell whether it's actually narrowing. 11269 case NK_Not_Narrowing: 11270 return false; 11271 11272 case NK_Constant_Narrowing: 11273 // Implicit conversion to a narrower type, and the value is not a constant 11274 // expression. 11275 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11276 << /*Constant*/ 1 11277 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11278 return true; 11279 11280 case NK_Variable_Narrowing: 11281 // Implicit conversion to a narrower type, and the value is not a constant 11282 // expression. 11283 case NK_Type_Narrowing: 11284 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11285 << /*Constant*/ 0 << FromType << ToType; 11286 // TODO: It's not a constant expression, but what if the user intended it 11287 // to be? Can we produce notes to help them figure out why it isn't? 11288 return true; 11289 } 11290 llvm_unreachable("unhandled case in switch"); 11291 } 11292 11293 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11294 ExprResult &LHS, 11295 ExprResult &RHS, 11296 SourceLocation Loc) { 11297 QualType LHSType = LHS.get()->getType(); 11298 QualType RHSType = RHS.get()->getType(); 11299 // Dig out the original argument type and expression before implicit casts 11300 // were applied. These are the types/expressions we need to check the 11301 // [expr.spaceship] requirements against. 11302 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11303 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11304 QualType LHSStrippedType = LHSStripped.get()->getType(); 11305 QualType RHSStrippedType = RHSStripped.get()->getType(); 11306 11307 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11308 // other is not, the program is ill-formed. 11309 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11310 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11311 return QualType(); 11312 } 11313 11314 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11315 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11316 RHSStrippedType->isEnumeralType(); 11317 if (NumEnumArgs == 1) { 11318 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11319 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11320 if (OtherTy->hasFloatingRepresentation()) { 11321 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11322 return QualType(); 11323 } 11324 } 11325 if (NumEnumArgs == 2) { 11326 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11327 // type E, the operator yields the result of converting the operands 11328 // to the underlying type of E and applying <=> to the converted operands. 11329 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11330 S.InvalidOperands(Loc, LHS, RHS); 11331 return QualType(); 11332 } 11333 QualType IntType = 11334 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11335 assert(IntType->isArithmeticType()); 11336 11337 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11338 // promote the boolean type, and all other promotable integer types, to 11339 // avoid this. 11340 if (IntType->isPromotableIntegerType()) 11341 IntType = S.Context.getPromotedIntegerType(IntType); 11342 11343 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11344 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11345 LHSType = RHSType = IntType; 11346 } 11347 11348 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11349 // usual arithmetic conversions are applied to the operands. 11350 QualType Type = 11351 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11352 if (LHS.isInvalid() || RHS.isInvalid()) 11353 return QualType(); 11354 if (Type.isNull()) 11355 return S.InvalidOperands(Loc, LHS, RHS); 11356 11357 Optional<ComparisonCategoryType> CCT = 11358 getComparisonCategoryForBuiltinCmp(Type); 11359 if (!CCT) 11360 return S.InvalidOperands(Loc, LHS, RHS); 11361 11362 bool HasNarrowing = checkThreeWayNarrowingConversion( 11363 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11364 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11365 RHS.get()->getBeginLoc()); 11366 if (HasNarrowing) 11367 return QualType(); 11368 11369 assert(!Type.isNull() && "composite type for <=> has not been set"); 11370 11371 return S.CheckComparisonCategoryType( 11372 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11373 } 11374 11375 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11376 ExprResult &RHS, 11377 SourceLocation Loc, 11378 BinaryOperatorKind Opc) { 11379 if (Opc == BO_Cmp) 11380 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11381 11382 // C99 6.5.8p3 / C99 6.5.9p4 11383 QualType Type = 11384 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11385 if (LHS.isInvalid() || RHS.isInvalid()) 11386 return QualType(); 11387 if (Type.isNull()) 11388 return S.InvalidOperands(Loc, LHS, RHS); 11389 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11390 11391 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11392 return S.InvalidOperands(Loc, LHS, RHS); 11393 11394 // Check for comparisons of floating point operands using != and ==. 11395 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11396 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11397 11398 // The result of comparisons is 'bool' in C++, 'int' in C. 11399 return S.Context.getLogicalOperationType(); 11400 } 11401 11402 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11403 if (!NullE.get()->getType()->isAnyPointerType()) 11404 return; 11405 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11406 if (!E.get()->getType()->isAnyPointerType() && 11407 E.get()->isNullPointerConstant(Context, 11408 Expr::NPC_ValueDependentIsNotNull) == 11409 Expr::NPCK_ZeroExpression) { 11410 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11411 if (CL->getValue() == 0) 11412 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11413 << NullValue 11414 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11415 NullValue ? "NULL" : "(void *)0"); 11416 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11417 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11418 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11419 if (T == Context.CharTy) 11420 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11421 << NullValue 11422 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11423 NullValue ? "NULL" : "(void *)0"); 11424 } 11425 } 11426 } 11427 11428 // C99 6.5.8, C++ [expr.rel] 11429 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11430 SourceLocation Loc, 11431 BinaryOperatorKind Opc) { 11432 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11433 bool IsThreeWay = Opc == BO_Cmp; 11434 bool IsOrdered = IsRelational || IsThreeWay; 11435 auto IsAnyPointerType = [](ExprResult E) { 11436 QualType Ty = E.get()->getType(); 11437 return Ty->isPointerType() || Ty->isMemberPointerType(); 11438 }; 11439 11440 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11441 // type, array-to-pointer, ..., conversions are performed on both operands to 11442 // bring them to their composite type. 11443 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11444 // any type-related checks. 11445 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11446 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11447 if (LHS.isInvalid()) 11448 return QualType(); 11449 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11450 if (RHS.isInvalid()) 11451 return QualType(); 11452 } else { 11453 LHS = DefaultLvalueConversion(LHS.get()); 11454 if (LHS.isInvalid()) 11455 return QualType(); 11456 RHS = DefaultLvalueConversion(RHS.get()); 11457 if (RHS.isInvalid()) 11458 return QualType(); 11459 } 11460 11461 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11462 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11463 CheckPtrComparisonWithNullChar(LHS, RHS); 11464 CheckPtrComparisonWithNullChar(RHS, LHS); 11465 } 11466 11467 // Handle vector comparisons separately. 11468 if (LHS.get()->getType()->isVectorType() || 11469 RHS.get()->getType()->isVectorType()) 11470 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11471 11472 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11473 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11474 11475 QualType LHSType = LHS.get()->getType(); 11476 QualType RHSType = RHS.get()->getType(); 11477 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11478 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11479 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11480 11481 const Expr::NullPointerConstantKind LHSNullKind = 11482 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11483 const Expr::NullPointerConstantKind RHSNullKind = 11484 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11485 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11486 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11487 11488 auto computeResultTy = [&]() { 11489 if (Opc != BO_Cmp) 11490 return Context.getLogicalOperationType(); 11491 assert(getLangOpts().CPlusPlus); 11492 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11493 11494 QualType CompositeTy = LHS.get()->getType(); 11495 assert(!CompositeTy->isReferenceType()); 11496 11497 Optional<ComparisonCategoryType> CCT = 11498 getComparisonCategoryForBuiltinCmp(CompositeTy); 11499 if (!CCT) 11500 return InvalidOperands(Loc, LHS, RHS); 11501 11502 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11503 // P0946R0: Comparisons between a null pointer constant and an object 11504 // pointer result in std::strong_equality, which is ill-formed under 11505 // P1959R0. 11506 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11507 << (LHSIsNull ? LHS.get()->getSourceRange() 11508 : RHS.get()->getSourceRange()); 11509 return QualType(); 11510 } 11511 11512 return CheckComparisonCategoryType( 11513 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11514 }; 11515 11516 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11517 bool IsEquality = Opc == BO_EQ; 11518 if (RHSIsNull) 11519 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11520 RHS.get()->getSourceRange()); 11521 else 11522 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11523 LHS.get()->getSourceRange()); 11524 } 11525 11526 if ((LHSType->isIntegerType() && !LHSIsNull) || 11527 (RHSType->isIntegerType() && !RHSIsNull)) { 11528 // Skip normal pointer conversion checks in this case; we have better 11529 // diagnostics for this below. 11530 } else if (getLangOpts().CPlusPlus) { 11531 // Equality comparison of a function pointer to a void pointer is invalid, 11532 // but we allow it as an extension. 11533 // FIXME: If we really want to allow this, should it be part of composite 11534 // pointer type computation so it works in conditionals too? 11535 if (!IsOrdered && 11536 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11537 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11538 // This is a gcc extension compatibility comparison. 11539 // In a SFINAE context, we treat this as a hard error to maintain 11540 // conformance with the C++ standard. 11541 diagnoseFunctionPointerToVoidComparison( 11542 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11543 11544 if (isSFINAEContext()) 11545 return QualType(); 11546 11547 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11548 return computeResultTy(); 11549 } 11550 11551 // C++ [expr.eq]p2: 11552 // If at least one operand is a pointer [...] bring them to their 11553 // composite pointer type. 11554 // C++ [expr.spaceship]p6 11555 // If at least one of the operands is of pointer type, [...] bring them 11556 // to their composite pointer type. 11557 // C++ [expr.rel]p2: 11558 // If both operands are pointers, [...] bring them to their composite 11559 // pointer type. 11560 // For <=>, the only valid non-pointer types are arrays and functions, and 11561 // we already decayed those, so this is really the same as the relational 11562 // comparison rule. 11563 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11564 (IsOrdered ? 2 : 1) && 11565 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11566 RHSType->isObjCObjectPointerType()))) { 11567 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11568 return QualType(); 11569 return computeResultTy(); 11570 } 11571 } else if (LHSType->isPointerType() && 11572 RHSType->isPointerType()) { // C99 6.5.8p2 11573 // All of the following pointer-related warnings are GCC extensions, except 11574 // when handling null pointer constants. 11575 QualType LCanPointeeTy = 11576 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11577 QualType RCanPointeeTy = 11578 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11579 11580 // C99 6.5.9p2 and C99 6.5.8p2 11581 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11582 RCanPointeeTy.getUnqualifiedType())) { 11583 if (IsRelational) { 11584 // Pointers both need to point to complete or incomplete types 11585 if ((LCanPointeeTy->isIncompleteType() != 11586 RCanPointeeTy->isIncompleteType()) && 11587 !getLangOpts().C11) { 11588 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11589 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11590 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11591 << RCanPointeeTy->isIncompleteType(); 11592 } 11593 if (LCanPointeeTy->isFunctionType()) { 11594 // Valid unless a relational comparison of function pointers 11595 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11596 << LHSType << RHSType << LHS.get()->getSourceRange() 11597 << RHS.get()->getSourceRange(); 11598 } 11599 } 11600 } else if (!IsRelational && 11601 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11602 // Valid unless comparison between non-null pointer and function pointer 11603 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11604 && !LHSIsNull && !RHSIsNull) 11605 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11606 /*isError*/false); 11607 } else { 11608 // Invalid 11609 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11610 } 11611 if (LCanPointeeTy != RCanPointeeTy) { 11612 // Treat NULL constant as a special case in OpenCL. 11613 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11614 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11615 Diag(Loc, 11616 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11617 << LHSType << RHSType << 0 /* comparison */ 11618 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11619 } 11620 } 11621 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11622 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11623 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11624 : CK_BitCast; 11625 if (LHSIsNull && !RHSIsNull) 11626 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11627 else 11628 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11629 } 11630 return computeResultTy(); 11631 } 11632 11633 if (getLangOpts().CPlusPlus) { 11634 // C++ [expr.eq]p4: 11635 // Two operands of type std::nullptr_t or one operand of type 11636 // std::nullptr_t and the other a null pointer constant compare equal. 11637 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11638 if (LHSType->isNullPtrType()) { 11639 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11640 return computeResultTy(); 11641 } 11642 if (RHSType->isNullPtrType()) { 11643 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11644 return computeResultTy(); 11645 } 11646 } 11647 11648 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11649 // These aren't covered by the composite pointer type rules. 11650 if (!IsOrdered && RHSType->isNullPtrType() && 11651 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11652 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11653 return computeResultTy(); 11654 } 11655 if (!IsOrdered && LHSType->isNullPtrType() && 11656 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11657 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11658 return computeResultTy(); 11659 } 11660 11661 if (IsRelational && 11662 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11663 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11664 // HACK: Relational comparison of nullptr_t against a pointer type is 11665 // invalid per DR583, but we allow it within std::less<> and friends, 11666 // since otherwise common uses of it break. 11667 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11668 // friends to have std::nullptr_t overload candidates. 11669 DeclContext *DC = CurContext; 11670 if (isa<FunctionDecl>(DC)) 11671 DC = DC->getParent(); 11672 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11673 if (CTSD->isInStdNamespace() && 11674 llvm::StringSwitch<bool>(CTSD->getName()) 11675 .Cases("less", "less_equal", "greater", "greater_equal", true) 11676 .Default(false)) { 11677 if (RHSType->isNullPtrType()) 11678 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11679 else 11680 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11681 return computeResultTy(); 11682 } 11683 } 11684 } 11685 11686 // C++ [expr.eq]p2: 11687 // If at least one operand is a pointer to member, [...] bring them to 11688 // their composite pointer type. 11689 if (!IsOrdered && 11690 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11691 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11692 return QualType(); 11693 else 11694 return computeResultTy(); 11695 } 11696 } 11697 11698 // Handle block pointer types. 11699 if (!IsOrdered && LHSType->isBlockPointerType() && 11700 RHSType->isBlockPointerType()) { 11701 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11702 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11703 11704 if (!LHSIsNull && !RHSIsNull && 11705 !Context.typesAreCompatible(lpointee, rpointee)) { 11706 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11707 << LHSType << RHSType << LHS.get()->getSourceRange() 11708 << RHS.get()->getSourceRange(); 11709 } 11710 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11711 return computeResultTy(); 11712 } 11713 11714 // Allow block pointers to be compared with null pointer constants. 11715 if (!IsOrdered 11716 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11717 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11718 if (!LHSIsNull && !RHSIsNull) { 11719 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11720 ->getPointeeType()->isVoidType()) 11721 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11722 ->getPointeeType()->isVoidType()))) 11723 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11724 << LHSType << RHSType << LHS.get()->getSourceRange() 11725 << RHS.get()->getSourceRange(); 11726 } 11727 if (LHSIsNull && !RHSIsNull) 11728 LHS = ImpCastExprToType(LHS.get(), RHSType, 11729 RHSType->isPointerType() ? CK_BitCast 11730 : CK_AnyPointerToBlockPointerCast); 11731 else 11732 RHS = ImpCastExprToType(RHS.get(), LHSType, 11733 LHSType->isPointerType() ? CK_BitCast 11734 : CK_AnyPointerToBlockPointerCast); 11735 return computeResultTy(); 11736 } 11737 11738 if (LHSType->isObjCObjectPointerType() || 11739 RHSType->isObjCObjectPointerType()) { 11740 const PointerType *LPT = LHSType->getAs<PointerType>(); 11741 const PointerType *RPT = RHSType->getAs<PointerType>(); 11742 if (LPT || RPT) { 11743 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11744 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11745 11746 if (!LPtrToVoid && !RPtrToVoid && 11747 !Context.typesAreCompatible(LHSType, RHSType)) { 11748 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11749 /*isError*/false); 11750 } 11751 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11752 // the RHS, but we have test coverage for this behavior. 11753 // FIXME: Consider using convertPointersToCompositeType in C++. 11754 if (LHSIsNull && !RHSIsNull) { 11755 Expr *E = LHS.get(); 11756 if (getLangOpts().ObjCAutoRefCount) 11757 CheckObjCConversion(SourceRange(), RHSType, E, 11758 CCK_ImplicitConversion); 11759 LHS = ImpCastExprToType(E, RHSType, 11760 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11761 } 11762 else { 11763 Expr *E = RHS.get(); 11764 if (getLangOpts().ObjCAutoRefCount) 11765 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11766 /*Diagnose=*/true, 11767 /*DiagnoseCFAudited=*/false, Opc); 11768 RHS = ImpCastExprToType(E, LHSType, 11769 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11770 } 11771 return computeResultTy(); 11772 } 11773 if (LHSType->isObjCObjectPointerType() && 11774 RHSType->isObjCObjectPointerType()) { 11775 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11776 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11777 /*isError*/false); 11778 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11779 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11780 11781 if (LHSIsNull && !RHSIsNull) 11782 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11783 else 11784 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11785 return computeResultTy(); 11786 } 11787 11788 if (!IsOrdered && LHSType->isBlockPointerType() && 11789 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11790 LHS = ImpCastExprToType(LHS.get(), RHSType, 11791 CK_BlockPointerToObjCPointerCast); 11792 return computeResultTy(); 11793 } else if (!IsOrdered && 11794 LHSType->isBlockCompatibleObjCPointerType(Context) && 11795 RHSType->isBlockPointerType()) { 11796 RHS = ImpCastExprToType(RHS.get(), LHSType, 11797 CK_BlockPointerToObjCPointerCast); 11798 return computeResultTy(); 11799 } 11800 } 11801 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11802 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11803 unsigned DiagID = 0; 11804 bool isError = false; 11805 if (LangOpts.DebuggerSupport) { 11806 // Under a debugger, allow the comparison of pointers to integers, 11807 // since users tend to want to compare addresses. 11808 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11809 (RHSIsNull && RHSType->isIntegerType())) { 11810 if (IsOrdered) { 11811 isError = getLangOpts().CPlusPlus; 11812 DiagID = 11813 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11814 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11815 } 11816 } else if (getLangOpts().CPlusPlus) { 11817 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11818 isError = true; 11819 } else if (IsOrdered) 11820 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11821 else 11822 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11823 11824 if (DiagID) { 11825 Diag(Loc, DiagID) 11826 << LHSType << RHSType << LHS.get()->getSourceRange() 11827 << RHS.get()->getSourceRange(); 11828 if (isError) 11829 return QualType(); 11830 } 11831 11832 if (LHSType->isIntegerType()) 11833 LHS = ImpCastExprToType(LHS.get(), RHSType, 11834 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11835 else 11836 RHS = ImpCastExprToType(RHS.get(), LHSType, 11837 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11838 return computeResultTy(); 11839 } 11840 11841 // Handle block pointers. 11842 if (!IsOrdered && RHSIsNull 11843 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11844 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11845 return computeResultTy(); 11846 } 11847 if (!IsOrdered && LHSIsNull 11848 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11849 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11850 return computeResultTy(); 11851 } 11852 11853 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11854 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11855 return computeResultTy(); 11856 } 11857 11858 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11859 return computeResultTy(); 11860 } 11861 11862 if (LHSIsNull && RHSType->isQueueT()) { 11863 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11864 return computeResultTy(); 11865 } 11866 11867 if (LHSType->isQueueT() && RHSIsNull) { 11868 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11869 return computeResultTy(); 11870 } 11871 } 11872 11873 return InvalidOperands(Loc, LHS, RHS); 11874 } 11875 11876 // Return a signed ext_vector_type that is of identical size and number of 11877 // elements. For floating point vectors, return an integer type of identical 11878 // size and number of elements. In the non ext_vector_type case, search from 11879 // the largest type to the smallest type to avoid cases where long long == long, 11880 // where long gets picked over long long. 11881 QualType Sema::GetSignedVectorType(QualType V) { 11882 const VectorType *VTy = V->castAs<VectorType>(); 11883 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11884 11885 if (isa<ExtVectorType>(VTy)) { 11886 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11887 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11888 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11889 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11890 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11891 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11892 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11893 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11894 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11895 "Unhandled vector element size in vector compare"); 11896 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11897 } 11898 11899 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11900 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11901 VectorType::GenericVector); 11902 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11903 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11904 VectorType::GenericVector); 11905 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11906 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11907 VectorType::GenericVector); 11908 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11909 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11910 VectorType::GenericVector); 11911 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11912 "Unhandled vector element size in vector compare"); 11913 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11914 VectorType::GenericVector); 11915 } 11916 11917 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11918 /// operates on extended vector types. Instead of producing an IntTy result, 11919 /// like a scalar comparison, a vector comparison produces a vector of integer 11920 /// types. 11921 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11922 SourceLocation Loc, 11923 BinaryOperatorKind Opc) { 11924 if (Opc == BO_Cmp) { 11925 Diag(Loc, diag::err_three_way_vector_comparison); 11926 return QualType(); 11927 } 11928 11929 // Check to make sure we're operating on vectors of the same type and width, 11930 // Allowing one side to be a scalar of element type. 11931 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11932 /*AllowBothBool*/true, 11933 /*AllowBoolConversions*/getLangOpts().ZVector); 11934 if (vType.isNull()) 11935 return vType; 11936 11937 QualType LHSType = LHS.get()->getType(); 11938 11939 // If AltiVec, the comparison results in a numeric type, i.e. 11940 // bool for C++, int for C 11941 if (getLangOpts().AltiVec && 11942 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11943 return Context.getLogicalOperationType(); 11944 11945 // For non-floating point types, check for self-comparisons of the form 11946 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11947 // often indicate logic errors in the program. 11948 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11949 11950 // Check for comparisons of floating point operands using != and ==. 11951 if (BinaryOperator::isEqualityOp(Opc) && 11952 LHSType->hasFloatingRepresentation()) { 11953 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11954 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11955 } 11956 11957 // Return a signed type for the vector. 11958 return GetSignedVectorType(vType); 11959 } 11960 11961 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11962 const ExprResult &XorRHS, 11963 const SourceLocation Loc) { 11964 // Do not diagnose macros. 11965 if (Loc.isMacroID()) 11966 return; 11967 11968 bool Negative = false; 11969 bool ExplicitPlus = false; 11970 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11971 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11972 11973 if (!LHSInt) 11974 return; 11975 if (!RHSInt) { 11976 // Check negative literals. 11977 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11978 UnaryOperatorKind Opc = UO->getOpcode(); 11979 if (Opc != UO_Minus && Opc != UO_Plus) 11980 return; 11981 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11982 if (!RHSInt) 11983 return; 11984 Negative = (Opc == UO_Minus); 11985 ExplicitPlus = !Negative; 11986 } else { 11987 return; 11988 } 11989 } 11990 11991 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11992 llvm::APInt RightSideValue = RHSInt->getValue(); 11993 if (LeftSideValue != 2 && LeftSideValue != 10) 11994 return; 11995 11996 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11997 return; 11998 11999 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12000 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12001 llvm::StringRef ExprStr = 12002 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12003 12004 CharSourceRange XorRange = 12005 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12006 llvm::StringRef XorStr = 12007 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12008 // Do not diagnose if xor keyword/macro is used. 12009 if (XorStr == "xor") 12010 return; 12011 12012 std::string LHSStr = std::string(Lexer::getSourceText( 12013 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12014 S.getSourceManager(), S.getLangOpts())); 12015 std::string RHSStr = std::string(Lexer::getSourceText( 12016 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12017 S.getSourceManager(), S.getLangOpts())); 12018 12019 if (Negative) { 12020 RightSideValue = -RightSideValue; 12021 RHSStr = "-" + RHSStr; 12022 } else if (ExplicitPlus) { 12023 RHSStr = "+" + RHSStr; 12024 } 12025 12026 StringRef LHSStrRef = LHSStr; 12027 StringRef RHSStrRef = RHSStr; 12028 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12029 // literals. 12030 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12031 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12032 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12033 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12034 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12035 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12036 LHSStrRef.find('\'') != StringRef::npos || 12037 RHSStrRef.find('\'') != StringRef::npos) 12038 return; 12039 12040 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12041 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12042 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12043 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12044 std::string SuggestedExpr = "1 << " + RHSStr; 12045 bool Overflow = false; 12046 llvm::APInt One = (LeftSideValue - 1); 12047 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12048 if (Overflow) { 12049 if (RightSideIntValue < 64) 12050 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12051 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12052 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12053 else if (RightSideIntValue == 64) 12054 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12055 else 12056 return; 12057 } else { 12058 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12059 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12060 << PowValue.toString(10, true) 12061 << FixItHint::CreateReplacement( 12062 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12063 } 12064 12065 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12066 } else if (LeftSideValue == 10) { 12067 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12068 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12069 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12070 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12071 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12072 } 12073 } 12074 12075 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12076 SourceLocation Loc) { 12077 // Ensure that either both operands are of the same vector type, or 12078 // one operand is of a vector type and the other is of its element type. 12079 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12080 /*AllowBothBool*/true, 12081 /*AllowBoolConversions*/false); 12082 if (vType.isNull()) 12083 return InvalidOperands(Loc, LHS, RHS); 12084 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12085 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12086 return InvalidOperands(Loc, LHS, RHS); 12087 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12088 // usage of the logical operators && and || with vectors in C. This 12089 // check could be notionally dropped. 12090 if (!getLangOpts().CPlusPlus && 12091 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12092 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12093 12094 return GetSignedVectorType(LHS.get()->getType()); 12095 } 12096 12097 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12098 SourceLocation Loc, 12099 bool IsCompAssign) { 12100 if (!IsCompAssign) { 12101 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12102 if (LHS.isInvalid()) 12103 return QualType(); 12104 } 12105 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12106 if (RHS.isInvalid()) 12107 return QualType(); 12108 12109 // For conversion purposes, we ignore any qualifiers. 12110 // For example, "const float" and "float" are equivalent. 12111 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12112 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12113 12114 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12115 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12116 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12117 12118 if (Context.hasSameType(LHSType, RHSType)) 12119 return LHSType; 12120 12121 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12122 // case we have to return InvalidOperands. 12123 ExprResult OriginalLHS = LHS; 12124 ExprResult OriginalRHS = RHS; 12125 if (LHSMatType && !RHSMatType) { 12126 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12127 if (!RHS.isInvalid()) 12128 return LHSType; 12129 12130 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12131 } 12132 12133 if (!LHSMatType && RHSMatType) { 12134 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12135 if (!LHS.isInvalid()) 12136 return RHSType; 12137 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12138 } 12139 12140 return InvalidOperands(Loc, LHS, RHS); 12141 } 12142 12143 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12144 SourceLocation Loc, 12145 bool IsCompAssign) { 12146 if (!IsCompAssign) { 12147 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12148 if (LHS.isInvalid()) 12149 return QualType(); 12150 } 12151 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12152 if (RHS.isInvalid()) 12153 return QualType(); 12154 12155 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12156 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12157 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12158 12159 if (LHSMatType && RHSMatType) { 12160 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12161 return InvalidOperands(Loc, LHS, RHS); 12162 12163 if (!Context.hasSameType(LHSMatType->getElementType(), 12164 RHSMatType->getElementType())) 12165 return InvalidOperands(Loc, LHS, RHS); 12166 12167 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12168 LHSMatType->getNumRows(), 12169 RHSMatType->getNumColumns()); 12170 } 12171 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12172 } 12173 12174 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12175 SourceLocation Loc, 12176 BinaryOperatorKind Opc) { 12177 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12178 12179 bool IsCompAssign = 12180 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12181 12182 if (LHS.get()->getType()->isVectorType() || 12183 RHS.get()->getType()->isVectorType()) { 12184 if (LHS.get()->getType()->hasIntegerRepresentation() && 12185 RHS.get()->getType()->hasIntegerRepresentation()) 12186 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12187 /*AllowBothBool*/true, 12188 /*AllowBoolConversions*/getLangOpts().ZVector); 12189 return InvalidOperands(Loc, LHS, RHS); 12190 } 12191 12192 if (Opc == BO_And) 12193 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12194 12195 if (LHS.get()->getType()->hasFloatingRepresentation() || 12196 RHS.get()->getType()->hasFloatingRepresentation()) 12197 return InvalidOperands(Loc, LHS, RHS); 12198 12199 ExprResult LHSResult = LHS, RHSResult = RHS; 12200 QualType compType = UsualArithmeticConversions( 12201 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12202 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12203 return QualType(); 12204 LHS = LHSResult.get(); 12205 RHS = RHSResult.get(); 12206 12207 if (Opc == BO_Xor) 12208 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12209 12210 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12211 return compType; 12212 return InvalidOperands(Loc, LHS, RHS); 12213 } 12214 12215 // C99 6.5.[13,14] 12216 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12217 SourceLocation Loc, 12218 BinaryOperatorKind Opc) { 12219 // Check vector operands differently. 12220 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12221 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12222 12223 bool EnumConstantInBoolContext = false; 12224 for (const ExprResult &HS : {LHS, RHS}) { 12225 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12226 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12227 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12228 EnumConstantInBoolContext = true; 12229 } 12230 } 12231 12232 if (EnumConstantInBoolContext) 12233 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12234 12235 // Diagnose cases where the user write a logical and/or but probably meant a 12236 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12237 // is a constant. 12238 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12239 !LHS.get()->getType()->isBooleanType() && 12240 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12241 // Don't warn in macros or template instantiations. 12242 !Loc.isMacroID() && !inTemplateInstantiation()) { 12243 // If the RHS can be constant folded, and if it constant folds to something 12244 // that isn't 0 or 1 (which indicate a potential logical operation that 12245 // happened to fold to true/false) then warn. 12246 // Parens on the RHS are ignored. 12247 Expr::EvalResult EVResult; 12248 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12249 llvm::APSInt Result = EVResult.Val.getInt(); 12250 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12251 !RHS.get()->getExprLoc().isMacroID()) || 12252 (Result != 0 && Result != 1)) { 12253 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12254 << RHS.get()->getSourceRange() 12255 << (Opc == BO_LAnd ? "&&" : "||"); 12256 // Suggest replacing the logical operator with the bitwise version 12257 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12258 << (Opc == BO_LAnd ? "&" : "|") 12259 << FixItHint::CreateReplacement(SourceRange( 12260 Loc, getLocForEndOfToken(Loc)), 12261 Opc == BO_LAnd ? "&" : "|"); 12262 if (Opc == BO_LAnd) 12263 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12264 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12265 << FixItHint::CreateRemoval( 12266 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12267 RHS.get()->getEndLoc())); 12268 } 12269 } 12270 } 12271 12272 if (!Context.getLangOpts().CPlusPlus) { 12273 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12274 // not operate on the built-in scalar and vector float types. 12275 if (Context.getLangOpts().OpenCL && 12276 Context.getLangOpts().OpenCLVersion < 120) { 12277 if (LHS.get()->getType()->isFloatingType() || 12278 RHS.get()->getType()->isFloatingType()) 12279 return InvalidOperands(Loc, LHS, RHS); 12280 } 12281 12282 LHS = UsualUnaryConversions(LHS.get()); 12283 if (LHS.isInvalid()) 12284 return QualType(); 12285 12286 RHS = UsualUnaryConversions(RHS.get()); 12287 if (RHS.isInvalid()) 12288 return QualType(); 12289 12290 if (!LHS.get()->getType()->isScalarType() || 12291 !RHS.get()->getType()->isScalarType()) 12292 return InvalidOperands(Loc, LHS, RHS); 12293 12294 return Context.IntTy; 12295 } 12296 12297 // The following is safe because we only use this method for 12298 // non-overloadable operands. 12299 12300 // C++ [expr.log.and]p1 12301 // C++ [expr.log.or]p1 12302 // The operands are both contextually converted to type bool. 12303 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12304 if (LHSRes.isInvalid()) 12305 return InvalidOperands(Loc, LHS, RHS); 12306 LHS = LHSRes; 12307 12308 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12309 if (RHSRes.isInvalid()) 12310 return InvalidOperands(Loc, LHS, RHS); 12311 RHS = RHSRes; 12312 12313 // C++ [expr.log.and]p2 12314 // C++ [expr.log.or]p2 12315 // The result is a bool. 12316 return Context.BoolTy; 12317 } 12318 12319 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12320 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12321 if (!ME) return false; 12322 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12323 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12324 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12325 if (!Base) return false; 12326 return Base->getMethodDecl() != nullptr; 12327 } 12328 12329 /// Is the given expression (which must be 'const') a reference to a 12330 /// variable which was originally non-const, but which has become 12331 /// 'const' due to being captured within a block? 12332 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12333 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12334 assert(E->isLValue() && E->getType().isConstQualified()); 12335 E = E->IgnoreParens(); 12336 12337 // Must be a reference to a declaration from an enclosing scope. 12338 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12339 if (!DRE) return NCCK_None; 12340 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12341 12342 // The declaration must be a variable which is not declared 'const'. 12343 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12344 if (!var) return NCCK_None; 12345 if (var->getType().isConstQualified()) return NCCK_None; 12346 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12347 12348 // Decide whether the first capture was for a block or a lambda. 12349 DeclContext *DC = S.CurContext, *Prev = nullptr; 12350 // Decide whether the first capture was for a block or a lambda. 12351 while (DC) { 12352 // For init-capture, it is possible that the variable belongs to the 12353 // template pattern of the current context. 12354 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12355 if (var->isInitCapture() && 12356 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12357 break; 12358 if (DC == var->getDeclContext()) 12359 break; 12360 Prev = DC; 12361 DC = DC->getParent(); 12362 } 12363 // Unless we have an init-capture, we've gone one step too far. 12364 if (!var->isInitCapture()) 12365 DC = Prev; 12366 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12367 } 12368 12369 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12370 Ty = Ty.getNonReferenceType(); 12371 if (IsDereference && Ty->isPointerType()) 12372 Ty = Ty->getPointeeType(); 12373 return !Ty.isConstQualified(); 12374 } 12375 12376 // Update err_typecheck_assign_const and note_typecheck_assign_const 12377 // when this enum is changed. 12378 enum { 12379 ConstFunction, 12380 ConstVariable, 12381 ConstMember, 12382 ConstMethod, 12383 NestedConstMember, 12384 ConstUnknown, // Keep as last element 12385 }; 12386 12387 /// Emit the "read-only variable not assignable" error and print notes to give 12388 /// more information about why the variable is not assignable, such as pointing 12389 /// to the declaration of a const variable, showing that a method is const, or 12390 /// that the function is returning a const reference. 12391 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12392 SourceLocation Loc) { 12393 SourceRange ExprRange = E->getSourceRange(); 12394 12395 // Only emit one error on the first const found. All other consts will emit 12396 // a note to the error. 12397 bool DiagnosticEmitted = false; 12398 12399 // Track if the current expression is the result of a dereference, and if the 12400 // next checked expression is the result of a dereference. 12401 bool IsDereference = false; 12402 bool NextIsDereference = false; 12403 12404 // Loop to process MemberExpr chains. 12405 while (true) { 12406 IsDereference = NextIsDereference; 12407 12408 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12409 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12410 NextIsDereference = ME->isArrow(); 12411 const ValueDecl *VD = ME->getMemberDecl(); 12412 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12413 // Mutable fields can be modified even if the class is const. 12414 if (Field->isMutable()) { 12415 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12416 break; 12417 } 12418 12419 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12420 if (!DiagnosticEmitted) { 12421 S.Diag(Loc, diag::err_typecheck_assign_const) 12422 << ExprRange << ConstMember << false /*static*/ << Field 12423 << Field->getType(); 12424 DiagnosticEmitted = true; 12425 } 12426 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12427 << ConstMember << false /*static*/ << Field << Field->getType() 12428 << Field->getSourceRange(); 12429 } 12430 E = ME->getBase(); 12431 continue; 12432 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12433 if (VDecl->getType().isConstQualified()) { 12434 if (!DiagnosticEmitted) { 12435 S.Diag(Loc, diag::err_typecheck_assign_const) 12436 << ExprRange << ConstMember << true /*static*/ << VDecl 12437 << VDecl->getType(); 12438 DiagnosticEmitted = true; 12439 } 12440 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12441 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12442 << VDecl->getSourceRange(); 12443 } 12444 // Static fields do not inherit constness from parents. 12445 break; 12446 } 12447 break; // End MemberExpr 12448 } else if (const ArraySubscriptExpr *ASE = 12449 dyn_cast<ArraySubscriptExpr>(E)) { 12450 E = ASE->getBase()->IgnoreParenImpCasts(); 12451 continue; 12452 } else if (const ExtVectorElementExpr *EVE = 12453 dyn_cast<ExtVectorElementExpr>(E)) { 12454 E = EVE->getBase()->IgnoreParenImpCasts(); 12455 continue; 12456 } 12457 break; 12458 } 12459 12460 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12461 // Function calls 12462 const FunctionDecl *FD = CE->getDirectCallee(); 12463 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12464 if (!DiagnosticEmitted) { 12465 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12466 << ConstFunction << FD; 12467 DiagnosticEmitted = true; 12468 } 12469 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12470 diag::note_typecheck_assign_const) 12471 << ConstFunction << FD << FD->getReturnType() 12472 << FD->getReturnTypeSourceRange(); 12473 } 12474 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12475 // Point to variable declaration. 12476 if (const ValueDecl *VD = DRE->getDecl()) { 12477 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12478 if (!DiagnosticEmitted) { 12479 S.Diag(Loc, diag::err_typecheck_assign_const) 12480 << ExprRange << ConstVariable << VD << VD->getType(); 12481 DiagnosticEmitted = true; 12482 } 12483 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12484 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12485 } 12486 } 12487 } else if (isa<CXXThisExpr>(E)) { 12488 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12489 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12490 if (MD->isConst()) { 12491 if (!DiagnosticEmitted) { 12492 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12493 << ConstMethod << MD; 12494 DiagnosticEmitted = true; 12495 } 12496 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12497 << ConstMethod << MD << MD->getSourceRange(); 12498 } 12499 } 12500 } 12501 } 12502 12503 if (DiagnosticEmitted) 12504 return; 12505 12506 // Can't determine a more specific message, so display the generic error. 12507 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12508 } 12509 12510 enum OriginalExprKind { 12511 OEK_Variable, 12512 OEK_Member, 12513 OEK_LValue 12514 }; 12515 12516 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12517 const RecordType *Ty, 12518 SourceLocation Loc, SourceRange Range, 12519 OriginalExprKind OEK, 12520 bool &DiagnosticEmitted) { 12521 std::vector<const RecordType *> RecordTypeList; 12522 RecordTypeList.push_back(Ty); 12523 unsigned NextToCheckIndex = 0; 12524 // We walk the record hierarchy breadth-first to ensure that we print 12525 // diagnostics in field nesting order. 12526 while (RecordTypeList.size() > NextToCheckIndex) { 12527 bool IsNested = NextToCheckIndex > 0; 12528 for (const FieldDecl *Field : 12529 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12530 // First, check every field for constness. 12531 QualType FieldTy = Field->getType(); 12532 if (FieldTy.isConstQualified()) { 12533 if (!DiagnosticEmitted) { 12534 S.Diag(Loc, diag::err_typecheck_assign_const) 12535 << Range << NestedConstMember << OEK << VD 12536 << IsNested << Field; 12537 DiagnosticEmitted = true; 12538 } 12539 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12540 << NestedConstMember << IsNested << Field 12541 << FieldTy << Field->getSourceRange(); 12542 } 12543 12544 // Then we append it to the list to check next in order. 12545 FieldTy = FieldTy.getCanonicalType(); 12546 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12547 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12548 RecordTypeList.push_back(FieldRecTy); 12549 } 12550 } 12551 ++NextToCheckIndex; 12552 } 12553 } 12554 12555 /// Emit an error for the case where a record we are trying to assign to has a 12556 /// const-qualified field somewhere in its hierarchy. 12557 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12558 SourceLocation Loc) { 12559 QualType Ty = E->getType(); 12560 assert(Ty->isRecordType() && "lvalue was not record?"); 12561 SourceRange Range = E->getSourceRange(); 12562 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12563 bool DiagEmitted = false; 12564 12565 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12566 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12567 Range, OEK_Member, DiagEmitted); 12568 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12569 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12570 Range, OEK_Variable, DiagEmitted); 12571 else 12572 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12573 Range, OEK_LValue, DiagEmitted); 12574 if (!DiagEmitted) 12575 DiagnoseConstAssignment(S, E, Loc); 12576 } 12577 12578 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12579 /// emit an error and return true. If so, return false. 12580 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12581 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12582 12583 S.CheckShadowingDeclModification(E, Loc); 12584 12585 SourceLocation OrigLoc = Loc; 12586 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12587 &Loc); 12588 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12589 IsLV = Expr::MLV_InvalidMessageExpression; 12590 if (IsLV == Expr::MLV_Valid) 12591 return false; 12592 12593 unsigned DiagID = 0; 12594 bool NeedType = false; 12595 switch (IsLV) { // C99 6.5.16p2 12596 case Expr::MLV_ConstQualified: 12597 // Use a specialized diagnostic when we're assigning to an object 12598 // from an enclosing function or block. 12599 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12600 if (NCCK == NCCK_Block) 12601 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12602 else 12603 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12604 break; 12605 } 12606 12607 // In ARC, use some specialized diagnostics for occasions where we 12608 // infer 'const'. These are always pseudo-strong variables. 12609 if (S.getLangOpts().ObjCAutoRefCount) { 12610 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12611 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12612 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12613 12614 // Use the normal diagnostic if it's pseudo-__strong but the 12615 // user actually wrote 'const'. 12616 if (var->isARCPseudoStrong() && 12617 (!var->getTypeSourceInfo() || 12618 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12619 // There are three pseudo-strong cases: 12620 // - self 12621 ObjCMethodDecl *method = S.getCurMethodDecl(); 12622 if (method && var == method->getSelfDecl()) { 12623 DiagID = method->isClassMethod() 12624 ? diag::err_typecheck_arc_assign_self_class_method 12625 : diag::err_typecheck_arc_assign_self; 12626 12627 // - Objective-C externally_retained attribute. 12628 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12629 isa<ParmVarDecl>(var)) { 12630 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12631 12632 // - fast enumeration variables 12633 } else { 12634 DiagID = diag::err_typecheck_arr_assign_enumeration; 12635 } 12636 12637 SourceRange Assign; 12638 if (Loc != OrigLoc) 12639 Assign = SourceRange(OrigLoc, OrigLoc); 12640 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12641 // We need to preserve the AST regardless, so migration tool 12642 // can do its job. 12643 return false; 12644 } 12645 } 12646 } 12647 12648 // If none of the special cases above are triggered, then this is a 12649 // simple const assignment. 12650 if (DiagID == 0) { 12651 DiagnoseConstAssignment(S, E, Loc); 12652 return true; 12653 } 12654 12655 break; 12656 case Expr::MLV_ConstAddrSpace: 12657 DiagnoseConstAssignment(S, E, Loc); 12658 return true; 12659 case Expr::MLV_ConstQualifiedField: 12660 DiagnoseRecursiveConstFields(S, E, Loc); 12661 return true; 12662 case Expr::MLV_ArrayType: 12663 case Expr::MLV_ArrayTemporary: 12664 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12665 NeedType = true; 12666 break; 12667 case Expr::MLV_NotObjectType: 12668 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12669 NeedType = true; 12670 break; 12671 case Expr::MLV_LValueCast: 12672 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12673 break; 12674 case Expr::MLV_Valid: 12675 llvm_unreachable("did not take early return for MLV_Valid"); 12676 case Expr::MLV_InvalidExpression: 12677 case Expr::MLV_MemberFunction: 12678 case Expr::MLV_ClassTemporary: 12679 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12680 break; 12681 case Expr::MLV_IncompleteType: 12682 case Expr::MLV_IncompleteVoidType: 12683 return S.RequireCompleteType(Loc, E->getType(), 12684 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12685 case Expr::MLV_DuplicateVectorComponents: 12686 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12687 break; 12688 case Expr::MLV_NoSetterProperty: 12689 llvm_unreachable("readonly properties should be processed differently"); 12690 case Expr::MLV_InvalidMessageExpression: 12691 DiagID = diag::err_readonly_message_assignment; 12692 break; 12693 case Expr::MLV_SubObjCPropertySetting: 12694 DiagID = diag::err_no_subobject_property_setting; 12695 break; 12696 } 12697 12698 SourceRange Assign; 12699 if (Loc != OrigLoc) 12700 Assign = SourceRange(OrigLoc, OrigLoc); 12701 if (NeedType) 12702 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12703 else 12704 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12705 return true; 12706 } 12707 12708 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12709 SourceLocation Loc, 12710 Sema &Sema) { 12711 if (Sema.inTemplateInstantiation()) 12712 return; 12713 if (Sema.isUnevaluatedContext()) 12714 return; 12715 if (Loc.isInvalid() || Loc.isMacroID()) 12716 return; 12717 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12718 return; 12719 12720 // C / C++ fields 12721 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12722 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12723 if (ML && MR) { 12724 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12725 return; 12726 const ValueDecl *LHSDecl = 12727 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12728 const ValueDecl *RHSDecl = 12729 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12730 if (LHSDecl != RHSDecl) 12731 return; 12732 if (LHSDecl->getType().isVolatileQualified()) 12733 return; 12734 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12735 if (RefTy->getPointeeType().isVolatileQualified()) 12736 return; 12737 12738 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12739 } 12740 12741 // Objective-C instance variables 12742 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12743 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12744 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12745 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12746 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12747 if (RL && RR && RL->getDecl() == RR->getDecl()) 12748 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12749 } 12750 } 12751 12752 // C99 6.5.16.1 12753 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12754 SourceLocation Loc, 12755 QualType CompoundType) { 12756 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12757 12758 // Verify that LHS is a modifiable lvalue, and emit error if not. 12759 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12760 return QualType(); 12761 12762 QualType LHSType = LHSExpr->getType(); 12763 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12764 CompoundType; 12765 // OpenCL v1.2 s6.1.1.1 p2: 12766 // The half data type can only be used to declare a pointer to a buffer that 12767 // contains half values 12768 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12769 LHSType->isHalfType()) { 12770 Diag(Loc, diag::err_opencl_half_load_store) << 1 12771 << LHSType.getUnqualifiedType(); 12772 return QualType(); 12773 } 12774 12775 AssignConvertType ConvTy; 12776 if (CompoundType.isNull()) { 12777 Expr *RHSCheck = RHS.get(); 12778 12779 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12780 12781 QualType LHSTy(LHSType); 12782 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12783 if (RHS.isInvalid()) 12784 return QualType(); 12785 // Special case of NSObject attributes on c-style pointer types. 12786 if (ConvTy == IncompatiblePointer && 12787 ((Context.isObjCNSObjectType(LHSType) && 12788 RHSType->isObjCObjectPointerType()) || 12789 (Context.isObjCNSObjectType(RHSType) && 12790 LHSType->isObjCObjectPointerType()))) 12791 ConvTy = Compatible; 12792 12793 if (ConvTy == Compatible && 12794 LHSType->isObjCObjectType()) 12795 Diag(Loc, diag::err_objc_object_assignment) 12796 << LHSType; 12797 12798 // If the RHS is a unary plus or minus, check to see if they = and + are 12799 // right next to each other. If so, the user may have typo'd "x =+ 4" 12800 // instead of "x += 4". 12801 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12802 RHSCheck = ICE->getSubExpr(); 12803 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12804 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12805 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12806 // Only if the two operators are exactly adjacent. 12807 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12808 // And there is a space or other character before the subexpr of the 12809 // unary +/-. We don't want to warn on "x=-1". 12810 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12811 UO->getSubExpr()->getBeginLoc().isFileID()) { 12812 Diag(Loc, diag::warn_not_compound_assign) 12813 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12814 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12815 } 12816 } 12817 12818 if (ConvTy == Compatible) { 12819 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12820 // Warn about retain cycles where a block captures the LHS, but 12821 // not if the LHS is a simple variable into which the block is 12822 // being stored...unless that variable can be captured by reference! 12823 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12824 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12825 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12826 checkRetainCycles(LHSExpr, RHS.get()); 12827 } 12828 12829 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12830 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12831 // It is safe to assign a weak reference into a strong variable. 12832 // Although this code can still have problems: 12833 // id x = self.weakProp; 12834 // id y = self.weakProp; 12835 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12836 // paths through the function. This should be revisited if 12837 // -Wrepeated-use-of-weak is made flow-sensitive. 12838 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12839 // variable, which will be valid for the current autorelease scope. 12840 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12841 RHS.get()->getBeginLoc())) 12842 getCurFunction()->markSafeWeakUse(RHS.get()); 12843 12844 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12845 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12846 } 12847 } 12848 } else { 12849 // Compound assignment "x += y" 12850 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12851 } 12852 12853 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12854 RHS.get(), AA_Assigning)) 12855 return QualType(); 12856 12857 CheckForNullPointerDereference(*this, LHSExpr); 12858 12859 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12860 if (CompoundType.isNull()) { 12861 // C++2a [expr.ass]p5: 12862 // A simple-assignment whose left operand is of a volatile-qualified 12863 // type is deprecated unless the assignment is either a discarded-value 12864 // expression or an unevaluated operand 12865 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12866 } else { 12867 // C++2a [expr.ass]p6: 12868 // [Compound-assignment] expressions are deprecated if E1 has 12869 // volatile-qualified type 12870 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12871 } 12872 } 12873 12874 // C99 6.5.16p3: The type of an assignment expression is the type of the 12875 // left operand unless the left operand has qualified type, in which case 12876 // it is the unqualified version of the type of the left operand. 12877 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12878 // is converted to the type of the assignment expression (above). 12879 // C++ 5.17p1: the type of the assignment expression is that of its left 12880 // operand. 12881 return (getLangOpts().CPlusPlus 12882 ? LHSType : LHSType.getUnqualifiedType()); 12883 } 12884 12885 // Only ignore explicit casts to void. 12886 static bool IgnoreCommaOperand(const Expr *E) { 12887 E = E->IgnoreParens(); 12888 12889 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12890 if (CE->getCastKind() == CK_ToVoid) { 12891 return true; 12892 } 12893 12894 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12895 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12896 CE->getSubExpr()->getType()->isDependentType()) { 12897 return true; 12898 } 12899 } 12900 12901 return false; 12902 } 12903 12904 // Look for instances where it is likely the comma operator is confused with 12905 // another operator. There is an explicit list of acceptable expressions for 12906 // the left hand side of the comma operator, otherwise emit a warning. 12907 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12908 // No warnings in macros 12909 if (Loc.isMacroID()) 12910 return; 12911 12912 // Don't warn in template instantiations. 12913 if (inTemplateInstantiation()) 12914 return; 12915 12916 // Scope isn't fine-grained enough to explicitly list the specific cases, so 12917 // instead, skip more than needed, then call back into here with the 12918 // CommaVisitor in SemaStmt.cpp. 12919 // The listed locations are the initialization and increment portions 12920 // of a for loop. The additional checks are on the condition of 12921 // if statements, do/while loops, and for loops. 12922 // Differences in scope flags for C89 mode requires the extra logic. 12923 const unsigned ForIncrementFlags = 12924 getLangOpts().C99 || getLangOpts().CPlusPlus 12925 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12926 : Scope::ContinueScope | Scope::BreakScope; 12927 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12928 const unsigned ScopeFlags = getCurScope()->getFlags(); 12929 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12930 (ScopeFlags & ForInitFlags) == ForInitFlags) 12931 return; 12932 12933 // If there are multiple comma operators used together, get the RHS of the 12934 // of the comma operator as the LHS. 12935 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12936 if (BO->getOpcode() != BO_Comma) 12937 break; 12938 LHS = BO->getRHS(); 12939 } 12940 12941 // Only allow some expressions on LHS to not warn. 12942 if (IgnoreCommaOperand(LHS)) 12943 return; 12944 12945 Diag(Loc, diag::warn_comma_operator); 12946 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12947 << LHS->getSourceRange() 12948 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12949 LangOpts.CPlusPlus ? "static_cast<void>(" 12950 : "(void)(") 12951 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12952 ")"); 12953 } 12954 12955 // C99 6.5.17 12956 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12957 SourceLocation Loc) { 12958 LHS = S.CheckPlaceholderExpr(LHS.get()); 12959 RHS = S.CheckPlaceholderExpr(RHS.get()); 12960 if (LHS.isInvalid() || RHS.isInvalid()) 12961 return QualType(); 12962 12963 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12964 // operands, but not unary promotions. 12965 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12966 12967 // So we treat the LHS as a ignored value, and in C++ we allow the 12968 // containing site to determine what should be done with the RHS. 12969 LHS = S.IgnoredValueConversions(LHS.get()); 12970 if (LHS.isInvalid()) 12971 return QualType(); 12972 12973 S.DiagnoseUnusedExprResult(LHS.get()); 12974 12975 if (!S.getLangOpts().CPlusPlus) { 12976 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12977 if (RHS.isInvalid()) 12978 return QualType(); 12979 if (!RHS.get()->getType()->isVoidType()) 12980 S.RequireCompleteType(Loc, RHS.get()->getType(), 12981 diag::err_incomplete_type); 12982 } 12983 12984 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12985 S.DiagnoseCommaOperator(LHS.get(), Loc); 12986 12987 return RHS.get()->getType(); 12988 } 12989 12990 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12991 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12992 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12993 ExprValueKind &VK, 12994 ExprObjectKind &OK, 12995 SourceLocation OpLoc, 12996 bool IsInc, bool IsPrefix) { 12997 if (Op->isTypeDependent()) 12998 return S.Context.DependentTy; 12999 13000 QualType ResType = Op->getType(); 13001 // Atomic types can be used for increment / decrement where the non-atomic 13002 // versions can, so ignore the _Atomic() specifier for the purpose of 13003 // checking. 13004 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13005 ResType = ResAtomicType->getValueType(); 13006 13007 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13008 13009 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13010 // Decrement of bool is not allowed. 13011 if (!IsInc) { 13012 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13013 return QualType(); 13014 } 13015 // Increment of bool sets it to true, but is deprecated. 13016 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13017 : diag::warn_increment_bool) 13018 << Op->getSourceRange(); 13019 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13020 // Error on enum increments and decrements in C++ mode 13021 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13022 return QualType(); 13023 } else if (ResType->isRealType()) { 13024 // OK! 13025 } else if (ResType->isPointerType()) { 13026 // C99 6.5.2.4p2, 6.5.6p2 13027 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13028 return QualType(); 13029 } else if (ResType->isObjCObjectPointerType()) { 13030 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13031 // Otherwise, we just need a complete type. 13032 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13033 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13034 return QualType(); 13035 } else if (ResType->isAnyComplexType()) { 13036 // C99 does not support ++/-- on complex types, we allow as an extension. 13037 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13038 << ResType << Op->getSourceRange(); 13039 } else if (ResType->isPlaceholderType()) { 13040 ExprResult PR = S.CheckPlaceholderExpr(Op); 13041 if (PR.isInvalid()) return QualType(); 13042 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13043 IsInc, IsPrefix); 13044 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13045 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13046 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13047 (ResType->castAs<VectorType>()->getVectorKind() != 13048 VectorType::AltiVecBool)) { 13049 // The z vector extensions allow ++ and -- for non-bool vectors. 13050 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13051 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13052 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13053 } else { 13054 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13055 << ResType << int(IsInc) << Op->getSourceRange(); 13056 return QualType(); 13057 } 13058 // At this point, we know we have a real, complex or pointer type. 13059 // Now make sure the operand is a modifiable lvalue. 13060 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13061 return QualType(); 13062 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13063 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13064 // An operand with volatile-qualified type is deprecated 13065 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13066 << IsInc << ResType; 13067 } 13068 // In C++, a prefix increment is the same type as the operand. Otherwise 13069 // (in C or with postfix), the increment is the unqualified type of the 13070 // operand. 13071 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13072 VK = VK_LValue; 13073 OK = Op->getObjectKind(); 13074 return ResType; 13075 } else { 13076 VK = VK_RValue; 13077 return ResType.getUnqualifiedType(); 13078 } 13079 } 13080 13081 13082 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13083 /// This routine allows us to typecheck complex/recursive expressions 13084 /// where the declaration is needed for type checking. We only need to 13085 /// handle cases when the expression references a function designator 13086 /// or is an lvalue. Here are some examples: 13087 /// - &(x) => x 13088 /// - &*****f => f for f a function designator. 13089 /// - &s.xx => s 13090 /// - &s.zz[1].yy -> s, if zz is an array 13091 /// - *(x + 1) -> x, if x is an array 13092 /// - &"123"[2] -> 0 13093 /// - & __real__ x -> x 13094 /// 13095 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13096 /// members. 13097 static ValueDecl *getPrimaryDecl(Expr *E) { 13098 switch (E->getStmtClass()) { 13099 case Stmt::DeclRefExprClass: 13100 return cast<DeclRefExpr>(E)->getDecl(); 13101 case Stmt::MemberExprClass: 13102 // If this is an arrow operator, the address is an offset from 13103 // the base's value, so the object the base refers to is 13104 // irrelevant. 13105 if (cast<MemberExpr>(E)->isArrow()) 13106 return nullptr; 13107 // Otherwise, the expression refers to a part of the base 13108 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13109 case Stmt::ArraySubscriptExprClass: { 13110 // FIXME: This code shouldn't be necessary! We should catch the implicit 13111 // promotion of register arrays earlier. 13112 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13113 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13114 if (ICE->getSubExpr()->getType()->isArrayType()) 13115 return getPrimaryDecl(ICE->getSubExpr()); 13116 } 13117 return nullptr; 13118 } 13119 case Stmt::UnaryOperatorClass: { 13120 UnaryOperator *UO = cast<UnaryOperator>(E); 13121 13122 switch(UO->getOpcode()) { 13123 case UO_Real: 13124 case UO_Imag: 13125 case UO_Extension: 13126 return getPrimaryDecl(UO->getSubExpr()); 13127 default: 13128 return nullptr; 13129 } 13130 } 13131 case Stmt::ParenExprClass: 13132 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13133 case Stmt::ImplicitCastExprClass: 13134 // If the result of an implicit cast is an l-value, we care about 13135 // the sub-expression; otherwise, the result here doesn't matter. 13136 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13137 case Stmt::CXXUuidofExprClass: 13138 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13139 default: 13140 return nullptr; 13141 } 13142 } 13143 13144 namespace { 13145 enum { 13146 AO_Bit_Field = 0, 13147 AO_Vector_Element = 1, 13148 AO_Property_Expansion = 2, 13149 AO_Register_Variable = 3, 13150 AO_Matrix_Element = 4, 13151 AO_No_Error = 5 13152 }; 13153 } 13154 /// Diagnose invalid operand for address of operations. 13155 /// 13156 /// \param Type The type of operand which cannot have its address taken. 13157 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13158 Expr *E, unsigned Type) { 13159 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13160 } 13161 13162 /// CheckAddressOfOperand - The operand of & must be either a function 13163 /// designator or an lvalue designating an object. If it is an lvalue, the 13164 /// object cannot be declared with storage class register or be a bit field. 13165 /// Note: The usual conversions are *not* applied to the operand of the & 13166 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13167 /// In C++, the operand might be an overloaded function name, in which case 13168 /// we allow the '&' but retain the overloaded-function type. 13169 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13170 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13171 if (PTy->getKind() == BuiltinType::Overload) { 13172 Expr *E = OrigOp.get()->IgnoreParens(); 13173 if (!isa<OverloadExpr>(E)) { 13174 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13175 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13176 << OrigOp.get()->getSourceRange(); 13177 return QualType(); 13178 } 13179 13180 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13181 if (isa<UnresolvedMemberExpr>(Ovl)) 13182 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13183 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13184 << OrigOp.get()->getSourceRange(); 13185 return QualType(); 13186 } 13187 13188 return Context.OverloadTy; 13189 } 13190 13191 if (PTy->getKind() == BuiltinType::UnknownAny) 13192 return Context.UnknownAnyTy; 13193 13194 if (PTy->getKind() == BuiltinType::BoundMember) { 13195 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13196 << OrigOp.get()->getSourceRange(); 13197 return QualType(); 13198 } 13199 13200 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13201 if (OrigOp.isInvalid()) return QualType(); 13202 } 13203 13204 if (OrigOp.get()->isTypeDependent()) 13205 return Context.DependentTy; 13206 13207 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13208 13209 // Make sure to ignore parentheses in subsequent checks 13210 Expr *op = OrigOp.get()->IgnoreParens(); 13211 13212 // In OpenCL captures for blocks called as lambda functions 13213 // are located in the private address space. Blocks used in 13214 // enqueue_kernel can be located in a different address space 13215 // depending on a vendor implementation. Thus preventing 13216 // taking an address of the capture to avoid invalid AS casts. 13217 if (LangOpts.OpenCL) { 13218 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13219 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13220 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13221 return QualType(); 13222 } 13223 } 13224 13225 if (getLangOpts().C99) { 13226 // Implement C99-only parts of addressof rules. 13227 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13228 if (uOp->getOpcode() == UO_Deref) 13229 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13230 // (assuming the deref expression is valid). 13231 return uOp->getSubExpr()->getType(); 13232 } 13233 // Technically, there should be a check for array subscript 13234 // expressions here, but the result of one is always an lvalue anyway. 13235 } 13236 ValueDecl *dcl = getPrimaryDecl(op); 13237 13238 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13239 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13240 op->getBeginLoc())) 13241 return QualType(); 13242 13243 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13244 unsigned AddressOfError = AO_No_Error; 13245 13246 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13247 bool sfinae = (bool)isSFINAEContext(); 13248 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13249 : diag::ext_typecheck_addrof_temporary) 13250 << op->getType() << op->getSourceRange(); 13251 if (sfinae) 13252 return QualType(); 13253 // Materialize the temporary as an lvalue so that we can take its address. 13254 OrigOp = op = 13255 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13256 } else if (isa<ObjCSelectorExpr>(op)) { 13257 return Context.getPointerType(op->getType()); 13258 } else if (lval == Expr::LV_MemberFunction) { 13259 // If it's an instance method, make a member pointer. 13260 // The expression must have exactly the form &A::foo. 13261 13262 // If the underlying expression isn't a decl ref, give up. 13263 if (!isa<DeclRefExpr>(op)) { 13264 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13265 << OrigOp.get()->getSourceRange(); 13266 return QualType(); 13267 } 13268 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13269 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13270 13271 // The id-expression was parenthesized. 13272 if (OrigOp.get() != DRE) { 13273 Diag(OpLoc, diag::err_parens_pointer_member_function) 13274 << OrigOp.get()->getSourceRange(); 13275 13276 // The method was named without a qualifier. 13277 } else if (!DRE->getQualifier()) { 13278 if (MD->getParent()->getName().empty()) 13279 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13280 << op->getSourceRange(); 13281 else { 13282 SmallString<32> Str; 13283 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13284 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13285 << op->getSourceRange() 13286 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13287 } 13288 } 13289 13290 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13291 if (isa<CXXDestructorDecl>(MD)) 13292 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13293 13294 QualType MPTy = Context.getMemberPointerType( 13295 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13296 // Under the MS ABI, lock down the inheritance model now. 13297 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13298 (void)isCompleteType(OpLoc, MPTy); 13299 return MPTy; 13300 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13301 // C99 6.5.3.2p1 13302 // The operand must be either an l-value or a function designator 13303 if (!op->getType()->isFunctionType()) { 13304 // Use a special diagnostic for loads from property references. 13305 if (isa<PseudoObjectExpr>(op)) { 13306 AddressOfError = AO_Property_Expansion; 13307 } else { 13308 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13309 << op->getType() << op->getSourceRange(); 13310 return QualType(); 13311 } 13312 } 13313 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13314 // The operand cannot be a bit-field 13315 AddressOfError = AO_Bit_Field; 13316 } else if (op->getObjectKind() == OK_VectorComponent) { 13317 // The operand cannot be an element of a vector 13318 AddressOfError = AO_Vector_Element; 13319 } else if (op->getObjectKind() == OK_MatrixComponent) { 13320 // The operand cannot be an element of a matrix. 13321 AddressOfError = AO_Matrix_Element; 13322 } else if (dcl) { // C99 6.5.3.2p1 13323 // We have an lvalue with a decl. Make sure the decl is not declared 13324 // with the register storage-class specifier. 13325 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13326 // in C++ it is not error to take address of a register 13327 // variable (c++03 7.1.1P3) 13328 if (vd->getStorageClass() == SC_Register && 13329 !getLangOpts().CPlusPlus) { 13330 AddressOfError = AO_Register_Variable; 13331 } 13332 } else if (isa<MSPropertyDecl>(dcl)) { 13333 AddressOfError = AO_Property_Expansion; 13334 } else if (isa<FunctionTemplateDecl>(dcl)) { 13335 return Context.OverloadTy; 13336 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13337 // Okay: we can take the address of a field. 13338 // Could be a pointer to member, though, if there is an explicit 13339 // scope qualifier for the class. 13340 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13341 DeclContext *Ctx = dcl->getDeclContext(); 13342 if (Ctx && Ctx->isRecord()) { 13343 if (dcl->getType()->isReferenceType()) { 13344 Diag(OpLoc, 13345 diag::err_cannot_form_pointer_to_member_of_reference_type) 13346 << dcl->getDeclName() << dcl->getType(); 13347 return QualType(); 13348 } 13349 13350 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13351 Ctx = Ctx->getParent(); 13352 13353 QualType MPTy = Context.getMemberPointerType( 13354 op->getType(), 13355 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13356 // Under the MS ABI, lock down the inheritance model now. 13357 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13358 (void)isCompleteType(OpLoc, MPTy); 13359 return MPTy; 13360 } 13361 } 13362 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13363 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13364 llvm_unreachable("Unknown/unexpected decl type"); 13365 } 13366 13367 if (AddressOfError != AO_No_Error) { 13368 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13369 return QualType(); 13370 } 13371 13372 if (lval == Expr::LV_IncompleteVoidType) { 13373 // Taking the address of a void variable is technically illegal, but we 13374 // allow it in cases which are otherwise valid. 13375 // Example: "extern void x; void* y = &x;". 13376 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13377 } 13378 13379 // If the operand has type "type", the result has type "pointer to type". 13380 if (op->getType()->isObjCObjectType()) 13381 return Context.getObjCObjectPointerType(op->getType()); 13382 13383 CheckAddressOfPackedMember(op); 13384 13385 return Context.getPointerType(op->getType()); 13386 } 13387 13388 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13389 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13390 if (!DRE) 13391 return; 13392 const Decl *D = DRE->getDecl(); 13393 if (!D) 13394 return; 13395 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13396 if (!Param) 13397 return; 13398 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13399 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13400 return; 13401 if (FunctionScopeInfo *FD = S.getCurFunction()) 13402 if (!FD->ModifiedNonNullParams.count(Param)) 13403 FD->ModifiedNonNullParams.insert(Param); 13404 } 13405 13406 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13407 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13408 SourceLocation OpLoc) { 13409 if (Op->isTypeDependent()) 13410 return S.Context.DependentTy; 13411 13412 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13413 if (ConvResult.isInvalid()) 13414 return QualType(); 13415 Op = ConvResult.get(); 13416 QualType OpTy = Op->getType(); 13417 QualType Result; 13418 13419 if (isa<CXXReinterpretCastExpr>(Op)) { 13420 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13421 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13422 Op->getSourceRange()); 13423 } 13424 13425 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13426 { 13427 Result = PT->getPointeeType(); 13428 } 13429 else if (const ObjCObjectPointerType *OPT = 13430 OpTy->getAs<ObjCObjectPointerType>()) 13431 Result = OPT->getPointeeType(); 13432 else { 13433 ExprResult PR = S.CheckPlaceholderExpr(Op); 13434 if (PR.isInvalid()) return QualType(); 13435 if (PR.get() != Op) 13436 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13437 } 13438 13439 if (Result.isNull()) { 13440 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13441 << OpTy << Op->getSourceRange(); 13442 return QualType(); 13443 } 13444 13445 // Note that per both C89 and C99, indirection is always legal, even if Result 13446 // is an incomplete type or void. It would be possible to warn about 13447 // dereferencing a void pointer, but it's completely well-defined, and such a 13448 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13449 // for pointers to 'void' but is fine for any other pointer type: 13450 // 13451 // C++ [expr.unary.op]p1: 13452 // [...] the expression to which [the unary * operator] is applied shall 13453 // be a pointer to an object type, or a pointer to a function type 13454 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13455 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13456 << OpTy << Op->getSourceRange(); 13457 13458 // Dereferences are usually l-values... 13459 VK = VK_LValue; 13460 13461 // ...except that certain expressions are never l-values in C. 13462 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13463 VK = VK_RValue; 13464 13465 return Result; 13466 } 13467 13468 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13469 BinaryOperatorKind Opc; 13470 switch (Kind) { 13471 default: llvm_unreachable("Unknown binop!"); 13472 case tok::periodstar: Opc = BO_PtrMemD; break; 13473 case tok::arrowstar: Opc = BO_PtrMemI; break; 13474 case tok::star: Opc = BO_Mul; break; 13475 case tok::slash: Opc = BO_Div; break; 13476 case tok::percent: Opc = BO_Rem; break; 13477 case tok::plus: Opc = BO_Add; break; 13478 case tok::minus: Opc = BO_Sub; break; 13479 case tok::lessless: Opc = BO_Shl; break; 13480 case tok::greatergreater: Opc = BO_Shr; break; 13481 case tok::lessequal: Opc = BO_LE; break; 13482 case tok::less: Opc = BO_LT; break; 13483 case tok::greaterequal: Opc = BO_GE; break; 13484 case tok::greater: Opc = BO_GT; break; 13485 case tok::exclaimequal: Opc = BO_NE; break; 13486 case tok::equalequal: Opc = BO_EQ; break; 13487 case tok::spaceship: Opc = BO_Cmp; break; 13488 case tok::amp: Opc = BO_And; break; 13489 case tok::caret: Opc = BO_Xor; break; 13490 case tok::pipe: Opc = BO_Or; break; 13491 case tok::ampamp: Opc = BO_LAnd; break; 13492 case tok::pipepipe: Opc = BO_LOr; break; 13493 case tok::equal: Opc = BO_Assign; break; 13494 case tok::starequal: Opc = BO_MulAssign; break; 13495 case tok::slashequal: Opc = BO_DivAssign; break; 13496 case tok::percentequal: Opc = BO_RemAssign; break; 13497 case tok::plusequal: Opc = BO_AddAssign; break; 13498 case tok::minusequal: Opc = BO_SubAssign; break; 13499 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13500 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13501 case tok::ampequal: Opc = BO_AndAssign; break; 13502 case tok::caretequal: Opc = BO_XorAssign; break; 13503 case tok::pipeequal: Opc = BO_OrAssign; break; 13504 case tok::comma: Opc = BO_Comma; break; 13505 } 13506 return Opc; 13507 } 13508 13509 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13510 tok::TokenKind Kind) { 13511 UnaryOperatorKind Opc; 13512 switch (Kind) { 13513 default: llvm_unreachable("Unknown unary op!"); 13514 case tok::plusplus: Opc = UO_PreInc; break; 13515 case tok::minusminus: Opc = UO_PreDec; break; 13516 case tok::amp: Opc = UO_AddrOf; break; 13517 case tok::star: Opc = UO_Deref; break; 13518 case tok::plus: Opc = UO_Plus; break; 13519 case tok::minus: Opc = UO_Minus; break; 13520 case tok::tilde: Opc = UO_Not; break; 13521 case tok::exclaim: Opc = UO_LNot; break; 13522 case tok::kw___real: Opc = UO_Real; break; 13523 case tok::kw___imag: Opc = UO_Imag; break; 13524 case tok::kw___extension__: Opc = UO_Extension; break; 13525 } 13526 return Opc; 13527 } 13528 13529 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13530 /// This warning suppressed in the event of macro expansions. 13531 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13532 SourceLocation OpLoc, bool IsBuiltin) { 13533 if (S.inTemplateInstantiation()) 13534 return; 13535 if (S.isUnevaluatedContext()) 13536 return; 13537 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13538 return; 13539 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13540 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13541 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13542 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13543 if (!LHSDeclRef || !RHSDeclRef || 13544 LHSDeclRef->getLocation().isMacroID() || 13545 RHSDeclRef->getLocation().isMacroID()) 13546 return; 13547 const ValueDecl *LHSDecl = 13548 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13549 const ValueDecl *RHSDecl = 13550 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13551 if (LHSDecl != RHSDecl) 13552 return; 13553 if (LHSDecl->getType().isVolatileQualified()) 13554 return; 13555 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13556 if (RefTy->getPointeeType().isVolatileQualified()) 13557 return; 13558 13559 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13560 : diag::warn_self_assignment_overloaded) 13561 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13562 << RHSExpr->getSourceRange(); 13563 } 13564 13565 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13566 /// is usually indicative of introspection within the Objective-C pointer. 13567 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13568 SourceLocation OpLoc) { 13569 if (!S.getLangOpts().ObjC) 13570 return; 13571 13572 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13573 const Expr *LHS = L.get(); 13574 const Expr *RHS = R.get(); 13575 13576 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13577 ObjCPointerExpr = LHS; 13578 OtherExpr = RHS; 13579 } 13580 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13581 ObjCPointerExpr = RHS; 13582 OtherExpr = LHS; 13583 } 13584 13585 // This warning is deliberately made very specific to reduce false 13586 // positives with logic that uses '&' for hashing. This logic mainly 13587 // looks for code trying to introspect into tagged pointers, which 13588 // code should generally never do. 13589 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13590 unsigned Diag = diag::warn_objc_pointer_masking; 13591 // Determine if we are introspecting the result of performSelectorXXX. 13592 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13593 // Special case messages to -performSelector and friends, which 13594 // can return non-pointer values boxed in a pointer value. 13595 // Some clients may wish to silence warnings in this subcase. 13596 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13597 Selector S = ME->getSelector(); 13598 StringRef SelArg0 = S.getNameForSlot(0); 13599 if (SelArg0.startswith("performSelector")) 13600 Diag = diag::warn_objc_pointer_masking_performSelector; 13601 } 13602 13603 S.Diag(OpLoc, Diag) 13604 << ObjCPointerExpr->getSourceRange(); 13605 } 13606 } 13607 13608 static NamedDecl *getDeclFromExpr(Expr *E) { 13609 if (!E) 13610 return nullptr; 13611 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13612 return DRE->getDecl(); 13613 if (auto *ME = dyn_cast<MemberExpr>(E)) 13614 return ME->getMemberDecl(); 13615 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13616 return IRE->getDecl(); 13617 return nullptr; 13618 } 13619 13620 // This helper function promotes a binary operator's operands (which are of a 13621 // half vector type) to a vector of floats and then truncates the result to 13622 // a vector of either half or short. 13623 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13624 BinaryOperatorKind Opc, QualType ResultTy, 13625 ExprValueKind VK, ExprObjectKind OK, 13626 bool IsCompAssign, SourceLocation OpLoc, 13627 FPOptionsOverride FPFeatures) { 13628 auto &Context = S.getASTContext(); 13629 assert((isVector(ResultTy, Context.HalfTy) || 13630 isVector(ResultTy, Context.ShortTy)) && 13631 "Result must be a vector of half or short"); 13632 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13633 isVector(RHS.get()->getType(), Context.HalfTy) && 13634 "both operands expected to be a half vector"); 13635 13636 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13637 QualType BinOpResTy = RHS.get()->getType(); 13638 13639 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13640 // change BinOpResTy to a vector of ints. 13641 if (isVector(ResultTy, Context.ShortTy)) 13642 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13643 13644 if (IsCompAssign) 13645 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13646 ResultTy, VK, OK, OpLoc, FPFeatures, 13647 BinOpResTy, BinOpResTy); 13648 13649 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13650 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13651 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13652 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13653 } 13654 13655 static std::pair<ExprResult, ExprResult> 13656 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13657 Expr *RHSExpr) { 13658 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13659 if (!S.getLangOpts().CPlusPlus) { 13660 // C cannot handle TypoExpr nodes on either side of a binop because it 13661 // doesn't handle dependent types properly, so make sure any TypoExprs have 13662 // been dealt with before checking the operands. 13663 LHS = S.CorrectDelayedTyposInExpr(LHS); 13664 RHS = S.CorrectDelayedTyposInExpr( 13665 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13666 [Opc, LHS](Expr *E) { 13667 if (Opc != BO_Assign) 13668 return ExprResult(E); 13669 // Avoid correcting the RHS to the same Expr as the LHS. 13670 Decl *D = getDeclFromExpr(E); 13671 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13672 }); 13673 } 13674 return std::make_pair(LHS, RHS); 13675 } 13676 13677 /// Returns true if conversion between vectors of halfs and vectors of floats 13678 /// is needed. 13679 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13680 Expr *E0, Expr *E1 = nullptr) { 13681 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13682 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13683 return false; 13684 13685 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13686 QualType Ty = E->IgnoreImplicit()->getType(); 13687 13688 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13689 // to vectors of floats. Although the element type of the vectors is __fp16, 13690 // the vectors shouldn't be treated as storage-only types. See the 13691 // discussion here: https://reviews.llvm.org/rG825235c140e7 13692 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13693 if (VT->getVectorKind() == VectorType::NeonVector) 13694 return false; 13695 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13696 } 13697 return false; 13698 }; 13699 13700 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13701 } 13702 13703 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13704 /// operator @p Opc at location @c TokLoc. This routine only supports 13705 /// built-in operations; ActOnBinOp handles overloaded operators. 13706 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13707 BinaryOperatorKind Opc, 13708 Expr *LHSExpr, Expr *RHSExpr) { 13709 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13710 // The syntax only allows initializer lists on the RHS of assignment, 13711 // so we don't need to worry about accepting invalid code for 13712 // non-assignment operators. 13713 // C++11 5.17p9: 13714 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13715 // of x = {} is x = T(). 13716 InitializationKind Kind = InitializationKind::CreateDirectList( 13717 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13718 InitializedEntity Entity = 13719 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13720 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13721 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13722 if (Init.isInvalid()) 13723 return Init; 13724 RHSExpr = Init.get(); 13725 } 13726 13727 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13728 QualType ResultTy; // Result type of the binary operator. 13729 // The following two variables are used for compound assignment operators 13730 QualType CompLHSTy; // Type of LHS after promotions for computation 13731 QualType CompResultTy; // Type of computation result 13732 ExprValueKind VK = VK_RValue; 13733 ExprObjectKind OK = OK_Ordinary; 13734 bool ConvertHalfVec = false; 13735 13736 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13737 if (!LHS.isUsable() || !RHS.isUsable()) 13738 return ExprError(); 13739 13740 if (getLangOpts().OpenCL) { 13741 QualType LHSTy = LHSExpr->getType(); 13742 QualType RHSTy = RHSExpr->getType(); 13743 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13744 // the ATOMIC_VAR_INIT macro. 13745 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13746 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13747 if (BO_Assign == Opc) 13748 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13749 else 13750 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13751 return ExprError(); 13752 } 13753 13754 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13755 // only with a builtin functions and therefore should be disallowed here. 13756 if (LHSTy->isImageType() || RHSTy->isImageType() || 13757 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13758 LHSTy->isPipeType() || RHSTy->isPipeType() || 13759 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13760 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13761 return ExprError(); 13762 } 13763 } 13764 13765 switch (Opc) { 13766 case BO_Assign: 13767 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13768 if (getLangOpts().CPlusPlus && 13769 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13770 VK = LHS.get()->getValueKind(); 13771 OK = LHS.get()->getObjectKind(); 13772 } 13773 if (!ResultTy.isNull()) { 13774 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13775 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13776 13777 // Avoid copying a block to the heap if the block is assigned to a local 13778 // auto variable that is declared in the same scope as the block. This 13779 // optimization is unsafe if the local variable is declared in an outer 13780 // scope. For example: 13781 // 13782 // BlockTy b; 13783 // { 13784 // b = ^{...}; 13785 // } 13786 // // It is unsafe to invoke the block here if it wasn't copied to the 13787 // // heap. 13788 // b(); 13789 13790 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13791 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13792 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13793 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13794 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13795 13796 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13797 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13798 NTCUC_Assignment, NTCUK_Copy); 13799 } 13800 RecordModifiableNonNullParam(*this, LHS.get()); 13801 break; 13802 case BO_PtrMemD: 13803 case BO_PtrMemI: 13804 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13805 Opc == BO_PtrMemI); 13806 break; 13807 case BO_Mul: 13808 case BO_Div: 13809 ConvertHalfVec = true; 13810 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13811 Opc == BO_Div); 13812 break; 13813 case BO_Rem: 13814 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13815 break; 13816 case BO_Add: 13817 ConvertHalfVec = true; 13818 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13819 break; 13820 case BO_Sub: 13821 ConvertHalfVec = true; 13822 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13823 break; 13824 case BO_Shl: 13825 case BO_Shr: 13826 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13827 break; 13828 case BO_LE: 13829 case BO_LT: 13830 case BO_GE: 13831 case BO_GT: 13832 ConvertHalfVec = true; 13833 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13834 break; 13835 case BO_EQ: 13836 case BO_NE: 13837 ConvertHalfVec = true; 13838 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13839 break; 13840 case BO_Cmp: 13841 ConvertHalfVec = true; 13842 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13843 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13844 break; 13845 case BO_And: 13846 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13847 LLVM_FALLTHROUGH; 13848 case BO_Xor: 13849 case BO_Or: 13850 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13851 break; 13852 case BO_LAnd: 13853 case BO_LOr: 13854 ConvertHalfVec = true; 13855 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13856 break; 13857 case BO_MulAssign: 13858 case BO_DivAssign: 13859 ConvertHalfVec = true; 13860 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13861 Opc == BO_DivAssign); 13862 CompLHSTy = CompResultTy; 13863 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13864 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13865 break; 13866 case BO_RemAssign: 13867 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13868 CompLHSTy = CompResultTy; 13869 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13870 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13871 break; 13872 case BO_AddAssign: 13873 ConvertHalfVec = true; 13874 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13875 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13876 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13877 break; 13878 case BO_SubAssign: 13879 ConvertHalfVec = true; 13880 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13881 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13882 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13883 break; 13884 case BO_ShlAssign: 13885 case BO_ShrAssign: 13886 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13887 CompLHSTy = CompResultTy; 13888 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13889 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13890 break; 13891 case BO_AndAssign: 13892 case BO_OrAssign: // fallthrough 13893 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13894 LLVM_FALLTHROUGH; 13895 case BO_XorAssign: 13896 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13897 CompLHSTy = CompResultTy; 13898 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13899 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13900 break; 13901 case BO_Comma: 13902 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13903 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13904 VK = RHS.get()->getValueKind(); 13905 OK = RHS.get()->getObjectKind(); 13906 } 13907 break; 13908 } 13909 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13910 return ExprError(); 13911 13912 // Some of the binary operations require promoting operands of half vector to 13913 // float vectors and truncating the result back to half vector. For now, we do 13914 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13915 // arm64). 13916 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13917 isVector(LHS.get()->getType(), Context.HalfTy) && 13918 "both sides are half vectors or neither sides are"); 13919 ConvertHalfVec = 13920 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13921 13922 // Check for array bounds violations for both sides of the BinaryOperator 13923 CheckArrayAccess(LHS.get()); 13924 CheckArrayAccess(RHS.get()); 13925 13926 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13927 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13928 &Context.Idents.get("object_setClass"), 13929 SourceLocation(), LookupOrdinaryName); 13930 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13931 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13932 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13933 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13934 "object_setClass(") 13935 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13936 ",") 13937 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13938 } 13939 else 13940 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13941 } 13942 else if (const ObjCIvarRefExpr *OIRE = 13943 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13944 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13945 13946 // Opc is not a compound assignment if CompResultTy is null. 13947 if (CompResultTy.isNull()) { 13948 if (ConvertHalfVec) 13949 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13950 OpLoc, CurFPFeatureOverrides()); 13951 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13952 VK, OK, OpLoc, CurFPFeatureOverrides()); 13953 } 13954 13955 // Handle compound assignments. 13956 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13957 OK_ObjCProperty) { 13958 VK = VK_LValue; 13959 OK = LHS.get()->getObjectKind(); 13960 } 13961 13962 // The LHS is not converted to the result type for fixed-point compound 13963 // assignment as the common type is computed on demand. Reset the CompLHSTy 13964 // to the LHS type we would have gotten after unary conversions. 13965 if (CompResultTy->isFixedPointType()) 13966 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13967 13968 if (ConvertHalfVec) 13969 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13970 OpLoc, CurFPFeatureOverrides()); 13971 13972 return CompoundAssignOperator::Create( 13973 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 13974 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 13975 } 13976 13977 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13978 /// operators are mixed in a way that suggests that the programmer forgot that 13979 /// comparison operators have higher precedence. The most typical example of 13980 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13981 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13982 SourceLocation OpLoc, Expr *LHSExpr, 13983 Expr *RHSExpr) { 13984 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13985 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13986 13987 // Check that one of the sides is a comparison operator and the other isn't. 13988 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13989 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13990 if (isLeftComp == isRightComp) 13991 return; 13992 13993 // Bitwise operations are sometimes used as eager logical ops. 13994 // Don't diagnose this. 13995 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13996 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13997 if (isLeftBitwise || isRightBitwise) 13998 return; 13999 14000 SourceRange DiagRange = isLeftComp 14001 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14002 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14003 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14004 SourceRange ParensRange = 14005 isLeftComp 14006 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14007 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14008 14009 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14010 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14011 SuggestParentheses(Self, OpLoc, 14012 Self.PDiag(diag::note_precedence_silence) << OpStr, 14013 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14014 SuggestParentheses(Self, OpLoc, 14015 Self.PDiag(diag::note_precedence_bitwise_first) 14016 << BinaryOperator::getOpcodeStr(Opc), 14017 ParensRange); 14018 } 14019 14020 /// It accepts a '&&' expr that is inside a '||' one. 14021 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14022 /// in parentheses. 14023 static void 14024 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14025 BinaryOperator *Bop) { 14026 assert(Bop->getOpcode() == BO_LAnd); 14027 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14028 << Bop->getSourceRange() << OpLoc; 14029 SuggestParentheses(Self, Bop->getOperatorLoc(), 14030 Self.PDiag(diag::note_precedence_silence) 14031 << Bop->getOpcodeStr(), 14032 Bop->getSourceRange()); 14033 } 14034 14035 /// Returns true if the given expression can be evaluated as a constant 14036 /// 'true'. 14037 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14038 bool Res; 14039 return !E->isValueDependent() && 14040 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14041 } 14042 14043 /// Returns true if the given expression can be evaluated as a constant 14044 /// 'false'. 14045 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14046 bool Res; 14047 return !E->isValueDependent() && 14048 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14049 } 14050 14051 /// Look for '&&' in the left hand of a '||' expr. 14052 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14053 Expr *LHSExpr, Expr *RHSExpr) { 14054 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14055 if (Bop->getOpcode() == BO_LAnd) { 14056 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14057 if (EvaluatesAsFalse(S, RHSExpr)) 14058 return; 14059 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14060 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14061 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14062 } else if (Bop->getOpcode() == BO_LOr) { 14063 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14064 // If it's "a || b && 1 || c" we didn't warn earlier for 14065 // "a || b && 1", but warn now. 14066 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14067 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14068 } 14069 } 14070 } 14071 } 14072 14073 /// Look for '&&' in the right hand of a '||' expr. 14074 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14075 Expr *LHSExpr, Expr *RHSExpr) { 14076 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14077 if (Bop->getOpcode() == BO_LAnd) { 14078 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14079 if (EvaluatesAsFalse(S, LHSExpr)) 14080 return; 14081 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14082 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14083 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14084 } 14085 } 14086 } 14087 14088 /// Look for bitwise op in the left or right hand of a bitwise op with 14089 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14090 /// the '&' expression in parentheses. 14091 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14092 SourceLocation OpLoc, Expr *SubExpr) { 14093 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14094 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14095 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14096 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14097 << Bop->getSourceRange() << OpLoc; 14098 SuggestParentheses(S, Bop->getOperatorLoc(), 14099 S.PDiag(diag::note_precedence_silence) 14100 << Bop->getOpcodeStr(), 14101 Bop->getSourceRange()); 14102 } 14103 } 14104 } 14105 14106 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14107 Expr *SubExpr, StringRef Shift) { 14108 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14109 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14110 StringRef Op = Bop->getOpcodeStr(); 14111 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14112 << Bop->getSourceRange() << OpLoc << Shift << Op; 14113 SuggestParentheses(S, Bop->getOperatorLoc(), 14114 S.PDiag(diag::note_precedence_silence) << Op, 14115 Bop->getSourceRange()); 14116 } 14117 } 14118 } 14119 14120 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14121 Expr *LHSExpr, Expr *RHSExpr) { 14122 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14123 if (!OCE) 14124 return; 14125 14126 FunctionDecl *FD = OCE->getDirectCallee(); 14127 if (!FD || !FD->isOverloadedOperator()) 14128 return; 14129 14130 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14131 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14132 return; 14133 14134 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14135 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14136 << (Kind == OO_LessLess); 14137 SuggestParentheses(S, OCE->getOperatorLoc(), 14138 S.PDiag(diag::note_precedence_silence) 14139 << (Kind == OO_LessLess ? "<<" : ">>"), 14140 OCE->getSourceRange()); 14141 SuggestParentheses( 14142 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14143 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14144 } 14145 14146 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14147 /// precedence. 14148 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14149 SourceLocation OpLoc, Expr *LHSExpr, 14150 Expr *RHSExpr){ 14151 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14152 if (BinaryOperator::isBitwiseOp(Opc)) 14153 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14154 14155 // Diagnose "arg1 & arg2 | arg3" 14156 if ((Opc == BO_Or || Opc == BO_Xor) && 14157 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14158 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14159 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14160 } 14161 14162 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14163 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14164 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14165 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14166 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14167 } 14168 14169 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14170 || Opc == BO_Shr) { 14171 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14172 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14173 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14174 } 14175 14176 // Warn on overloaded shift operators and comparisons, such as: 14177 // cout << 5 == 4; 14178 if (BinaryOperator::isComparisonOp(Opc)) 14179 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14180 } 14181 14182 // Binary Operators. 'Tok' is the token for the operator. 14183 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14184 tok::TokenKind Kind, 14185 Expr *LHSExpr, Expr *RHSExpr) { 14186 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14187 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14188 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14189 14190 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14191 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14192 14193 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14194 } 14195 14196 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14197 UnresolvedSetImpl &Functions) { 14198 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14199 if (OverOp != OO_None && OverOp != OO_Equal) 14200 LookupOverloadedOperatorName(OverOp, S, Functions); 14201 14202 // In C++20 onwards, we may have a second operator to look up. 14203 if (getLangOpts().CPlusPlus20) { 14204 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14205 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14206 } 14207 } 14208 14209 /// Build an overloaded binary operator expression in the given scope. 14210 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14211 BinaryOperatorKind Opc, 14212 Expr *LHS, Expr *RHS) { 14213 switch (Opc) { 14214 case BO_Assign: 14215 case BO_DivAssign: 14216 case BO_RemAssign: 14217 case BO_SubAssign: 14218 case BO_AndAssign: 14219 case BO_OrAssign: 14220 case BO_XorAssign: 14221 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14222 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14223 break; 14224 default: 14225 break; 14226 } 14227 14228 // Find all of the overloaded operators visible from this point. 14229 UnresolvedSet<16> Functions; 14230 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14231 14232 // Build the (potentially-overloaded, potentially-dependent) 14233 // binary operation. 14234 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14235 } 14236 14237 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14238 BinaryOperatorKind Opc, 14239 Expr *LHSExpr, Expr *RHSExpr) { 14240 ExprResult LHS, RHS; 14241 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14242 if (!LHS.isUsable() || !RHS.isUsable()) 14243 return ExprError(); 14244 LHSExpr = LHS.get(); 14245 RHSExpr = RHS.get(); 14246 14247 // We want to end up calling one of checkPseudoObjectAssignment 14248 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14249 // both expressions are overloadable or either is type-dependent), 14250 // or CreateBuiltinBinOp (in any other case). We also want to get 14251 // any placeholder types out of the way. 14252 14253 // Handle pseudo-objects in the LHS. 14254 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14255 // Assignments with a pseudo-object l-value need special analysis. 14256 if (pty->getKind() == BuiltinType::PseudoObject && 14257 BinaryOperator::isAssignmentOp(Opc)) 14258 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14259 14260 // Don't resolve overloads if the other type is overloadable. 14261 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14262 // We can't actually test that if we still have a placeholder, 14263 // though. Fortunately, none of the exceptions we see in that 14264 // code below are valid when the LHS is an overload set. Note 14265 // that an overload set can be dependently-typed, but it never 14266 // instantiates to having an overloadable type. 14267 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14268 if (resolvedRHS.isInvalid()) return ExprError(); 14269 RHSExpr = resolvedRHS.get(); 14270 14271 if (RHSExpr->isTypeDependent() || 14272 RHSExpr->getType()->isOverloadableType()) 14273 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14274 } 14275 14276 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14277 // template, diagnose the missing 'template' keyword instead of diagnosing 14278 // an invalid use of a bound member function. 14279 // 14280 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14281 // to C++1z [over.over]/1.4, but we already checked for that case above. 14282 if (Opc == BO_LT && inTemplateInstantiation() && 14283 (pty->getKind() == BuiltinType::BoundMember || 14284 pty->getKind() == BuiltinType::Overload)) { 14285 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14286 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14287 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14288 return isa<FunctionTemplateDecl>(ND); 14289 })) { 14290 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14291 : OE->getNameLoc(), 14292 diag::err_template_kw_missing) 14293 << OE->getName().getAsString() << ""; 14294 return ExprError(); 14295 } 14296 } 14297 14298 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14299 if (LHS.isInvalid()) return ExprError(); 14300 LHSExpr = LHS.get(); 14301 } 14302 14303 // Handle pseudo-objects in the RHS. 14304 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14305 // An overload in the RHS can potentially be resolved by the type 14306 // being assigned to. 14307 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14308 if (getLangOpts().CPlusPlus && 14309 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14310 LHSExpr->getType()->isOverloadableType())) 14311 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14312 14313 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14314 } 14315 14316 // Don't resolve overloads if the other type is overloadable. 14317 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14318 LHSExpr->getType()->isOverloadableType()) 14319 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14320 14321 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14322 if (!resolvedRHS.isUsable()) return ExprError(); 14323 RHSExpr = resolvedRHS.get(); 14324 } 14325 14326 if (getLangOpts().CPlusPlus) { 14327 // If either expression is type-dependent, always build an 14328 // overloaded op. 14329 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14330 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14331 14332 // Otherwise, build an overloaded op if either expression has an 14333 // overloadable type. 14334 if (LHSExpr->getType()->isOverloadableType() || 14335 RHSExpr->getType()->isOverloadableType()) 14336 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14337 } 14338 14339 // Build a built-in binary operation. 14340 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14341 } 14342 14343 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14344 if (T.isNull() || T->isDependentType()) 14345 return false; 14346 14347 if (!T->isPromotableIntegerType()) 14348 return true; 14349 14350 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14351 } 14352 14353 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14354 UnaryOperatorKind Opc, 14355 Expr *InputExpr) { 14356 ExprResult Input = InputExpr; 14357 ExprValueKind VK = VK_RValue; 14358 ExprObjectKind OK = OK_Ordinary; 14359 QualType resultType; 14360 bool CanOverflow = false; 14361 14362 bool ConvertHalfVec = false; 14363 if (getLangOpts().OpenCL) { 14364 QualType Ty = InputExpr->getType(); 14365 // The only legal unary operation for atomics is '&'. 14366 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14367 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14368 // only with a builtin functions and therefore should be disallowed here. 14369 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14370 || Ty->isBlockPointerType())) { 14371 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14372 << InputExpr->getType() 14373 << Input.get()->getSourceRange()); 14374 } 14375 } 14376 14377 switch (Opc) { 14378 case UO_PreInc: 14379 case UO_PreDec: 14380 case UO_PostInc: 14381 case UO_PostDec: 14382 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14383 OpLoc, 14384 Opc == UO_PreInc || 14385 Opc == UO_PostInc, 14386 Opc == UO_PreInc || 14387 Opc == UO_PreDec); 14388 CanOverflow = isOverflowingIntegerType(Context, resultType); 14389 break; 14390 case UO_AddrOf: 14391 resultType = CheckAddressOfOperand(Input, OpLoc); 14392 CheckAddressOfNoDeref(InputExpr); 14393 RecordModifiableNonNullParam(*this, InputExpr); 14394 break; 14395 case UO_Deref: { 14396 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14397 if (Input.isInvalid()) return ExprError(); 14398 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14399 break; 14400 } 14401 case UO_Plus: 14402 case UO_Minus: 14403 CanOverflow = Opc == UO_Minus && 14404 isOverflowingIntegerType(Context, Input.get()->getType()); 14405 Input = UsualUnaryConversions(Input.get()); 14406 if (Input.isInvalid()) return ExprError(); 14407 // Unary plus and minus require promoting an operand of half vector to a 14408 // float vector and truncating the result back to a half vector. For now, we 14409 // do this only when HalfArgsAndReturns is set (that is, when the target is 14410 // arm or arm64). 14411 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14412 14413 // If the operand is a half vector, promote it to a float vector. 14414 if (ConvertHalfVec) 14415 Input = convertVector(Input.get(), Context.FloatTy, *this); 14416 resultType = Input.get()->getType(); 14417 if (resultType->isDependentType()) 14418 break; 14419 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14420 break; 14421 else if (resultType->isVectorType() && 14422 // The z vector extensions don't allow + or - with bool vectors. 14423 (!Context.getLangOpts().ZVector || 14424 resultType->castAs<VectorType>()->getVectorKind() != 14425 VectorType::AltiVecBool)) 14426 break; 14427 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14428 Opc == UO_Plus && 14429 resultType->isPointerType()) 14430 break; 14431 14432 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14433 << resultType << Input.get()->getSourceRange()); 14434 14435 case UO_Not: // bitwise complement 14436 Input = UsualUnaryConversions(Input.get()); 14437 if (Input.isInvalid()) 14438 return ExprError(); 14439 resultType = Input.get()->getType(); 14440 if (resultType->isDependentType()) 14441 break; 14442 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14443 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14444 // C99 does not support '~' for complex conjugation. 14445 Diag(OpLoc, diag::ext_integer_complement_complex) 14446 << resultType << Input.get()->getSourceRange(); 14447 else if (resultType->hasIntegerRepresentation()) 14448 break; 14449 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14450 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14451 // on vector float types. 14452 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14453 if (!T->isIntegerType()) 14454 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14455 << resultType << Input.get()->getSourceRange()); 14456 } else { 14457 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14458 << resultType << Input.get()->getSourceRange()); 14459 } 14460 break; 14461 14462 case UO_LNot: // logical negation 14463 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14464 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14465 if (Input.isInvalid()) return ExprError(); 14466 resultType = Input.get()->getType(); 14467 14468 // Though we still have to promote half FP to float... 14469 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14470 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14471 resultType = Context.FloatTy; 14472 } 14473 14474 if (resultType->isDependentType()) 14475 break; 14476 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14477 // C99 6.5.3.3p1: ok, fallthrough; 14478 if (Context.getLangOpts().CPlusPlus) { 14479 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14480 // operand contextually converted to bool. 14481 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14482 ScalarTypeToBooleanCastKind(resultType)); 14483 } else if (Context.getLangOpts().OpenCL && 14484 Context.getLangOpts().OpenCLVersion < 120) { 14485 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14486 // operate on scalar float types. 14487 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14488 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14489 << resultType << Input.get()->getSourceRange()); 14490 } 14491 } else if (resultType->isExtVectorType()) { 14492 if (Context.getLangOpts().OpenCL && 14493 Context.getLangOpts().OpenCLVersion < 120 && 14494 !Context.getLangOpts().OpenCLCPlusPlus) { 14495 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14496 // operate on vector float types. 14497 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14498 if (!T->isIntegerType()) 14499 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14500 << resultType << Input.get()->getSourceRange()); 14501 } 14502 // Vector logical not returns the signed variant of the operand type. 14503 resultType = GetSignedVectorType(resultType); 14504 break; 14505 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14506 const VectorType *VTy = resultType->castAs<VectorType>(); 14507 if (VTy->getVectorKind() != VectorType::GenericVector) 14508 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14509 << resultType << Input.get()->getSourceRange()); 14510 14511 // Vector logical not returns the signed variant of the operand type. 14512 resultType = GetSignedVectorType(resultType); 14513 break; 14514 } else { 14515 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14516 << resultType << Input.get()->getSourceRange()); 14517 } 14518 14519 // LNot always has type int. C99 6.5.3.3p5. 14520 // In C++, it's bool. C++ 5.3.1p8 14521 resultType = Context.getLogicalOperationType(); 14522 break; 14523 case UO_Real: 14524 case UO_Imag: 14525 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14526 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14527 // complex l-values to ordinary l-values and all other values to r-values. 14528 if (Input.isInvalid()) return ExprError(); 14529 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14530 if (Input.get()->getValueKind() != VK_RValue && 14531 Input.get()->getObjectKind() == OK_Ordinary) 14532 VK = Input.get()->getValueKind(); 14533 } else if (!getLangOpts().CPlusPlus) { 14534 // In C, a volatile scalar is read by __imag. In C++, it is not. 14535 Input = DefaultLvalueConversion(Input.get()); 14536 } 14537 break; 14538 case UO_Extension: 14539 resultType = Input.get()->getType(); 14540 VK = Input.get()->getValueKind(); 14541 OK = Input.get()->getObjectKind(); 14542 break; 14543 case UO_Coawait: 14544 // It's unnecessary to represent the pass-through operator co_await in the 14545 // AST; just return the input expression instead. 14546 assert(!Input.get()->getType()->isDependentType() && 14547 "the co_await expression must be non-dependant before " 14548 "building operator co_await"); 14549 return Input; 14550 } 14551 if (resultType.isNull() || Input.isInvalid()) 14552 return ExprError(); 14553 14554 // Check for array bounds violations in the operand of the UnaryOperator, 14555 // except for the '*' and '&' operators that have to be handled specially 14556 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14557 // that are explicitly defined as valid by the standard). 14558 if (Opc != UO_AddrOf && Opc != UO_Deref) 14559 CheckArrayAccess(Input.get()); 14560 14561 auto *UO = 14562 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14563 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14564 14565 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14566 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14567 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14568 14569 // Convert the result back to a half vector. 14570 if (ConvertHalfVec) 14571 return convertVector(UO, Context.HalfTy, *this); 14572 return UO; 14573 } 14574 14575 /// Determine whether the given expression is a qualified member 14576 /// access expression, of a form that could be turned into a pointer to member 14577 /// with the address-of operator. 14578 bool Sema::isQualifiedMemberAccess(Expr *E) { 14579 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14580 if (!DRE->getQualifier()) 14581 return false; 14582 14583 ValueDecl *VD = DRE->getDecl(); 14584 if (!VD->isCXXClassMember()) 14585 return false; 14586 14587 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14588 return true; 14589 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14590 return Method->isInstance(); 14591 14592 return false; 14593 } 14594 14595 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14596 if (!ULE->getQualifier()) 14597 return false; 14598 14599 for (NamedDecl *D : ULE->decls()) { 14600 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14601 if (Method->isInstance()) 14602 return true; 14603 } else { 14604 // Overload set does not contain methods. 14605 break; 14606 } 14607 } 14608 14609 return false; 14610 } 14611 14612 return false; 14613 } 14614 14615 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14616 UnaryOperatorKind Opc, Expr *Input) { 14617 // First things first: handle placeholders so that the 14618 // overloaded-operator check considers the right type. 14619 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14620 // Increment and decrement of pseudo-object references. 14621 if (pty->getKind() == BuiltinType::PseudoObject && 14622 UnaryOperator::isIncrementDecrementOp(Opc)) 14623 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14624 14625 // extension is always a builtin operator. 14626 if (Opc == UO_Extension) 14627 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14628 14629 // & gets special logic for several kinds of placeholder. 14630 // The builtin code knows what to do. 14631 if (Opc == UO_AddrOf && 14632 (pty->getKind() == BuiltinType::Overload || 14633 pty->getKind() == BuiltinType::UnknownAny || 14634 pty->getKind() == BuiltinType::BoundMember)) 14635 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14636 14637 // Anything else needs to be handled now. 14638 ExprResult Result = CheckPlaceholderExpr(Input); 14639 if (Result.isInvalid()) return ExprError(); 14640 Input = Result.get(); 14641 } 14642 14643 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14644 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14645 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14646 // Find all of the overloaded operators visible from this point. 14647 UnresolvedSet<16> Functions; 14648 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14649 if (S && OverOp != OO_None) 14650 LookupOverloadedOperatorName(OverOp, S, Functions); 14651 14652 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14653 } 14654 14655 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14656 } 14657 14658 // Unary Operators. 'Tok' is the token for the operator. 14659 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14660 tok::TokenKind Op, Expr *Input) { 14661 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14662 } 14663 14664 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14665 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14666 LabelDecl *TheDecl) { 14667 TheDecl->markUsed(Context); 14668 // Create the AST node. The address of a label always has type 'void*'. 14669 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14670 Context.getPointerType(Context.VoidTy)); 14671 } 14672 14673 void Sema::ActOnStartStmtExpr() { 14674 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14675 } 14676 14677 void Sema::ActOnStmtExprError() { 14678 // Note that function is also called by TreeTransform when leaving a 14679 // StmtExpr scope without rebuilding anything. 14680 14681 DiscardCleanupsInEvaluationContext(); 14682 PopExpressionEvaluationContext(); 14683 } 14684 14685 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14686 SourceLocation RPLoc) { 14687 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14688 } 14689 14690 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14691 SourceLocation RPLoc, unsigned TemplateDepth) { 14692 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14693 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14694 14695 if (hasAnyUnrecoverableErrorsInThisFunction()) 14696 DiscardCleanupsInEvaluationContext(); 14697 assert(!Cleanup.exprNeedsCleanups() && 14698 "cleanups within StmtExpr not correctly bound!"); 14699 PopExpressionEvaluationContext(); 14700 14701 // FIXME: there are a variety of strange constraints to enforce here, for 14702 // example, it is not possible to goto into a stmt expression apparently. 14703 // More semantic analysis is needed. 14704 14705 // If there are sub-stmts in the compound stmt, take the type of the last one 14706 // as the type of the stmtexpr. 14707 QualType Ty = Context.VoidTy; 14708 bool StmtExprMayBindToTemp = false; 14709 if (!Compound->body_empty()) { 14710 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14711 if (const auto *LastStmt = 14712 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14713 if (const Expr *Value = LastStmt->getExprStmt()) { 14714 StmtExprMayBindToTemp = true; 14715 Ty = Value->getType(); 14716 } 14717 } 14718 } 14719 14720 // FIXME: Check that expression type is complete/non-abstract; statement 14721 // expressions are not lvalues. 14722 Expr *ResStmtExpr = 14723 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14724 if (StmtExprMayBindToTemp) 14725 return MaybeBindToTemporary(ResStmtExpr); 14726 return ResStmtExpr; 14727 } 14728 14729 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14730 if (ER.isInvalid()) 14731 return ExprError(); 14732 14733 // Do function/array conversion on the last expression, but not 14734 // lvalue-to-rvalue. However, initialize an unqualified type. 14735 ER = DefaultFunctionArrayConversion(ER.get()); 14736 if (ER.isInvalid()) 14737 return ExprError(); 14738 Expr *E = ER.get(); 14739 14740 if (E->isTypeDependent()) 14741 return E; 14742 14743 // In ARC, if the final expression ends in a consume, splice 14744 // the consume out and bind it later. In the alternate case 14745 // (when dealing with a retainable type), the result 14746 // initialization will create a produce. In both cases the 14747 // result will be +1, and we'll need to balance that out with 14748 // a bind. 14749 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14750 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14751 return Cast->getSubExpr(); 14752 14753 // FIXME: Provide a better location for the initialization. 14754 return PerformCopyInitialization( 14755 InitializedEntity::InitializeStmtExprResult( 14756 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14757 SourceLocation(), E); 14758 } 14759 14760 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14761 TypeSourceInfo *TInfo, 14762 ArrayRef<OffsetOfComponent> Components, 14763 SourceLocation RParenLoc) { 14764 QualType ArgTy = TInfo->getType(); 14765 bool Dependent = ArgTy->isDependentType(); 14766 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14767 14768 // We must have at least one component that refers to the type, and the first 14769 // one is known to be a field designator. Verify that the ArgTy represents 14770 // a struct/union/class. 14771 if (!Dependent && !ArgTy->isRecordType()) 14772 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14773 << ArgTy << TypeRange); 14774 14775 // Type must be complete per C99 7.17p3 because a declaring a variable 14776 // with an incomplete type would be ill-formed. 14777 if (!Dependent 14778 && RequireCompleteType(BuiltinLoc, ArgTy, 14779 diag::err_offsetof_incomplete_type, TypeRange)) 14780 return ExprError(); 14781 14782 bool DidWarnAboutNonPOD = false; 14783 QualType CurrentType = ArgTy; 14784 SmallVector<OffsetOfNode, 4> Comps; 14785 SmallVector<Expr*, 4> Exprs; 14786 for (const OffsetOfComponent &OC : Components) { 14787 if (OC.isBrackets) { 14788 // Offset of an array sub-field. TODO: Should we allow vector elements? 14789 if (!CurrentType->isDependentType()) { 14790 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14791 if(!AT) 14792 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14793 << CurrentType); 14794 CurrentType = AT->getElementType(); 14795 } else 14796 CurrentType = Context.DependentTy; 14797 14798 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14799 if (IdxRval.isInvalid()) 14800 return ExprError(); 14801 Expr *Idx = IdxRval.get(); 14802 14803 // The expression must be an integral expression. 14804 // FIXME: An integral constant expression? 14805 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14806 !Idx->getType()->isIntegerType()) 14807 return ExprError( 14808 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14809 << Idx->getSourceRange()); 14810 14811 // Record this array index. 14812 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14813 Exprs.push_back(Idx); 14814 continue; 14815 } 14816 14817 // Offset of a field. 14818 if (CurrentType->isDependentType()) { 14819 // We have the offset of a field, but we can't look into the dependent 14820 // type. Just record the identifier of the field. 14821 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14822 CurrentType = Context.DependentTy; 14823 continue; 14824 } 14825 14826 // We need to have a complete type to look into. 14827 if (RequireCompleteType(OC.LocStart, CurrentType, 14828 diag::err_offsetof_incomplete_type)) 14829 return ExprError(); 14830 14831 // Look for the designated field. 14832 const RecordType *RC = CurrentType->getAs<RecordType>(); 14833 if (!RC) 14834 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14835 << CurrentType); 14836 RecordDecl *RD = RC->getDecl(); 14837 14838 // C++ [lib.support.types]p5: 14839 // The macro offsetof accepts a restricted set of type arguments in this 14840 // International Standard. type shall be a POD structure or a POD union 14841 // (clause 9). 14842 // C++11 [support.types]p4: 14843 // If type is not a standard-layout class (Clause 9), the results are 14844 // undefined. 14845 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14846 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14847 unsigned DiagID = 14848 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14849 : diag::ext_offsetof_non_pod_type; 14850 14851 if (!IsSafe && !DidWarnAboutNonPOD && 14852 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14853 PDiag(DiagID) 14854 << SourceRange(Components[0].LocStart, OC.LocEnd) 14855 << CurrentType)) 14856 DidWarnAboutNonPOD = true; 14857 } 14858 14859 // Look for the field. 14860 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14861 LookupQualifiedName(R, RD); 14862 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14863 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14864 if (!MemberDecl) { 14865 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14866 MemberDecl = IndirectMemberDecl->getAnonField(); 14867 } 14868 14869 if (!MemberDecl) 14870 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14871 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14872 OC.LocEnd)); 14873 14874 // C99 7.17p3: 14875 // (If the specified member is a bit-field, the behavior is undefined.) 14876 // 14877 // We diagnose this as an error. 14878 if (MemberDecl->isBitField()) { 14879 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14880 << MemberDecl->getDeclName() 14881 << SourceRange(BuiltinLoc, RParenLoc); 14882 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14883 return ExprError(); 14884 } 14885 14886 RecordDecl *Parent = MemberDecl->getParent(); 14887 if (IndirectMemberDecl) 14888 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14889 14890 // If the member was found in a base class, introduce OffsetOfNodes for 14891 // the base class indirections. 14892 CXXBasePaths Paths; 14893 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14894 Paths)) { 14895 if (Paths.getDetectedVirtual()) { 14896 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14897 << MemberDecl->getDeclName() 14898 << SourceRange(BuiltinLoc, RParenLoc); 14899 return ExprError(); 14900 } 14901 14902 CXXBasePath &Path = Paths.front(); 14903 for (const CXXBasePathElement &B : Path) 14904 Comps.push_back(OffsetOfNode(B.Base)); 14905 } 14906 14907 if (IndirectMemberDecl) { 14908 for (auto *FI : IndirectMemberDecl->chain()) { 14909 assert(isa<FieldDecl>(FI)); 14910 Comps.push_back(OffsetOfNode(OC.LocStart, 14911 cast<FieldDecl>(FI), OC.LocEnd)); 14912 } 14913 } else 14914 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14915 14916 CurrentType = MemberDecl->getType().getNonReferenceType(); 14917 } 14918 14919 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14920 Comps, Exprs, RParenLoc); 14921 } 14922 14923 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14924 SourceLocation BuiltinLoc, 14925 SourceLocation TypeLoc, 14926 ParsedType ParsedArgTy, 14927 ArrayRef<OffsetOfComponent> Components, 14928 SourceLocation RParenLoc) { 14929 14930 TypeSourceInfo *ArgTInfo; 14931 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14932 if (ArgTy.isNull()) 14933 return ExprError(); 14934 14935 if (!ArgTInfo) 14936 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14937 14938 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14939 } 14940 14941 14942 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14943 Expr *CondExpr, 14944 Expr *LHSExpr, Expr *RHSExpr, 14945 SourceLocation RPLoc) { 14946 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14947 14948 ExprValueKind VK = VK_RValue; 14949 ExprObjectKind OK = OK_Ordinary; 14950 QualType resType; 14951 bool CondIsTrue = false; 14952 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14953 resType = Context.DependentTy; 14954 } else { 14955 // The conditional expression is required to be a constant expression. 14956 llvm::APSInt condEval(32); 14957 ExprResult CondICE 14958 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14959 diag::err_typecheck_choose_expr_requires_constant, false); 14960 if (CondICE.isInvalid()) 14961 return ExprError(); 14962 CondExpr = CondICE.get(); 14963 CondIsTrue = condEval.getZExtValue(); 14964 14965 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14966 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14967 14968 resType = ActiveExpr->getType(); 14969 VK = ActiveExpr->getValueKind(); 14970 OK = ActiveExpr->getObjectKind(); 14971 } 14972 14973 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14974 resType, VK, OK, RPLoc, CondIsTrue); 14975 } 14976 14977 //===----------------------------------------------------------------------===// 14978 // Clang Extensions. 14979 //===----------------------------------------------------------------------===// 14980 14981 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14982 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14983 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14984 14985 if (LangOpts.CPlusPlus) { 14986 MangleNumberingContext *MCtx; 14987 Decl *ManglingContextDecl; 14988 std::tie(MCtx, ManglingContextDecl) = 14989 getCurrentMangleNumberContext(Block->getDeclContext()); 14990 if (MCtx) { 14991 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14992 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14993 } 14994 } 14995 14996 PushBlockScope(CurScope, Block); 14997 CurContext->addDecl(Block); 14998 if (CurScope) 14999 PushDeclContext(CurScope, Block); 15000 else 15001 CurContext = Block; 15002 15003 getCurBlock()->HasImplicitReturnType = true; 15004 15005 // Enter a new evaluation context to insulate the block from any 15006 // cleanups from the enclosing full-expression. 15007 PushExpressionEvaluationContext( 15008 ExpressionEvaluationContext::PotentiallyEvaluated); 15009 } 15010 15011 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15012 Scope *CurScope) { 15013 assert(ParamInfo.getIdentifier() == nullptr && 15014 "block-id should have no identifier!"); 15015 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 15016 BlockScopeInfo *CurBlock = getCurBlock(); 15017 15018 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15019 QualType T = Sig->getType(); 15020 15021 // FIXME: We should allow unexpanded parameter packs here, but that would, 15022 // in turn, make the block expression contain unexpanded parameter packs. 15023 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15024 // Drop the parameters. 15025 FunctionProtoType::ExtProtoInfo EPI; 15026 EPI.HasTrailingReturn = false; 15027 EPI.TypeQuals.addConst(); 15028 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15029 Sig = Context.getTrivialTypeSourceInfo(T); 15030 } 15031 15032 // GetTypeForDeclarator always produces a function type for a block 15033 // literal signature. Furthermore, it is always a FunctionProtoType 15034 // unless the function was written with a typedef. 15035 assert(T->isFunctionType() && 15036 "GetTypeForDeclarator made a non-function block signature"); 15037 15038 // Look for an explicit signature in that function type. 15039 FunctionProtoTypeLoc ExplicitSignature; 15040 15041 if ((ExplicitSignature = Sig->getTypeLoc() 15042 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15043 15044 // Check whether that explicit signature was synthesized by 15045 // GetTypeForDeclarator. If so, don't save that as part of the 15046 // written signature. 15047 if (ExplicitSignature.getLocalRangeBegin() == 15048 ExplicitSignature.getLocalRangeEnd()) { 15049 // This would be much cheaper if we stored TypeLocs instead of 15050 // TypeSourceInfos. 15051 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15052 unsigned Size = Result.getFullDataSize(); 15053 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15054 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15055 15056 ExplicitSignature = FunctionProtoTypeLoc(); 15057 } 15058 } 15059 15060 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15061 CurBlock->FunctionType = T; 15062 15063 const FunctionType *Fn = T->getAs<FunctionType>(); 15064 QualType RetTy = Fn->getReturnType(); 15065 bool isVariadic = 15066 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15067 15068 CurBlock->TheDecl->setIsVariadic(isVariadic); 15069 15070 // Context.DependentTy is used as a placeholder for a missing block 15071 // return type. TODO: what should we do with declarators like: 15072 // ^ * { ... } 15073 // If the answer is "apply template argument deduction".... 15074 if (RetTy != Context.DependentTy) { 15075 CurBlock->ReturnType = RetTy; 15076 CurBlock->TheDecl->setBlockMissingReturnType(false); 15077 CurBlock->HasImplicitReturnType = false; 15078 } 15079 15080 // Push block parameters from the declarator if we had them. 15081 SmallVector<ParmVarDecl*, 8> Params; 15082 if (ExplicitSignature) { 15083 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15084 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15085 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15086 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15087 // Diagnose this as an extension in C17 and earlier. 15088 if (!getLangOpts().C2x) 15089 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15090 } 15091 Params.push_back(Param); 15092 } 15093 15094 // Fake up parameter variables if we have a typedef, like 15095 // ^ fntype { ... } 15096 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15097 for (const auto &I : Fn->param_types()) { 15098 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15099 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15100 Params.push_back(Param); 15101 } 15102 } 15103 15104 // Set the parameters on the block decl. 15105 if (!Params.empty()) { 15106 CurBlock->TheDecl->setParams(Params); 15107 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15108 /*CheckParameterNames=*/false); 15109 } 15110 15111 // Finally we can process decl attributes. 15112 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15113 15114 // Put the parameter variables in scope. 15115 for (auto AI : CurBlock->TheDecl->parameters()) { 15116 AI->setOwningFunction(CurBlock->TheDecl); 15117 15118 // If this has an identifier, add it to the scope stack. 15119 if (AI->getIdentifier()) { 15120 CheckShadow(CurBlock->TheScope, AI); 15121 15122 PushOnScopeChains(AI, CurBlock->TheScope); 15123 } 15124 } 15125 } 15126 15127 /// ActOnBlockError - If there is an error parsing a block, this callback 15128 /// is invoked to pop the information about the block from the action impl. 15129 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15130 // Leave the expression-evaluation context. 15131 DiscardCleanupsInEvaluationContext(); 15132 PopExpressionEvaluationContext(); 15133 15134 // Pop off CurBlock, handle nested blocks. 15135 PopDeclContext(); 15136 PopFunctionScopeInfo(); 15137 } 15138 15139 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15140 /// literal was successfully completed. ^(int x){...} 15141 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15142 Stmt *Body, Scope *CurScope) { 15143 // If blocks are disabled, emit an error. 15144 if (!LangOpts.Blocks) 15145 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15146 15147 // Leave the expression-evaluation context. 15148 if (hasAnyUnrecoverableErrorsInThisFunction()) 15149 DiscardCleanupsInEvaluationContext(); 15150 assert(!Cleanup.exprNeedsCleanups() && 15151 "cleanups within block not correctly bound!"); 15152 PopExpressionEvaluationContext(); 15153 15154 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15155 BlockDecl *BD = BSI->TheDecl; 15156 15157 if (BSI->HasImplicitReturnType) 15158 deduceClosureReturnType(*BSI); 15159 15160 QualType RetTy = Context.VoidTy; 15161 if (!BSI->ReturnType.isNull()) 15162 RetTy = BSI->ReturnType; 15163 15164 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15165 QualType BlockTy; 15166 15167 // If the user wrote a function type in some form, try to use that. 15168 if (!BSI->FunctionType.isNull()) { 15169 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15170 15171 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15172 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15173 15174 // Turn protoless block types into nullary block types. 15175 if (isa<FunctionNoProtoType>(FTy)) { 15176 FunctionProtoType::ExtProtoInfo EPI; 15177 EPI.ExtInfo = Ext; 15178 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15179 15180 // Otherwise, if we don't need to change anything about the function type, 15181 // preserve its sugar structure. 15182 } else if (FTy->getReturnType() == RetTy && 15183 (!NoReturn || FTy->getNoReturnAttr())) { 15184 BlockTy = BSI->FunctionType; 15185 15186 // Otherwise, make the minimal modifications to the function type. 15187 } else { 15188 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15189 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15190 EPI.TypeQuals = Qualifiers(); 15191 EPI.ExtInfo = Ext; 15192 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15193 } 15194 15195 // If we don't have a function type, just build one from nothing. 15196 } else { 15197 FunctionProtoType::ExtProtoInfo EPI; 15198 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15199 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15200 } 15201 15202 DiagnoseUnusedParameters(BD->parameters()); 15203 BlockTy = Context.getBlockPointerType(BlockTy); 15204 15205 // If needed, diagnose invalid gotos and switches in the block. 15206 if (getCurFunction()->NeedsScopeChecking() && 15207 !PP.isCodeCompletionEnabled()) 15208 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15209 15210 BD->setBody(cast<CompoundStmt>(Body)); 15211 15212 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15213 DiagnoseUnguardedAvailabilityViolations(BD); 15214 15215 // Try to apply the named return value optimization. We have to check again 15216 // if we can do this, though, because blocks keep return statements around 15217 // to deduce an implicit return type. 15218 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15219 !BD->isDependentContext()) 15220 computeNRVO(Body, BSI); 15221 15222 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15223 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15224 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15225 NTCUK_Destruct|NTCUK_Copy); 15226 15227 PopDeclContext(); 15228 15229 // Pop the block scope now but keep it alive to the end of this function. 15230 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15231 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15232 15233 // Set the captured variables on the block. 15234 SmallVector<BlockDecl::Capture, 4> Captures; 15235 for (Capture &Cap : BSI->Captures) { 15236 if (Cap.isInvalid() || Cap.isThisCapture()) 15237 continue; 15238 15239 VarDecl *Var = Cap.getVariable(); 15240 Expr *CopyExpr = nullptr; 15241 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15242 if (const RecordType *Record = 15243 Cap.getCaptureType()->getAs<RecordType>()) { 15244 // The capture logic needs the destructor, so make sure we mark it. 15245 // Usually this is unnecessary because most local variables have 15246 // their destructors marked at declaration time, but parameters are 15247 // an exception because it's technically only the call site that 15248 // actually requires the destructor. 15249 if (isa<ParmVarDecl>(Var)) 15250 FinalizeVarWithDestructor(Var, Record); 15251 15252 // Enter a separate potentially-evaluated context while building block 15253 // initializers to isolate their cleanups from those of the block 15254 // itself. 15255 // FIXME: Is this appropriate even when the block itself occurs in an 15256 // unevaluated operand? 15257 EnterExpressionEvaluationContext EvalContext( 15258 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15259 15260 SourceLocation Loc = Cap.getLocation(); 15261 15262 ExprResult Result = BuildDeclarationNameExpr( 15263 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15264 15265 // According to the blocks spec, the capture of a variable from 15266 // the stack requires a const copy constructor. This is not true 15267 // of the copy/move done to move a __block variable to the heap. 15268 if (!Result.isInvalid() && 15269 !Result.get()->getType().isConstQualified()) { 15270 Result = ImpCastExprToType(Result.get(), 15271 Result.get()->getType().withConst(), 15272 CK_NoOp, VK_LValue); 15273 } 15274 15275 if (!Result.isInvalid()) { 15276 Result = PerformCopyInitialization( 15277 InitializedEntity::InitializeBlock(Var->getLocation(), 15278 Cap.getCaptureType(), false), 15279 Loc, Result.get()); 15280 } 15281 15282 // Build a full-expression copy expression if initialization 15283 // succeeded and used a non-trivial constructor. Recover from 15284 // errors by pretending that the copy isn't necessary. 15285 if (!Result.isInvalid() && 15286 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15287 ->isTrivial()) { 15288 Result = MaybeCreateExprWithCleanups(Result); 15289 CopyExpr = Result.get(); 15290 } 15291 } 15292 } 15293 15294 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15295 CopyExpr); 15296 Captures.push_back(NewCap); 15297 } 15298 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15299 15300 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15301 15302 // If the block isn't obviously global, i.e. it captures anything at 15303 // all, then we need to do a few things in the surrounding context: 15304 if (Result->getBlockDecl()->hasCaptures()) { 15305 // First, this expression has a new cleanup object. 15306 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15307 Cleanup.setExprNeedsCleanups(true); 15308 15309 // It also gets a branch-protected scope if any of the captured 15310 // variables needs destruction. 15311 for (const auto &CI : Result->getBlockDecl()->captures()) { 15312 const VarDecl *var = CI.getVariable(); 15313 if (var->getType().isDestructedType() != QualType::DK_none) { 15314 setFunctionHasBranchProtectedScope(); 15315 break; 15316 } 15317 } 15318 } 15319 15320 if (getCurFunction()) 15321 getCurFunction()->addBlock(BD); 15322 15323 return Result; 15324 } 15325 15326 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15327 SourceLocation RPLoc) { 15328 TypeSourceInfo *TInfo; 15329 GetTypeFromParser(Ty, &TInfo); 15330 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15331 } 15332 15333 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15334 Expr *E, TypeSourceInfo *TInfo, 15335 SourceLocation RPLoc) { 15336 Expr *OrigExpr = E; 15337 bool IsMS = false; 15338 15339 // CUDA device code does not support varargs. 15340 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15341 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15342 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15343 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15344 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15345 } 15346 } 15347 15348 // NVPTX does not support va_arg expression. 15349 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15350 Context.getTargetInfo().getTriple().isNVPTX()) 15351 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15352 15353 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15354 // as Microsoft ABI on an actual Microsoft platform, where 15355 // __builtin_ms_va_list and __builtin_va_list are the same.) 15356 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15357 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15358 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15359 if (Context.hasSameType(MSVaListType, E->getType())) { 15360 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15361 return ExprError(); 15362 IsMS = true; 15363 } 15364 } 15365 15366 // Get the va_list type 15367 QualType VaListType = Context.getBuiltinVaListType(); 15368 if (!IsMS) { 15369 if (VaListType->isArrayType()) { 15370 // Deal with implicit array decay; for example, on x86-64, 15371 // va_list is an array, but it's supposed to decay to 15372 // a pointer for va_arg. 15373 VaListType = Context.getArrayDecayedType(VaListType); 15374 // Make sure the input expression also decays appropriately. 15375 ExprResult Result = UsualUnaryConversions(E); 15376 if (Result.isInvalid()) 15377 return ExprError(); 15378 E = Result.get(); 15379 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15380 // If va_list is a record type and we are compiling in C++ mode, 15381 // check the argument using reference binding. 15382 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15383 Context, Context.getLValueReferenceType(VaListType), false); 15384 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15385 if (Init.isInvalid()) 15386 return ExprError(); 15387 E = Init.getAs<Expr>(); 15388 } else { 15389 // Otherwise, the va_list argument must be an l-value because 15390 // it is modified by va_arg. 15391 if (!E->isTypeDependent() && 15392 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15393 return ExprError(); 15394 } 15395 } 15396 15397 if (!IsMS && !E->isTypeDependent() && 15398 !Context.hasSameType(VaListType, E->getType())) 15399 return ExprError( 15400 Diag(E->getBeginLoc(), 15401 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15402 << OrigExpr->getType() << E->getSourceRange()); 15403 15404 if (!TInfo->getType()->isDependentType()) { 15405 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15406 diag::err_second_parameter_to_va_arg_incomplete, 15407 TInfo->getTypeLoc())) 15408 return ExprError(); 15409 15410 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15411 TInfo->getType(), 15412 diag::err_second_parameter_to_va_arg_abstract, 15413 TInfo->getTypeLoc())) 15414 return ExprError(); 15415 15416 if (!TInfo->getType().isPODType(Context)) { 15417 Diag(TInfo->getTypeLoc().getBeginLoc(), 15418 TInfo->getType()->isObjCLifetimeType() 15419 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15420 : diag::warn_second_parameter_to_va_arg_not_pod) 15421 << TInfo->getType() 15422 << TInfo->getTypeLoc().getSourceRange(); 15423 } 15424 15425 // Check for va_arg where arguments of the given type will be promoted 15426 // (i.e. this va_arg is guaranteed to have undefined behavior). 15427 QualType PromoteType; 15428 if (TInfo->getType()->isPromotableIntegerType()) { 15429 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15430 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15431 PromoteType = QualType(); 15432 } 15433 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15434 PromoteType = Context.DoubleTy; 15435 if (!PromoteType.isNull()) 15436 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15437 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15438 << TInfo->getType() 15439 << PromoteType 15440 << TInfo->getTypeLoc().getSourceRange()); 15441 } 15442 15443 QualType T = TInfo->getType().getNonLValueExprType(Context); 15444 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15445 } 15446 15447 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15448 // The type of __null will be int or long, depending on the size of 15449 // pointers on the target. 15450 QualType Ty; 15451 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15452 if (pw == Context.getTargetInfo().getIntWidth()) 15453 Ty = Context.IntTy; 15454 else if (pw == Context.getTargetInfo().getLongWidth()) 15455 Ty = Context.LongTy; 15456 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15457 Ty = Context.LongLongTy; 15458 else { 15459 llvm_unreachable("I don't know size of pointer!"); 15460 } 15461 15462 return new (Context) GNUNullExpr(Ty, TokenLoc); 15463 } 15464 15465 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15466 SourceLocation BuiltinLoc, 15467 SourceLocation RPLoc) { 15468 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15469 } 15470 15471 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15472 SourceLocation BuiltinLoc, 15473 SourceLocation RPLoc, 15474 DeclContext *ParentContext) { 15475 return new (Context) 15476 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15477 } 15478 15479 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15480 bool Diagnose) { 15481 if (!getLangOpts().ObjC) 15482 return false; 15483 15484 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15485 if (!PT) 15486 return false; 15487 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15488 15489 // Ignore any parens, implicit casts (should only be 15490 // array-to-pointer decays), and not-so-opaque values. The last is 15491 // important for making this trigger for property assignments. 15492 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15493 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15494 if (OV->getSourceExpr()) 15495 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15496 15497 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15498 if (!PT->isObjCIdType() && 15499 !(ID && ID->getIdentifier()->isStr("NSString"))) 15500 return false; 15501 if (!SL->isAscii()) 15502 return false; 15503 15504 if (Diagnose) { 15505 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15506 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15507 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15508 } 15509 return true; 15510 } 15511 15512 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15513 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15514 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15515 !SrcExpr->isNullPointerConstant( 15516 getASTContext(), Expr::NPC_NeverValueDependent)) { 15517 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15518 return false; 15519 if (Diagnose) { 15520 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15521 << /*number*/1 15522 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15523 Expr *NumLit = 15524 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15525 if (NumLit) 15526 Exp = NumLit; 15527 } 15528 return true; 15529 } 15530 15531 return false; 15532 } 15533 15534 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15535 const Expr *SrcExpr) { 15536 if (!DstType->isFunctionPointerType() || 15537 !SrcExpr->getType()->isFunctionType()) 15538 return false; 15539 15540 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15541 if (!DRE) 15542 return false; 15543 15544 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15545 if (!FD) 15546 return false; 15547 15548 return !S.checkAddressOfFunctionIsAvailable(FD, 15549 /*Complain=*/true, 15550 SrcExpr->getBeginLoc()); 15551 } 15552 15553 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15554 SourceLocation Loc, 15555 QualType DstType, QualType SrcType, 15556 Expr *SrcExpr, AssignmentAction Action, 15557 bool *Complained) { 15558 if (Complained) 15559 *Complained = false; 15560 15561 // Decode the result (notice that AST's are still created for extensions). 15562 bool CheckInferredResultType = false; 15563 bool isInvalid = false; 15564 unsigned DiagKind = 0; 15565 ConversionFixItGenerator ConvHints; 15566 bool MayHaveConvFixit = false; 15567 bool MayHaveFunctionDiff = false; 15568 const ObjCInterfaceDecl *IFace = nullptr; 15569 const ObjCProtocolDecl *PDecl = nullptr; 15570 15571 switch (ConvTy) { 15572 case Compatible: 15573 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15574 return false; 15575 15576 case PointerToInt: 15577 if (getLangOpts().CPlusPlus) { 15578 DiagKind = diag::err_typecheck_convert_pointer_int; 15579 isInvalid = true; 15580 } else { 15581 DiagKind = diag::ext_typecheck_convert_pointer_int; 15582 } 15583 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15584 MayHaveConvFixit = true; 15585 break; 15586 case IntToPointer: 15587 if (getLangOpts().CPlusPlus) { 15588 DiagKind = diag::err_typecheck_convert_int_pointer; 15589 isInvalid = true; 15590 } else { 15591 DiagKind = diag::ext_typecheck_convert_int_pointer; 15592 } 15593 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15594 MayHaveConvFixit = true; 15595 break; 15596 case IncompatibleFunctionPointer: 15597 if (getLangOpts().CPlusPlus) { 15598 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15599 isInvalid = true; 15600 } else { 15601 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15602 } 15603 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15604 MayHaveConvFixit = true; 15605 break; 15606 case IncompatiblePointer: 15607 if (Action == AA_Passing_CFAudited) { 15608 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15609 } else if (getLangOpts().CPlusPlus) { 15610 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15611 isInvalid = true; 15612 } else { 15613 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15614 } 15615 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15616 SrcType->isObjCObjectPointerType(); 15617 if (!CheckInferredResultType) { 15618 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15619 } else if (CheckInferredResultType) { 15620 SrcType = SrcType.getUnqualifiedType(); 15621 DstType = DstType.getUnqualifiedType(); 15622 } 15623 MayHaveConvFixit = true; 15624 break; 15625 case IncompatiblePointerSign: 15626 if (getLangOpts().CPlusPlus) { 15627 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15628 isInvalid = true; 15629 } else { 15630 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15631 } 15632 break; 15633 case FunctionVoidPointer: 15634 if (getLangOpts().CPlusPlus) { 15635 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15636 isInvalid = true; 15637 } else { 15638 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15639 } 15640 break; 15641 case IncompatiblePointerDiscardsQualifiers: { 15642 // Perform array-to-pointer decay if necessary. 15643 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15644 15645 isInvalid = true; 15646 15647 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15648 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15649 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15650 DiagKind = diag::err_typecheck_incompatible_address_space; 15651 break; 15652 15653 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15654 DiagKind = diag::err_typecheck_incompatible_ownership; 15655 break; 15656 } 15657 15658 llvm_unreachable("unknown error case for discarding qualifiers!"); 15659 // fallthrough 15660 } 15661 case CompatiblePointerDiscardsQualifiers: 15662 // If the qualifiers lost were because we were applying the 15663 // (deprecated) C++ conversion from a string literal to a char* 15664 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15665 // Ideally, this check would be performed in 15666 // checkPointerTypesForAssignment. However, that would require a 15667 // bit of refactoring (so that the second argument is an 15668 // expression, rather than a type), which should be done as part 15669 // of a larger effort to fix checkPointerTypesForAssignment for 15670 // C++ semantics. 15671 if (getLangOpts().CPlusPlus && 15672 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15673 return false; 15674 if (getLangOpts().CPlusPlus) { 15675 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15676 isInvalid = true; 15677 } else { 15678 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15679 } 15680 15681 break; 15682 case IncompatibleNestedPointerQualifiers: 15683 if (getLangOpts().CPlusPlus) { 15684 isInvalid = true; 15685 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15686 } else { 15687 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15688 } 15689 break; 15690 case IncompatibleNestedPointerAddressSpaceMismatch: 15691 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15692 isInvalid = true; 15693 break; 15694 case IntToBlockPointer: 15695 DiagKind = diag::err_int_to_block_pointer; 15696 isInvalid = true; 15697 break; 15698 case IncompatibleBlockPointer: 15699 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15700 isInvalid = true; 15701 break; 15702 case IncompatibleObjCQualifiedId: { 15703 if (SrcType->isObjCQualifiedIdType()) { 15704 const ObjCObjectPointerType *srcOPT = 15705 SrcType->castAs<ObjCObjectPointerType>(); 15706 for (auto *srcProto : srcOPT->quals()) { 15707 PDecl = srcProto; 15708 break; 15709 } 15710 if (const ObjCInterfaceType *IFaceT = 15711 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15712 IFace = IFaceT->getDecl(); 15713 } 15714 else if (DstType->isObjCQualifiedIdType()) { 15715 const ObjCObjectPointerType *dstOPT = 15716 DstType->castAs<ObjCObjectPointerType>(); 15717 for (auto *dstProto : dstOPT->quals()) { 15718 PDecl = dstProto; 15719 break; 15720 } 15721 if (const ObjCInterfaceType *IFaceT = 15722 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15723 IFace = IFaceT->getDecl(); 15724 } 15725 if (getLangOpts().CPlusPlus) { 15726 DiagKind = diag::err_incompatible_qualified_id; 15727 isInvalid = true; 15728 } else { 15729 DiagKind = diag::warn_incompatible_qualified_id; 15730 } 15731 break; 15732 } 15733 case IncompatibleVectors: 15734 if (getLangOpts().CPlusPlus) { 15735 DiagKind = diag::err_incompatible_vectors; 15736 isInvalid = true; 15737 } else { 15738 DiagKind = diag::warn_incompatible_vectors; 15739 } 15740 break; 15741 case IncompatibleObjCWeakRef: 15742 DiagKind = diag::err_arc_weak_unavailable_assign; 15743 isInvalid = true; 15744 break; 15745 case Incompatible: 15746 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15747 if (Complained) 15748 *Complained = true; 15749 return true; 15750 } 15751 15752 DiagKind = diag::err_typecheck_convert_incompatible; 15753 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15754 MayHaveConvFixit = true; 15755 isInvalid = true; 15756 MayHaveFunctionDiff = true; 15757 break; 15758 } 15759 15760 QualType FirstType, SecondType; 15761 switch (Action) { 15762 case AA_Assigning: 15763 case AA_Initializing: 15764 // The destination type comes first. 15765 FirstType = DstType; 15766 SecondType = SrcType; 15767 break; 15768 15769 case AA_Returning: 15770 case AA_Passing: 15771 case AA_Passing_CFAudited: 15772 case AA_Converting: 15773 case AA_Sending: 15774 case AA_Casting: 15775 // The source type comes first. 15776 FirstType = SrcType; 15777 SecondType = DstType; 15778 break; 15779 } 15780 15781 PartialDiagnostic FDiag = PDiag(DiagKind); 15782 if (Action == AA_Passing_CFAudited) 15783 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15784 else 15785 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15786 15787 // If we can fix the conversion, suggest the FixIts. 15788 if (!ConvHints.isNull()) { 15789 for (FixItHint &H : ConvHints.Hints) 15790 FDiag << H; 15791 } 15792 15793 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15794 15795 if (MayHaveFunctionDiff) 15796 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15797 15798 Diag(Loc, FDiag); 15799 if ((DiagKind == diag::warn_incompatible_qualified_id || 15800 DiagKind == diag::err_incompatible_qualified_id) && 15801 PDecl && IFace && !IFace->hasDefinition()) 15802 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15803 << IFace << PDecl; 15804 15805 if (SecondType == Context.OverloadTy) 15806 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15807 FirstType, /*TakingAddress=*/true); 15808 15809 if (CheckInferredResultType) 15810 EmitRelatedResultTypeNote(SrcExpr); 15811 15812 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15813 EmitRelatedResultTypeNoteForReturn(DstType); 15814 15815 if (Complained) 15816 *Complained = true; 15817 return isInvalid; 15818 } 15819 15820 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15821 llvm::APSInt *Result) { 15822 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15823 public: 15824 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15825 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15826 } 15827 } Diagnoser; 15828 15829 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15830 } 15831 15832 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15833 llvm::APSInt *Result, 15834 unsigned DiagID, 15835 bool AllowFold) { 15836 class IDDiagnoser : public VerifyICEDiagnoser { 15837 unsigned DiagID; 15838 15839 public: 15840 IDDiagnoser(unsigned DiagID) 15841 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15842 15843 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15844 S.Diag(Loc, DiagID) << SR; 15845 } 15846 } Diagnoser(DiagID); 15847 15848 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15849 } 15850 15851 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15852 SourceRange SR) { 15853 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15854 } 15855 15856 ExprResult 15857 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15858 VerifyICEDiagnoser &Diagnoser, 15859 bool AllowFold) { 15860 SourceLocation DiagLoc = E->getBeginLoc(); 15861 15862 if (getLangOpts().CPlusPlus11) { 15863 // C++11 [expr.const]p5: 15864 // If an expression of literal class type is used in a context where an 15865 // integral constant expression is required, then that class type shall 15866 // have a single non-explicit conversion function to an integral or 15867 // unscoped enumeration type 15868 ExprResult Converted; 15869 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15870 public: 15871 CXX11ConvertDiagnoser(bool Silent) 15872 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15873 Silent, true) {} 15874 15875 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15876 QualType T) override { 15877 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15878 } 15879 15880 SemaDiagnosticBuilder diagnoseIncomplete( 15881 Sema &S, SourceLocation Loc, QualType T) override { 15882 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15883 } 15884 15885 SemaDiagnosticBuilder diagnoseExplicitConv( 15886 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15887 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15888 } 15889 15890 SemaDiagnosticBuilder noteExplicitConv( 15891 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15892 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15893 << ConvTy->isEnumeralType() << ConvTy; 15894 } 15895 15896 SemaDiagnosticBuilder diagnoseAmbiguous( 15897 Sema &S, SourceLocation Loc, QualType T) override { 15898 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15899 } 15900 15901 SemaDiagnosticBuilder noteAmbiguous( 15902 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15903 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15904 << ConvTy->isEnumeralType() << ConvTy; 15905 } 15906 15907 SemaDiagnosticBuilder diagnoseConversion( 15908 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15909 llvm_unreachable("conversion functions are permitted"); 15910 } 15911 } ConvertDiagnoser(Diagnoser.Suppress); 15912 15913 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15914 ConvertDiagnoser); 15915 if (Converted.isInvalid()) 15916 return Converted; 15917 E = Converted.get(); 15918 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15919 return ExprError(); 15920 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15921 // An ICE must be of integral or unscoped enumeration type. 15922 if (!Diagnoser.Suppress) 15923 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15924 return ExprError(); 15925 } 15926 15927 ExprResult RValueExpr = DefaultLvalueConversion(E); 15928 if (RValueExpr.isInvalid()) 15929 return ExprError(); 15930 15931 E = RValueExpr.get(); 15932 15933 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15934 // in the non-ICE case. 15935 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15936 if (Result) 15937 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15938 if (!isa<ConstantExpr>(E)) 15939 E = ConstantExpr::Create(Context, E); 15940 return E; 15941 } 15942 15943 Expr::EvalResult EvalResult; 15944 SmallVector<PartialDiagnosticAt, 8> Notes; 15945 EvalResult.Diag = &Notes; 15946 15947 // Try to evaluate the expression, and produce diagnostics explaining why it's 15948 // not a constant expression as a side-effect. 15949 bool Folded = 15950 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15951 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15952 15953 if (!isa<ConstantExpr>(E)) 15954 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15955 15956 // In C++11, we can rely on diagnostics being produced for any expression 15957 // which is not a constant expression. If no diagnostics were produced, then 15958 // this is a constant expression. 15959 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15960 if (Result) 15961 *Result = EvalResult.Val.getInt(); 15962 return E; 15963 } 15964 15965 // If our only note is the usual "invalid subexpression" note, just point 15966 // the caret at its location rather than producing an essentially 15967 // redundant note. 15968 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15969 diag::note_invalid_subexpr_in_const_expr) { 15970 DiagLoc = Notes[0].first; 15971 Notes.clear(); 15972 } 15973 15974 if (!Folded || !AllowFold) { 15975 if (!Diagnoser.Suppress) { 15976 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15977 for (const PartialDiagnosticAt &Note : Notes) 15978 Diag(Note.first, Note.second); 15979 } 15980 15981 return ExprError(); 15982 } 15983 15984 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15985 for (const PartialDiagnosticAt &Note : Notes) 15986 Diag(Note.first, Note.second); 15987 15988 if (Result) 15989 *Result = EvalResult.Val.getInt(); 15990 return E; 15991 } 15992 15993 namespace { 15994 // Handle the case where we conclude a expression which we speculatively 15995 // considered to be unevaluated is actually evaluated. 15996 class TransformToPE : public TreeTransform<TransformToPE> { 15997 typedef TreeTransform<TransformToPE> BaseTransform; 15998 15999 public: 16000 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16001 16002 // Make sure we redo semantic analysis 16003 bool AlwaysRebuild() { return true; } 16004 bool ReplacingOriginal() { return true; } 16005 16006 // We need to special-case DeclRefExprs referring to FieldDecls which 16007 // are not part of a member pointer formation; normal TreeTransforming 16008 // doesn't catch this case because of the way we represent them in the AST. 16009 // FIXME: This is a bit ugly; is it really the best way to handle this 16010 // case? 16011 // 16012 // Error on DeclRefExprs referring to FieldDecls. 16013 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16014 if (isa<FieldDecl>(E->getDecl()) && 16015 !SemaRef.isUnevaluatedContext()) 16016 return SemaRef.Diag(E->getLocation(), 16017 diag::err_invalid_non_static_member_use) 16018 << E->getDecl() << E->getSourceRange(); 16019 16020 return BaseTransform::TransformDeclRefExpr(E); 16021 } 16022 16023 // Exception: filter out member pointer formation 16024 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16025 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16026 return E; 16027 16028 return BaseTransform::TransformUnaryOperator(E); 16029 } 16030 16031 // The body of a lambda-expression is in a separate expression evaluation 16032 // context so never needs to be transformed. 16033 // FIXME: Ideally we wouldn't transform the closure type either, and would 16034 // just recreate the capture expressions and lambda expression. 16035 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16036 return SkipLambdaBody(E, Body); 16037 } 16038 }; 16039 } 16040 16041 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16042 assert(isUnevaluatedContext() && 16043 "Should only transform unevaluated expressions"); 16044 ExprEvalContexts.back().Context = 16045 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16046 if (isUnevaluatedContext()) 16047 return E; 16048 return TransformToPE(*this).TransformExpr(E); 16049 } 16050 16051 void 16052 Sema::PushExpressionEvaluationContext( 16053 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16054 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16055 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16056 LambdaContextDecl, ExprContext); 16057 Cleanup.reset(); 16058 if (!MaybeODRUseExprs.empty()) 16059 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16060 } 16061 16062 void 16063 Sema::PushExpressionEvaluationContext( 16064 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16065 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16066 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16067 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16068 } 16069 16070 namespace { 16071 16072 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16073 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16074 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16075 if (E->getOpcode() == UO_Deref) 16076 return CheckPossibleDeref(S, E->getSubExpr()); 16077 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16078 return CheckPossibleDeref(S, E->getBase()); 16079 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16080 return CheckPossibleDeref(S, E->getBase()); 16081 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16082 QualType Inner; 16083 QualType Ty = E->getType(); 16084 if (const auto *Ptr = Ty->getAs<PointerType>()) 16085 Inner = Ptr->getPointeeType(); 16086 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16087 Inner = Arr->getElementType(); 16088 else 16089 return nullptr; 16090 16091 if (Inner->hasAttr(attr::NoDeref)) 16092 return E; 16093 } 16094 return nullptr; 16095 } 16096 16097 } // namespace 16098 16099 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16100 for (const Expr *E : Rec.PossibleDerefs) { 16101 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16102 if (DeclRef) { 16103 const ValueDecl *Decl = DeclRef->getDecl(); 16104 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16105 << Decl->getName() << E->getSourceRange(); 16106 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16107 } else { 16108 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16109 << E->getSourceRange(); 16110 } 16111 } 16112 Rec.PossibleDerefs.clear(); 16113 } 16114 16115 /// Check whether E, which is either a discarded-value expression or an 16116 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16117 /// and if so, remove it from the list of volatile-qualified assignments that 16118 /// we are going to warn are deprecated. 16119 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16120 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16121 return; 16122 16123 // Note: ignoring parens here is not justified by the standard rules, but 16124 // ignoring parentheses seems like a more reasonable approach, and this only 16125 // drives a deprecation warning so doesn't affect conformance. 16126 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16127 if (BO->getOpcode() == BO_Assign) { 16128 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16129 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16130 LHSs.end()); 16131 } 16132 } 16133 } 16134 16135 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16136 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16137 RebuildingImmediateInvocation) 16138 return E; 16139 16140 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16141 /// It's OK if this fails; we'll also remove this in 16142 /// HandleImmediateInvocations, but catching it here allows us to avoid 16143 /// walking the AST looking for it in simple cases. 16144 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16145 if (auto *DeclRef = 16146 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16147 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16148 16149 E = MaybeCreateExprWithCleanups(E); 16150 16151 ConstantExpr *Res = ConstantExpr::Create( 16152 getASTContext(), E.get(), 16153 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16154 getASTContext()), 16155 /*IsImmediateInvocation*/ true); 16156 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16157 return Res; 16158 } 16159 16160 static void EvaluateAndDiagnoseImmediateInvocation( 16161 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16162 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16163 Expr::EvalResult Eval; 16164 Eval.Diag = &Notes; 16165 ConstantExpr *CE = Candidate.getPointer(); 16166 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 16167 SemaRef.getASTContext(), true); 16168 if (!Result || !Notes.empty()) { 16169 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16170 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16171 InnerExpr = FunctionalCast->getSubExpr(); 16172 FunctionDecl *FD = nullptr; 16173 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16174 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16175 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16176 FD = Call->getConstructor(); 16177 else 16178 llvm_unreachable("unhandled decl kind"); 16179 assert(FD->isConsteval()); 16180 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16181 for (auto &Note : Notes) 16182 SemaRef.Diag(Note.first, Note.second); 16183 return; 16184 } 16185 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16186 } 16187 16188 static void RemoveNestedImmediateInvocation( 16189 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16190 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16191 struct ComplexRemove : TreeTransform<ComplexRemove> { 16192 using Base = TreeTransform<ComplexRemove>; 16193 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16194 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16195 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16196 CurrentII; 16197 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16198 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16199 SmallVector<Sema::ImmediateInvocationCandidate, 16200 4>::reverse_iterator Current) 16201 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16202 void RemoveImmediateInvocation(ConstantExpr* E) { 16203 auto It = std::find_if(CurrentII, IISet.rend(), 16204 [E](Sema::ImmediateInvocationCandidate Elem) { 16205 return Elem.getPointer() == E; 16206 }); 16207 assert(It != IISet.rend() && 16208 "ConstantExpr marked IsImmediateInvocation should " 16209 "be present"); 16210 It->setInt(1); // Mark as deleted 16211 } 16212 ExprResult TransformConstantExpr(ConstantExpr *E) { 16213 if (!E->isImmediateInvocation()) 16214 return Base::TransformConstantExpr(E); 16215 RemoveImmediateInvocation(E); 16216 return Base::TransformExpr(E->getSubExpr()); 16217 } 16218 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16219 /// we need to remove its DeclRefExpr from the DRSet. 16220 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16221 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16222 return Base::TransformCXXOperatorCallExpr(E); 16223 } 16224 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16225 /// here. 16226 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16227 if (!Init) 16228 return Init; 16229 /// ConstantExpr are the first layer of implicit node to be removed so if 16230 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16231 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16232 if (CE->isImmediateInvocation()) 16233 RemoveImmediateInvocation(CE); 16234 return Base::TransformInitializer(Init, NotCopyInit); 16235 } 16236 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16237 DRSet.erase(E); 16238 return E; 16239 } 16240 bool AlwaysRebuild() { return false; } 16241 bool ReplacingOriginal() { return true; } 16242 bool AllowSkippingCXXConstructExpr() { 16243 bool Res = AllowSkippingFirstCXXConstructExpr; 16244 AllowSkippingFirstCXXConstructExpr = true; 16245 return Res; 16246 } 16247 bool AllowSkippingFirstCXXConstructExpr = true; 16248 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16249 Rec.ImmediateInvocationCandidates, It); 16250 16251 /// CXXConstructExpr with a single argument are getting skipped by 16252 /// TreeTransform in some situtation because they could be implicit. This 16253 /// can only occur for the top-level CXXConstructExpr because it is used 16254 /// nowhere in the expression being transformed therefore will not be rebuilt. 16255 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16256 /// skipping the first CXXConstructExpr. 16257 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16258 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16259 16260 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16261 assert(Res.isUsable()); 16262 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16263 It->getPointer()->setSubExpr(Res.get()); 16264 } 16265 16266 static void 16267 HandleImmediateInvocations(Sema &SemaRef, 16268 Sema::ExpressionEvaluationContextRecord &Rec) { 16269 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16270 Rec.ReferenceToConsteval.size() == 0) || 16271 SemaRef.RebuildingImmediateInvocation) 16272 return; 16273 16274 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16275 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16276 /// need to remove ReferenceToConsteval in the immediate invocation. 16277 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16278 16279 /// Prevent sema calls during the tree transform from adding pointers that 16280 /// are already in the sets. 16281 llvm::SaveAndRestore<bool> DisableIITracking( 16282 SemaRef.RebuildingImmediateInvocation, true); 16283 16284 /// Prevent diagnostic during tree transfrom as they are duplicates 16285 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16286 16287 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16288 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16289 if (!It->getInt()) 16290 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16291 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16292 Rec.ReferenceToConsteval.size()) { 16293 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16294 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16295 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16296 bool VisitDeclRefExpr(DeclRefExpr *E) { 16297 DRSet.erase(E); 16298 return DRSet.size(); 16299 } 16300 } Visitor(Rec.ReferenceToConsteval); 16301 Visitor.TraverseStmt( 16302 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16303 } 16304 for (auto CE : Rec.ImmediateInvocationCandidates) 16305 if (!CE.getInt()) 16306 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16307 for (auto DR : Rec.ReferenceToConsteval) { 16308 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16309 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16310 << FD; 16311 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16312 } 16313 } 16314 16315 void Sema::PopExpressionEvaluationContext() { 16316 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16317 unsigned NumTypos = Rec.NumTypos; 16318 16319 if (!Rec.Lambdas.empty()) { 16320 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16321 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16322 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16323 unsigned D; 16324 if (Rec.isUnevaluated()) { 16325 // C++11 [expr.prim.lambda]p2: 16326 // A lambda-expression shall not appear in an unevaluated operand 16327 // (Clause 5). 16328 D = diag::err_lambda_unevaluated_operand; 16329 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16330 // C++1y [expr.const]p2: 16331 // A conditional-expression e is a core constant expression unless the 16332 // evaluation of e, following the rules of the abstract machine, would 16333 // evaluate [...] a lambda-expression. 16334 D = diag::err_lambda_in_constant_expression; 16335 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16336 // C++17 [expr.prim.lamda]p2: 16337 // A lambda-expression shall not appear [...] in a template-argument. 16338 D = diag::err_lambda_in_invalid_context; 16339 } else 16340 llvm_unreachable("Couldn't infer lambda error message."); 16341 16342 for (const auto *L : Rec.Lambdas) 16343 Diag(L->getBeginLoc(), D); 16344 } 16345 } 16346 16347 WarnOnPendingNoDerefs(Rec); 16348 HandleImmediateInvocations(*this, Rec); 16349 16350 // Warn on any volatile-qualified simple-assignments that are not discarded- 16351 // value expressions nor unevaluated operands (those cases get removed from 16352 // this list by CheckUnusedVolatileAssignment). 16353 for (auto *BO : Rec.VolatileAssignmentLHSs) 16354 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16355 << BO->getType(); 16356 16357 // When are coming out of an unevaluated context, clear out any 16358 // temporaries that we may have created as part of the evaluation of 16359 // the expression in that context: they aren't relevant because they 16360 // will never be constructed. 16361 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16362 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16363 ExprCleanupObjects.end()); 16364 Cleanup = Rec.ParentCleanup; 16365 CleanupVarDeclMarking(); 16366 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16367 // Otherwise, merge the contexts together. 16368 } else { 16369 Cleanup.mergeFrom(Rec.ParentCleanup); 16370 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16371 Rec.SavedMaybeODRUseExprs.end()); 16372 } 16373 16374 // Pop the current expression evaluation context off the stack. 16375 ExprEvalContexts.pop_back(); 16376 16377 // The global expression evaluation context record is never popped. 16378 ExprEvalContexts.back().NumTypos += NumTypos; 16379 } 16380 16381 void Sema::DiscardCleanupsInEvaluationContext() { 16382 ExprCleanupObjects.erase( 16383 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16384 ExprCleanupObjects.end()); 16385 Cleanup.reset(); 16386 MaybeODRUseExprs.clear(); 16387 } 16388 16389 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16390 ExprResult Result = CheckPlaceholderExpr(E); 16391 if (Result.isInvalid()) 16392 return ExprError(); 16393 E = Result.get(); 16394 if (!E->getType()->isVariablyModifiedType()) 16395 return E; 16396 return TransformToPotentiallyEvaluated(E); 16397 } 16398 16399 /// Are we in a context that is potentially constant evaluated per C++20 16400 /// [expr.const]p12? 16401 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16402 /// C++2a [expr.const]p12: 16403 // An expression or conversion is potentially constant evaluated if it is 16404 switch (SemaRef.ExprEvalContexts.back().Context) { 16405 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16406 // -- a manifestly constant-evaluated expression, 16407 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16408 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16409 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16410 // -- a potentially-evaluated expression, 16411 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16412 // -- an immediate subexpression of a braced-init-list, 16413 16414 // -- [FIXME] an expression of the form & cast-expression that occurs 16415 // within a templated entity 16416 // -- a subexpression of one of the above that is not a subexpression of 16417 // a nested unevaluated operand. 16418 return true; 16419 16420 case Sema::ExpressionEvaluationContext::Unevaluated: 16421 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16422 // Expressions in this context are never evaluated. 16423 return false; 16424 } 16425 llvm_unreachable("Invalid context"); 16426 } 16427 16428 /// Return true if this function has a calling convention that requires mangling 16429 /// in the size of the parameter pack. 16430 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16431 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16432 // we don't need parameter type sizes. 16433 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16434 if (!TT.isOSWindows() || !TT.isX86()) 16435 return false; 16436 16437 // If this is C++ and this isn't an extern "C" function, parameters do not 16438 // need to be complete. In this case, C++ mangling will apply, which doesn't 16439 // use the size of the parameters. 16440 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16441 return false; 16442 16443 // Stdcall, fastcall, and vectorcall need this special treatment. 16444 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16445 switch (CC) { 16446 case CC_X86StdCall: 16447 case CC_X86FastCall: 16448 case CC_X86VectorCall: 16449 return true; 16450 default: 16451 break; 16452 } 16453 return false; 16454 } 16455 16456 /// Require that all of the parameter types of function be complete. Normally, 16457 /// parameter types are only required to be complete when a function is called 16458 /// or defined, but to mangle functions with certain calling conventions, the 16459 /// mangler needs to know the size of the parameter list. In this situation, 16460 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16461 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16462 /// result in a linker error. Clang doesn't implement this behavior, and instead 16463 /// attempts to error at compile time. 16464 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16465 SourceLocation Loc) { 16466 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16467 FunctionDecl *FD; 16468 ParmVarDecl *Param; 16469 16470 public: 16471 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16472 : FD(FD), Param(Param) {} 16473 16474 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16475 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16476 StringRef CCName; 16477 switch (CC) { 16478 case CC_X86StdCall: 16479 CCName = "stdcall"; 16480 break; 16481 case CC_X86FastCall: 16482 CCName = "fastcall"; 16483 break; 16484 case CC_X86VectorCall: 16485 CCName = "vectorcall"; 16486 break; 16487 default: 16488 llvm_unreachable("CC does not need mangling"); 16489 } 16490 16491 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16492 << Param->getDeclName() << FD->getDeclName() << CCName; 16493 } 16494 }; 16495 16496 for (ParmVarDecl *Param : FD->parameters()) { 16497 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16498 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16499 } 16500 } 16501 16502 namespace { 16503 enum class OdrUseContext { 16504 /// Declarations in this context are not odr-used. 16505 None, 16506 /// Declarations in this context are formally odr-used, but this is a 16507 /// dependent context. 16508 Dependent, 16509 /// Declarations in this context are odr-used but not actually used (yet). 16510 FormallyOdrUsed, 16511 /// Declarations in this context are used. 16512 Used 16513 }; 16514 } 16515 16516 /// Are we within a context in which references to resolved functions or to 16517 /// variables result in odr-use? 16518 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16519 OdrUseContext Result; 16520 16521 switch (SemaRef.ExprEvalContexts.back().Context) { 16522 case Sema::ExpressionEvaluationContext::Unevaluated: 16523 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16524 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16525 return OdrUseContext::None; 16526 16527 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16528 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16529 Result = OdrUseContext::Used; 16530 break; 16531 16532 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16533 Result = OdrUseContext::FormallyOdrUsed; 16534 break; 16535 16536 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16537 // A default argument formally results in odr-use, but doesn't actually 16538 // result in a use in any real sense until it itself is used. 16539 Result = OdrUseContext::FormallyOdrUsed; 16540 break; 16541 } 16542 16543 if (SemaRef.CurContext->isDependentContext()) 16544 return OdrUseContext::Dependent; 16545 16546 return Result; 16547 } 16548 16549 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16550 return Func->isConstexpr() && 16551 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 16552 } 16553 16554 /// Mark a function referenced, and check whether it is odr-used 16555 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16556 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16557 bool MightBeOdrUse) { 16558 assert(Func && "No function?"); 16559 16560 Func->setReferenced(); 16561 16562 // Recursive functions aren't really used until they're used from some other 16563 // context. 16564 bool IsRecursiveCall = CurContext == Func; 16565 16566 // C++11 [basic.def.odr]p3: 16567 // A function whose name appears as a potentially-evaluated expression is 16568 // odr-used if it is the unique lookup result or the selected member of a 16569 // set of overloaded functions [...]. 16570 // 16571 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16572 // can just check that here. 16573 OdrUseContext OdrUse = 16574 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16575 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16576 OdrUse = OdrUseContext::FormallyOdrUsed; 16577 16578 // Trivial default constructors and destructors are never actually used. 16579 // FIXME: What about other special members? 16580 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16581 OdrUse == OdrUseContext::Used) { 16582 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16583 if (Constructor->isDefaultConstructor()) 16584 OdrUse = OdrUseContext::FormallyOdrUsed; 16585 if (isa<CXXDestructorDecl>(Func)) 16586 OdrUse = OdrUseContext::FormallyOdrUsed; 16587 } 16588 16589 // C++20 [expr.const]p12: 16590 // A function [...] is needed for constant evaluation if it is [...] a 16591 // constexpr function that is named by an expression that is potentially 16592 // constant evaluated 16593 bool NeededForConstantEvaluation = 16594 isPotentiallyConstantEvaluatedContext(*this) && 16595 isImplicitlyDefinableConstexprFunction(Func); 16596 16597 // Determine whether we require a function definition to exist, per 16598 // C++11 [temp.inst]p3: 16599 // Unless a function template specialization has been explicitly 16600 // instantiated or explicitly specialized, the function template 16601 // specialization is implicitly instantiated when the specialization is 16602 // referenced in a context that requires a function definition to exist. 16603 // C++20 [temp.inst]p7: 16604 // The existence of a definition of a [...] function is considered to 16605 // affect the semantics of the program if the [...] function is needed for 16606 // constant evaluation by an expression 16607 // C++20 [basic.def.odr]p10: 16608 // Every program shall contain exactly one definition of every non-inline 16609 // function or variable that is odr-used in that program outside of a 16610 // discarded statement 16611 // C++20 [special]p1: 16612 // The implementation will implicitly define [defaulted special members] 16613 // if they are odr-used or needed for constant evaluation. 16614 // 16615 // Note that we skip the implicit instantiation of templates that are only 16616 // used in unused default arguments or by recursive calls to themselves. 16617 // This is formally non-conforming, but seems reasonable in practice. 16618 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16619 NeededForConstantEvaluation); 16620 16621 // C++14 [temp.expl.spec]p6: 16622 // If a template [...] is explicitly specialized then that specialization 16623 // shall be declared before the first use of that specialization that would 16624 // cause an implicit instantiation to take place, in every translation unit 16625 // in which such a use occurs 16626 if (NeedDefinition && 16627 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16628 Func->getMemberSpecializationInfo())) 16629 checkSpecializationVisibility(Loc, Func); 16630 16631 if (getLangOpts().CUDA) 16632 CheckCUDACall(Loc, Func); 16633 16634 if (getLangOpts().SYCLIsDevice) 16635 checkSYCLDeviceFunction(Loc, Func); 16636 16637 // If we need a definition, try to create one. 16638 if (NeedDefinition && !Func->getBody()) { 16639 runWithSufficientStackSpace(Loc, [&] { 16640 if (CXXConstructorDecl *Constructor = 16641 dyn_cast<CXXConstructorDecl>(Func)) { 16642 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16643 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16644 if (Constructor->isDefaultConstructor()) { 16645 if (Constructor->isTrivial() && 16646 !Constructor->hasAttr<DLLExportAttr>()) 16647 return; 16648 DefineImplicitDefaultConstructor(Loc, Constructor); 16649 } else if (Constructor->isCopyConstructor()) { 16650 DefineImplicitCopyConstructor(Loc, Constructor); 16651 } else if (Constructor->isMoveConstructor()) { 16652 DefineImplicitMoveConstructor(Loc, Constructor); 16653 } 16654 } else if (Constructor->getInheritedConstructor()) { 16655 DefineInheritingConstructor(Loc, Constructor); 16656 } 16657 } else if (CXXDestructorDecl *Destructor = 16658 dyn_cast<CXXDestructorDecl>(Func)) { 16659 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16660 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16661 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16662 return; 16663 DefineImplicitDestructor(Loc, Destructor); 16664 } 16665 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16666 MarkVTableUsed(Loc, Destructor->getParent()); 16667 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16668 if (MethodDecl->isOverloadedOperator() && 16669 MethodDecl->getOverloadedOperator() == OO_Equal) { 16670 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16671 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16672 if (MethodDecl->isCopyAssignmentOperator()) 16673 DefineImplicitCopyAssignment(Loc, MethodDecl); 16674 else if (MethodDecl->isMoveAssignmentOperator()) 16675 DefineImplicitMoveAssignment(Loc, MethodDecl); 16676 } 16677 } else if (isa<CXXConversionDecl>(MethodDecl) && 16678 MethodDecl->getParent()->isLambda()) { 16679 CXXConversionDecl *Conversion = 16680 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16681 if (Conversion->isLambdaToBlockPointerConversion()) 16682 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16683 else 16684 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16685 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16686 MarkVTableUsed(Loc, MethodDecl->getParent()); 16687 } 16688 16689 if (Func->isDefaulted() && !Func->isDeleted()) { 16690 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16691 if (DCK != DefaultedComparisonKind::None) 16692 DefineDefaultedComparison(Loc, Func, DCK); 16693 } 16694 16695 // Implicit instantiation of function templates and member functions of 16696 // class templates. 16697 if (Func->isImplicitlyInstantiable()) { 16698 TemplateSpecializationKind TSK = 16699 Func->getTemplateSpecializationKindForInstantiation(); 16700 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16701 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16702 if (FirstInstantiation) { 16703 PointOfInstantiation = Loc; 16704 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16705 } else if (TSK != TSK_ImplicitInstantiation) { 16706 // Use the point of use as the point of instantiation, instead of the 16707 // point of explicit instantiation (which we track as the actual point 16708 // of instantiation). This gives better backtraces in diagnostics. 16709 PointOfInstantiation = Loc; 16710 } 16711 16712 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16713 Func->isConstexpr()) { 16714 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16715 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16716 CodeSynthesisContexts.size()) 16717 PendingLocalImplicitInstantiations.push_back( 16718 std::make_pair(Func, PointOfInstantiation)); 16719 else if (Func->isConstexpr()) 16720 // Do not defer instantiations of constexpr functions, to avoid the 16721 // expression evaluator needing to call back into Sema if it sees a 16722 // call to such a function. 16723 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16724 else { 16725 Func->setInstantiationIsPending(true); 16726 PendingInstantiations.push_back( 16727 std::make_pair(Func, PointOfInstantiation)); 16728 // Notify the consumer that a function was implicitly instantiated. 16729 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16730 } 16731 } 16732 } else { 16733 // Walk redefinitions, as some of them may be instantiable. 16734 for (auto i : Func->redecls()) { 16735 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16736 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16737 } 16738 } 16739 }); 16740 } 16741 16742 // C++14 [except.spec]p17: 16743 // An exception-specification is considered to be needed when: 16744 // - the function is odr-used or, if it appears in an unevaluated operand, 16745 // would be odr-used if the expression were potentially-evaluated; 16746 // 16747 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16748 // function is a pure virtual function we're calling, and in that case the 16749 // function was selected by overload resolution and we need to resolve its 16750 // exception specification for a different reason. 16751 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16752 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16753 ResolveExceptionSpec(Loc, FPT); 16754 16755 // If this is the first "real" use, act on that. 16756 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16757 // Keep track of used but undefined functions. 16758 if (!Func->isDefined()) { 16759 if (mightHaveNonExternalLinkage(Func)) 16760 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16761 else if (Func->getMostRecentDecl()->isInlined() && 16762 !LangOpts.GNUInline && 16763 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16764 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16765 else if (isExternalWithNoLinkageType(Func)) 16766 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16767 } 16768 16769 // Some x86 Windows calling conventions mangle the size of the parameter 16770 // pack into the name. Computing the size of the parameters requires the 16771 // parameter types to be complete. Check that now. 16772 if (funcHasParameterSizeMangling(*this, Func)) 16773 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16774 16775 // In the MS C++ ABI, the compiler emits destructor variants where they are 16776 // used. If the destructor is used here but defined elsewhere, mark the 16777 // virtual base destructors referenced. If those virtual base destructors 16778 // are inline, this will ensure they are defined when emitting the complete 16779 // destructor variant. This checking may be redundant if the destructor is 16780 // provided later in this TU. 16781 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16782 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16783 CXXRecordDecl *Parent = Dtor->getParent(); 16784 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16785 CheckCompleteDestructorVariant(Loc, Dtor); 16786 } 16787 } 16788 16789 Func->markUsed(Context); 16790 } 16791 } 16792 16793 /// Directly mark a variable odr-used. Given a choice, prefer to use 16794 /// MarkVariableReferenced since it does additional checks and then 16795 /// calls MarkVarDeclODRUsed. 16796 /// If the variable must be captured: 16797 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16798 /// - else capture it in the DeclContext that maps to the 16799 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16800 static void 16801 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16802 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16803 // Keep track of used but undefined variables. 16804 // FIXME: We shouldn't suppress this warning for static data members. 16805 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16806 (!Var->isExternallyVisible() || Var->isInline() || 16807 SemaRef.isExternalWithNoLinkageType(Var)) && 16808 !(Var->isStaticDataMember() && Var->hasInit())) { 16809 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16810 if (old.isInvalid()) 16811 old = Loc; 16812 } 16813 QualType CaptureType, DeclRefType; 16814 if (SemaRef.LangOpts.OpenMP) 16815 SemaRef.tryCaptureOpenMPLambdas(Var); 16816 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16817 /*EllipsisLoc*/ SourceLocation(), 16818 /*BuildAndDiagnose*/ true, 16819 CaptureType, DeclRefType, 16820 FunctionScopeIndexToStopAt); 16821 16822 Var->markUsed(SemaRef.Context); 16823 } 16824 16825 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16826 SourceLocation Loc, 16827 unsigned CapturingScopeIndex) { 16828 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16829 } 16830 16831 static void 16832 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16833 ValueDecl *var, DeclContext *DC) { 16834 DeclContext *VarDC = var->getDeclContext(); 16835 16836 // If the parameter still belongs to the translation unit, then 16837 // we're actually just using one parameter in the declaration of 16838 // the next. 16839 if (isa<ParmVarDecl>(var) && 16840 isa<TranslationUnitDecl>(VarDC)) 16841 return; 16842 16843 // For C code, don't diagnose about capture if we're not actually in code 16844 // right now; it's impossible to write a non-constant expression outside of 16845 // function context, so we'll get other (more useful) diagnostics later. 16846 // 16847 // For C++, things get a bit more nasty... it would be nice to suppress this 16848 // diagnostic for certain cases like using a local variable in an array bound 16849 // for a member of a local class, but the correct predicate is not obvious. 16850 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16851 return; 16852 16853 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16854 unsigned ContextKind = 3; // unknown 16855 if (isa<CXXMethodDecl>(VarDC) && 16856 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16857 ContextKind = 2; 16858 } else if (isa<FunctionDecl>(VarDC)) { 16859 ContextKind = 0; 16860 } else if (isa<BlockDecl>(VarDC)) { 16861 ContextKind = 1; 16862 } 16863 16864 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16865 << var << ValueKind << ContextKind << VarDC; 16866 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16867 << var; 16868 16869 // FIXME: Add additional diagnostic info about class etc. which prevents 16870 // capture. 16871 } 16872 16873 16874 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16875 bool &SubCapturesAreNested, 16876 QualType &CaptureType, 16877 QualType &DeclRefType) { 16878 // Check whether we've already captured it. 16879 if (CSI->CaptureMap.count(Var)) { 16880 // If we found a capture, any subcaptures are nested. 16881 SubCapturesAreNested = true; 16882 16883 // Retrieve the capture type for this variable. 16884 CaptureType = CSI->getCapture(Var).getCaptureType(); 16885 16886 // Compute the type of an expression that refers to this variable. 16887 DeclRefType = CaptureType.getNonReferenceType(); 16888 16889 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16890 // are mutable in the sense that user can change their value - they are 16891 // private instances of the captured declarations. 16892 const Capture &Cap = CSI->getCapture(Var); 16893 if (Cap.isCopyCapture() && 16894 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16895 !(isa<CapturedRegionScopeInfo>(CSI) && 16896 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16897 DeclRefType.addConst(); 16898 return true; 16899 } 16900 return false; 16901 } 16902 16903 // Only block literals, captured statements, and lambda expressions can 16904 // capture; other scopes don't work. 16905 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16906 SourceLocation Loc, 16907 const bool Diagnose, Sema &S) { 16908 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16909 return getLambdaAwareParentOfDeclContext(DC); 16910 else if (Var->hasLocalStorage()) { 16911 if (Diagnose) 16912 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16913 } 16914 return nullptr; 16915 } 16916 16917 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16918 // certain types of variables (unnamed, variably modified types etc.) 16919 // so check for eligibility. 16920 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16921 SourceLocation Loc, 16922 const bool Diagnose, Sema &S) { 16923 16924 bool IsBlock = isa<BlockScopeInfo>(CSI); 16925 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16926 16927 // Lambdas are not allowed to capture unnamed variables 16928 // (e.g. anonymous unions). 16929 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16930 // assuming that's the intent. 16931 if (IsLambda && !Var->getDeclName()) { 16932 if (Diagnose) { 16933 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16934 S.Diag(Var->getLocation(), diag::note_declared_at); 16935 } 16936 return false; 16937 } 16938 16939 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16940 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16941 if (Diagnose) { 16942 S.Diag(Loc, diag::err_ref_vm_type); 16943 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 16944 } 16945 return false; 16946 } 16947 // Prohibit structs with flexible array members too. 16948 // We cannot capture what is in the tail end of the struct. 16949 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16950 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16951 if (Diagnose) { 16952 if (IsBlock) 16953 S.Diag(Loc, diag::err_ref_flexarray_type); 16954 else 16955 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 16956 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 16957 } 16958 return false; 16959 } 16960 } 16961 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16962 // Lambdas and captured statements are not allowed to capture __block 16963 // variables; they don't support the expected semantics. 16964 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16965 if (Diagnose) { 16966 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 16967 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 16968 } 16969 return false; 16970 } 16971 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16972 if (S.getLangOpts().OpenCL && IsBlock && 16973 Var->getType()->isBlockPointerType()) { 16974 if (Diagnose) 16975 S.Diag(Loc, diag::err_opencl_block_ref_block); 16976 return false; 16977 } 16978 16979 return true; 16980 } 16981 16982 // Returns true if the capture by block was successful. 16983 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16984 SourceLocation Loc, 16985 const bool BuildAndDiagnose, 16986 QualType &CaptureType, 16987 QualType &DeclRefType, 16988 const bool Nested, 16989 Sema &S, bool Invalid) { 16990 bool ByRef = false; 16991 16992 // Blocks are not allowed to capture arrays, excepting OpenCL. 16993 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16994 // (decayed to pointers). 16995 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16996 if (BuildAndDiagnose) { 16997 S.Diag(Loc, diag::err_ref_array_type); 16998 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 16999 Invalid = true; 17000 } else { 17001 return false; 17002 } 17003 } 17004 17005 // Forbid the block-capture of autoreleasing variables. 17006 if (!Invalid && 17007 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17008 if (BuildAndDiagnose) { 17009 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17010 << /*block*/ 0; 17011 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17012 Invalid = true; 17013 } else { 17014 return false; 17015 } 17016 } 17017 17018 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17019 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17020 QualType PointeeTy = PT->getPointeeType(); 17021 17022 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17023 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17024 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17025 if (BuildAndDiagnose) { 17026 SourceLocation VarLoc = Var->getLocation(); 17027 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17028 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17029 } 17030 } 17031 } 17032 17033 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17034 if (HasBlocksAttr || CaptureType->isReferenceType() || 17035 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17036 // Block capture by reference does not change the capture or 17037 // declaration reference types. 17038 ByRef = true; 17039 } else { 17040 // Block capture by copy introduces 'const'. 17041 CaptureType = CaptureType.getNonReferenceType().withConst(); 17042 DeclRefType = CaptureType; 17043 } 17044 17045 // Actually capture the variable. 17046 if (BuildAndDiagnose) 17047 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17048 CaptureType, Invalid); 17049 17050 return !Invalid; 17051 } 17052 17053 17054 /// Capture the given variable in the captured region. 17055 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17056 VarDecl *Var, 17057 SourceLocation Loc, 17058 const bool BuildAndDiagnose, 17059 QualType &CaptureType, 17060 QualType &DeclRefType, 17061 const bool RefersToCapturedVariable, 17062 Sema &S, bool Invalid) { 17063 // By default, capture variables by reference. 17064 bool ByRef = true; 17065 // Using an LValue reference type is consistent with Lambdas (see below). 17066 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17067 if (S.isOpenMPCapturedDecl(Var)) { 17068 bool HasConst = DeclRefType.isConstQualified(); 17069 DeclRefType = DeclRefType.getUnqualifiedType(); 17070 // Don't lose diagnostics about assignments to const. 17071 if (HasConst) 17072 DeclRefType.addConst(); 17073 } 17074 // Do not capture firstprivates in tasks. 17075 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17076 OMPC_unknown) 17077 return true; 17078 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17079 RSI->OpenMPCaptureLevel); 17080 } 17081 17082 if (ByRef) 17083 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17084 else 17085 CaptureType = DeclRefType; 17086 17087 // Actually capture the variable. 17088 if (BuildAndDiagnose) 17089 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17090 Loc, SourceLocation(), CaptureType, Invalid); 17091 17092 return !Invalid; 17093 } 17094 17095 /// Capture the given variable in the lambda. 17096 static bool captureInLambda(LambdaScopeInfo *LSI, 17097 VarDecl *Var, 17098 SourceLocation Loc, 17099 const bool BuildAndDiagnose, 17100 QualType &CaptureType, 17101 QualType &DeclRefType, 17102 const bool RefersToCapturedVariable, 17103 const Sema::TryCaptureKind Kind, 17104 SourceLocation EllipsisLoc, 17105 const bool IsTopScope, 17106 Sema &S, bool Invalid) { 17107 // Determine whether we are capturing by reference or by value. 17108 bool ByRef = false; 17109 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17110 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17111 } else { 17112 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17113 } 17114 17115 // Compute the type of the field that will capture this variable. 17116 if (ByRef) { 17117 // C++11 [expr.prim.lambda]p15: 17118 // An entity is captured by reference if it is implicitly or 17119 // explicitly captured but not captured by copy. It is 17120 // unspecified whether additional unnamed non-static data 17121 // members are declared in the closure type for entities 17122 // captured by reference. 17123 // 17124 // FIXME: It is not clear whether we want to build an lvalue reference 17125 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17126 // to do the former, while EDG does the latter. Core issue 1249 will 17127 // clarify, but for now we follow GCC because it's a more permissive and 17128 // easily defensible position. 17129 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17130 } else { 17131 // C++11 [expr.prim.lambda]p14: 17132 // For each entity captured by copy, an unnamed non-static 17133 // data member is declared in the closure type. The 17134 // declaration order of these members is unspecified. The type 17135 // of such a data member is the type of the corresponding 17136 // captured entity if the entity is not a reference to an 17137 // object, or the referenced type otherwise. [Note: If the 17138 // captured entity is a reference to a function, the 17139 // corresponding data member is also a reference to a 17140 // function. - end note ] 17141 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17142 if (!RefType->getPointeeType()->isFunctionType()) 17143 CaptureType = RefType->getPointeeType(); 17144 } 17145 17146 // Forbid the lambda copy-capture of autoreleasing variables. 17147 if (!Invalid && 17148 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17149 if (BuildAndDiagnose) { 17150 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17151 S.Diag(Var->getLocation(), diag::note_previous_decl) 17152 << Var->getDeclName(); 17153 Invalid = true; 17154 } else { 17155 return false; 17156 } 17157 } 17158 17159 // Make sure that by-copy captures are of a complete and non-abstract type. 17160 if (!Invalid && BuildAndDiagnose) { 17161 if (!CaptureType->isDependentType() && 17162 S.RequireCompleteSizedType( 17163 Loc, CaptureType, 17164 diag::err_capture_of_incomplete_or_sizeless_type, 17165 Var->getDeclName())) 17166 Invalid = true; 17167 else if (S.RequireNonAbstractType(Loc, CaptureType, 17168 diag::err_capture_of_abstract_type)) 17169 Invalid = true; 17170 } 17171 } 17172 17173 // Compute the type of a reference to this captured variable. 17174 if (ByRef) 17175 DeclRefType = CaptureType.getNonReferenceType(); 17176 else { 17177 // C++ [expr.prim.lambda]p5: 17178 // The closure type for a lambda-expression has a public inline 17179 // function call operator [...]. This function call operator is 17180 // declared const (9.3.1) if and only if the lambda-expression's 17181 // parameter-declaration-clause is not followed by mutable. 17182 DeclRefType = CaptureType.getNonReferenceType(); 17183 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17184 DeclRefType.addConst(); 17185 } 17186 17187 // Add the capture. 17188 if (BuildAndDiagnose) 17189 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17190 Loc, EllipsisLoc, CaptureType, Invalid); 17191 17192 return !Invalid; 17193 } 17194 17195 bool Sema::tryCaptureVariable( 17196 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17197 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17198 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17199 // An init-capture is notionally from the context surrounding its 17200 // declaration, but its parent DC is the lambda class. 17201 DeclContext *VarDC = Var->getDeclContext(); 17202 if (Var->isInitCapture()) 17203 VarDC = VarDC->getParent(); 17204 17205 DeclContext *DC = CurContext; 17206 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17207 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17208 // We need to sync up the Declaration Context with the 17209 // FunctionScopeIndexToStopAt 17210 if (FunctionScopeIndexToStopAt) { 17211 unsigned FSIndex = FunctionScopes.size() - 1; 17212 while (FSIndex != MaxFunctionScopesIndex) { 17213 DC = getLambdaAwareParentOfDeclContext(DC); 17214 --FSIndex; 17215 } 17216 } 17217 17218 17219 // If the variable is declared in the current context, there is no need to 17220 // capture it. 17221 if (VarDC == DC) return true; 17222 17223 // Capture global variables if it is required to use private copy of this 17224 // variable. 17225 bool IsGlobal = !Var->hasLocalStorage(); 17226 if (IsGlobal && 17227 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17228 MaxFunctionScopesIndex))) 17229 return true; 17230 Var = Var->getCanonicalDecl(); 17231 17232 // Walk up the stack to determine whether we can capture the variable, 17233 // performing the "simple" checks that don't depend on type. We stop when 17234 // we've either hit the declared scope of the variable or find an existing 17235 // capture of that variable. We start from the innermost capturing-entity 17236 // (the DC) and ensure that all intervening capturing-entities 17237 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17238 // declcontext can either capture the variable or have already captured 17239 // the variable. 17240 CaptureType = Var->getType(); 17241 DeclRefType = CaptureType.getNonReferenceType(); 17242 bool Nested = false; 17243 bool Explicit = (Kind != TryCapture_Implicit); 17244 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17245 do { 17246 // Only block literals, captured statements, and lambda expressions can 17247 // capture; other scopes don't work. 17248 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17249 ExprLoc, 17250 BuildAndDiagnose, 17251 *this); 17252 // We need to check for the parent *first* because, if we *have* 17253 // private-captured a global variable, we need to recursively capture it in 17254 // intermediate blocks, lambdas, etc. 17255 if (!ParentDC) { 17256 if (IsGlobal) { 17257 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17258 break; 17259 } 17260 return true; 17261 } 17262 17263 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17264 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17265 17266 17267 // Check whether we've already captured it. 17268 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17269 DeclRefType)) { 17270 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17271 break; 17272 } 17273 // If we are instantiating a generic lambda call operator body, 17274 // we do not want to capture new variables. What was captured 17275 // during either a lambdas transformation or initial parsing 17276 // should be used. 17277 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17278 if (BuildAndDiagnose) { 17279 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17280 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17281 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17282 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17283 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17284 } else 17285 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17286 } 17287 return true; 17288 } 17289 17290 // Try to capture variable-length arrays types. 17291 if (Var->getType()->isVariablyModifiedType()) { 17292 // We're going to walk down into the type and look for VLA 17293 // expressions. 17294 QualType QTy = Var->getType(); 17295 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17296 QTy = PVD->getOriginalType(); 17297 captureVariablyModifiedType(Context, QTy, CSI); 17298 } 17299 17300 if (getLangOpts().OpenMP) { 17301 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17302 // OpenMP private variables should not be captured in outer scope, so 17303 // just break here. Similarly, global variables that are captured in a 17304 // target region should not be captured outside the scope of the region. 17305 if (RSI->CapRegionKind == CR_OpenMP) { 17306 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17307 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17308 // If the variable is private (i.e. not captured) and has variably 17309 // modified type, we still need to capture the type for correct 17310 // codegen in all regions, associated with the construct. Currently, 17311 // it is captured in the innermost captured region only. 17312 if (IsOpenMPPrivateDecl != OMPC_unknown && 17313 Var->getType()->isVariablyModifiedType()) { 17314 QualType QTy = Var->getType(); 17315 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17316 QTy = PVD->getOriginalType(); 17317 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17318 I < E; ++I) { 17319 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17320 FunctionScopes[FunctionScopesIndex - I]); 17321 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17322 "Wrong number of captured regions associated with the " 17323 "OpenMP construct."); 17324 captureVariablyModifiedType(Context, QTy, OuterRSI); 17325 } 17326 } 17327 bool IsTargetCap = 17328 IsOpenMPPrivateDecl != OMPC_private && 17329 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17330 RSI->OpenMPCaptureLevel); 17331 // Do not capture global if it is not privatized in outer regions. 17332 bool IsGlobalCap = 17333 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17334 RSI->OpenMPCaptureLevel); 17335 17336 // When we detect target captures we are looking from inside the 17337 // target region, therefore we need to propagate the capture from the 17338 // enclosing region. Therefore, the capture is not initially nested. 17339 if (IsTargetCap) 17340 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17341 17342 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17343 (IsGlobal && !IsGlobalCap)) { 17344 Nested = !IsTargetCap; 17345 DeclRefType = DeclRefType.getUnqualifiedType(); 17346 CaptureType = Context.getLValueReferenceType(DeclRefType); 17347 break; 17348 } 17349 } 17350 } 17351 } 17352 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17353 // No capture-default, and this is not an explicit capture 17354 // so cannot capture this variable. 17355 if (BuildAndDiagnose) { 17356 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17357 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17358 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17359 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17360 diag::note_lambda_decl); 17361 // FIXME: If we error out because an outer lambda can not implicitly 17362 // capture a variable that an inner lambda explicitly captures, we 17363 // should have the inner lambda do the explicit capture - because 17364 // it makes for cleaner diagnostics later. This would purely be done 17365 // so that the diagnostic does not misleadingly claim that a variable 17366 // can not be captured by a lambda implicitly even though it is captured 17367 // explicitly. Suggestion: 17368 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17369 // at the function head 17370 // - cache the StartingDeclContext - this must be a lambda 17371 // - captureInLambda in the innermost lambda the variable. 17372 } 17373 return true; 17374 } 17375 17376 FunctionScopesIndex--; 17377 DC = ParentDC; 17378 Explicit = false; 17379 } while (!VarDC->Equals(DC)); 17380 17381 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17382 // computing the type of the capture at each step, checking type-specific 17383 // requirements, and adding captures if requested. 17384 // If the variable had already been captured previously, we start capturing 17385 // at the lambda nested within that one. 17386 bool Invalid = false; 17387 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17388 ++I) { 17389 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17390 17391 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17392 // certain types of variables (unnamed, variably modified types etc.) 17393 // so check for eligibility. 17394 if (!Invalid) 17395 Invalid = 17396 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17397 17398 // After encountering an error, if we're actually supposed to capture, keep 17399 // capturing in nested contexts to suppress any follow-on diagnostics. 17400 if (Invalid && !BuildAndDiagnose) 17401 return true; 17402 17403 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17404 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17405 DeclRefType, Nested, *this, Invalid); 17406 Nested = true; 17407 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17408 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17409 CaptureType, DeclRefType, Nested, 17410 *this, Invalid); 17411 Nested = true; 17412 } else { 17413 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17414 Invalid = 17415 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17416 DeclRefType, Nested, Kind, EllipsisLoc, 17417 /*IsTopScope*/ I == N - 1, *this, Invalid); 17418 Nested = true; 17419 } 17420 17421 if (Invalid && !BuildAndDiagnose) 17422 return true; 17423 } 17424 return Invalid; 17425 } 17426 17427 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17428 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17429 QualType CaptureType; 17430 QualType DeclRefType; 17431 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17432 /*BuildAndDiagnose=*/true, CaptureType, 17433 DeclRefType, nullptr); 17434 } 17435 17436 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17437 QualType CaptureType; 17438 QualType DeclRefType; 17439 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17440 /*BuildAndDiagnose=*/false, CaptureType, 17441 DeclRefType, nullptr); 17442 } 17443 17444 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17445 QualType CaptureType; 17446 QualType DeclRefType; 17447 17448 // Determine whether we can capture this variable. 17449 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17450 /*BuildAndDiagnose=*/false, CaptureType, 17451 DeclRefType, nullptr)) 17452 return QualType(); 17453 17454 return DeclRefType; 17455 } 17456 17457 namespace { 17458 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17459 // The produced TemplateArgumentListInfo* points to data stored within this 17460 // object, so should only be used in contexts where the pointer will not be 17461 // used after the CopiedTemplateArgs object is destroyed. 17462 class CopiedTemplateArgs { 17463 bool HasArgs; 17464 TemplateArgumentListInfo TemplateArgStorage; 17465 public: 17466 template<typename RefExpr> 17467 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17468 if (HasArgs) 17469 E->copyTemplateArgumentsInto(TemplateArgStorage); 17470 } 17471 operator TemplateArgumentListInfo*() 17472 #ifdef __has_cpp_attribute 17473 #if __has_cpp_attribute(clang::lifetimebound) 17474 [[clang::lifetimebound]] 17475 #endif 17476 #endif 17477 { 17478 return HasArgs ? &TemplateArgStorage : nullptr; 17479 } 17480 }; 17481 } 17482 17483 /// Walk the set of potential results of an expression and mark them all as 17484 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17485 /// 17486 /// \return A new expression if we found any potential results, ExprEmpty() if 17487 /// not, and ExprError() if we diagnosed an error. 17488 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17489 NonOdrUseReason NOUR) { 17490 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17491 // an object that satisfies the requirements for appearing in a 17492 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17493 // is immediately applied." This function handles the lvalue-to-rvalue 17494 // conversion part. 17495 // 17496 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17497 // transform it into the relevant kind of non-odr-use node and rebuild the 17498 // tree of nodes leading to it. 17499 // 17500 // This is a mini-TreeTransform that only transforms a restricted subset of 17501 // nodes (and only certain operands of them). 17502 17503 // Rebuild a subexpression. 17504 auto Rebuild = [&](Expr *Sub) { 17505 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17506 }; 17507 17508 // Check whether a potential result satisfies the requirements of NOUR. 17509 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17510 // Any entity other than a VarDecl is always odr-used whenever it's named 17511 // in a potentially-evaluated expression. 17512 auto *VD = dyn_cast<VarDecl>(D); 17513 if (!VD) 17514 return true; 17515 17516 // C++2a [basic.def.odr]p4: 17517 // A variable x whose name appears as a potentially-evalauted expression 17518 // e is odr-used by e unless 17519 // -- x is a reference that is usable in constant expressions, or 17520 // -- x is a variable of non-reference type that is usable in constant 17521 // expressions and has no mutable subobjects, and e is an element of 17522 // the set of potential results of an expression of 17523 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17524 // conversion is applied, or 17525 // -- x is a variable of non-reference type, and e is an element of the 17526 // set of potential results of a discarded-value expression to which 17527 // the lvalue-to-rvalue conversion is not applied 17528 // 17529 // We check the first bullet and the "potentially-evaluated" condition in 17530 // BuildDeclRefExpr. We check the type requirements in the second bullet 17531 // in CheckLValueToRValueConversionOperand below. 17532 switch (NOUR) { 17533 case NOUR_None: 17534 case NOUR_Unevaluated: 17535 llvm_unreachable("unexpected non-odr-use-reason"); 17536 17537 case NOUR_Constant: 17538 // Constant references were handled when they were built. 17539 if (VD->getType()->isReferenceType()) 17540 return true; 17541 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17542 if (RD->hasMutableFields()) 17543 return true; 17544 if (!VD->isUsableInConstantExpressions(S.Context)) 17545 return true; 17546 break; 17547 17548 case NOUR_Discarded: 17549 if (VD->getType()->isReferenceType()) 17550 return true; 17551 break; 17552 } 17553 return false; 17554 }; 17555 17556 // Mark that this expression does not constitute an odr-use. 17557 auto MarkNotOdrUsed = [&] { 17558 S.MaybeODRUseExprs.remove(E); 17559 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17560 LSI->markVariableExprAsNonODRUsed(E); 17561 }; 17562 17563 // C++2a [basic.def.odr]p2: 17564 // The set of potential results of an expression e is defined as follows: 17565 switch (E->getStmtClass()) { 17566 // -- If e is an id-expression, ... 17567 case Expr::DeclRefExprClass: { 17568 auto *DRE = cast<DeclRefExpr>(E); 17569 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17570 break; 17571 17572 // Rebuild as a non-odr-use DeclRefExpr. 17573 MarkNotOdrUsed(); 17574 return DeclRefExpr::Create( 17575 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17576 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17577 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17578 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17579 } 17580 17581 case Expr::FunctionParmPackExprClass: { 17582 auto *FPPE = cast<FunctionParmPackExpr>(E); 17583 // If any of the declarations in the pack is odr-used, then the expression 17584 // as a whole constitutes an odr-use. 17585 for (VarDecl *D : *FPPE) 17586 if (IsPotentialResultOdrUsed(D)) 17587 return ExprEmpty(); 17588 17589 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17590 // nothing cares about whether we marked this as an odr-use, but it might 17591 // be useful for non-compiler tools. 17592 MarkNotOdrUsed(); 17593 break; 17594 } 17595 17596 // -- If e is a subscripting operation with an array operand... 17597 case Expr::ArraySubscriptExprClass: { 17598 auto *ASE = cast<ArraySubscriptExpr>(E); 17599 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17600 if (!OldBase->getType()->isArrayType()) 17601 break; 17602 ExprResult Base = Rebuild(OldBase); 17603 if (!Base.isUsable()) 17604 return Base; 17605 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17606 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17607 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17608 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17609 ASE->getRBracketLoc()); 17610 } 17611 17612 case Expr::MemberExprClass: { 17613 auto *ME = cast<MemberExpr>(E); 17614 // -- If e is a class member access expression [...] naming a non-static 17615 // data member... 17616 if (isa<FieldDecl>(ME->getMemberDecl())) { 17617 ExprResult Base = Rebuild(ME->getBase()); 17618 if (!Base.isUsable()) 17619 return Base; 17620 return MemberExpr::Create( 17621 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17622 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17623 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17624 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17625 ME->getObjectKind(), ME->isNonOdrUse()); 17626 } 17627 17628 if (ME->getMemberDecl()->isCXXInstanceMember()) 17629 break; 17630 17631 // -- If e is a class member access expression naming a static data member, 17632 // ... 17633 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17634 break; 17635 17636 // Rebuild as a non-odr-use MemberExpr. 17637 MarkNotOdrUsed(); 17638 return MemberExpr::Create( 17639 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17640 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17641 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17642 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17643 return ExprEmpty(); 17644 } 17645 17646 case Expr::BinaryOperatorClass: { 17647 auto *BO = cast<BinaryOperator>(E); 17648 Expr *LHS = BO->getLHS(); 17649 Expr *RHS = BO->getRHS(); 17650 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17651 if (BO->getOpcode() == BO_PtrMemD) { 17652 ExprResult Sub = Rebuild(LHS); 17653 if (!Sub.isUsable()) 17654 return Sub; 17655 LHS = Sub.get(); 17656 // -- If e is a comma expression, ... 17657 } else if (BO->getOpcode() == BO_Comma) { 17658 ExprResult Sub = Rebuild(RHS); 17659 if (!Sub.isUsable()) 17660 return Sub; 17661 RHS = Sub.get(); 17662 } else { 17663 break; 17664 } 17665 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17666 LHS, RHS); 17667 } 17668 17669 // -- If e has the form (e1)... 17670 case Expr::ParenExprClass: { 17671 auto *PE = cast<ParenExpr>(E); 17672 ExprResult Sub = Rebuild(PE->getSubExpr()); 17673 if (!Sub.isUsable()) 17674 return Sub; 17675 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17676 } 17677 17678 // -- If e is a glvalue conditional expression, ... 17679 // We don't apply this to a binary conditional operator. FIXME: Should we? 17680 case Expr::ConditionalOperatorClass: { 17681 auto *CO = cast<ConditionalOperator>(E); 17682 ExprResult LHS = Rebuild(CO->getLHS()); 17683 if (LHS.isInvalid()) 17684 return ExprError(); 17685 ExprResult RHS = Rebuild(CO->getRHS()); 17686 if (RHS.isInvalid()) 17687 return ExprError(); 17688 if (!LHS.isUsable() && !RHS.isUsable()) 17689 return ExprEmpty(); 17690 if (!LHS.isUsable()) 17691 LHS = CO->getLHS(); 17692 if (!RHS.isUsable()) 17693 RHS = CO->getRHS(); 17694 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17695 CO->getCond(), LHS.get(), RHS.get()); 17696 } 17697 17698 // [Clang extension] 17699 // -- If e has the form __extension__ e1... 17700 case Expr::UnaryOperatorClass: { 17701 auto *UO = cast<UnaryOperator>(E); 17702 if (UO->getOpcode() != UO_Extension) 17703 break; 17704 ExprResult Sub = Rebuild(UO->getSubExpr()); 17705 if (!Sub.isUsable()) 17706 return Sub; 17707 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17708 Sub.get()); 17709 } 17710 17711 // [Clang extension] 17712 // -- If e has the form _Generic(...), the set of potential results is the 17713 // union of the sets of potential results of the associated expressions. 17714 case Expr::GenericSelectionExprClass: { 17715 auto *GSE = cast<GenericSelectionExpr>(E); 17716 17717 SmallVector<Expr *, 4> AssocExprs; 17718 bool AnyChanged = false; 17719 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17720 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17721 if (AssocExpr.isInvalid()) 17722 return ExprError(); 17723 if (AssocExpr.isUsable()) { 17724 AssocExprs.push_back(AssocExpr.get()); 17725 AnyChanged = true; 17726 } else { 17727 AssocExprs.push_back(OrigAssocExpr); 17728 } 17729 } 17730 17731 return AnyChanged ? S.CreateGenericSelectionExpr( 17732 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17733 GSE->getRParenLoc(), GSE->getControllingExpr(), 17734 GSE->getAssocTypeSourceInfos(), AssocExprs) 17735 : ExprEmpty(); 17736 } 17737 17738 // [Clang extension] 17739 // -- If e has the form __builtin_choose_expr(...), the set of potential 17740 // results is the union of the sets of potential results of the 17741 // second and third subexpressions. 17742 case Expr::ChooseExprClass: { 17743 auto *CE = cast<ChooseExpr>(E); 17744 17745 ExprResult LHS = Rebuild(CE->getLHS()); 17746 if (LHS.isInvalid()) 17747 return ExprError(); 17748 17749 ExprResult RHS = Rebuild(CE->getLHS()); 17750 if (RHS.isInvalid()) 17751 return ExprError(); 17752 17753 if (!LHS.get() && !RHS.get()) 17754 return ExprEmpty(); 17755 if (!LHS.isUsable()) 17756 LHS = CE->getLHS(); 17757 if (!RHS.isUsable()) 17758 RHS = CE->getRHS(); 17759 17760 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17761 RHS.get(), CE->getRParenLoc()); 17762 } 17763 17764 // Step through non-syntactic nodes. 17765 case Expr::ConstantExprClass: { 17766 auto *CE = cast<ConstantExpr>(E); 17767 ExprResult Sub = Rebuild(CE->getSubExpr()); 17768 if (!Sub.isUsable()) 17769 return Sub; 17770 return ConstantExpr::Create(S.Context, Sub.get()); 17771 } 17772 17773 // We could mostly rely on the recursive rebuilding to rebuild implicit 17774 // casts, but not at the top level, so rebuild them here. 17775 case Expr::ImplicitCastExprClass: { 17776 auto *ICE = cast<ImplicitCastExpr>(E); 17777 // Only step through the narrow set of cast kinds we expect to encounter. 17778 // Anything else suggests we've left the region in which potential results 17779 // can be found. 17780 switch (ICE->getCastKind()) { 17781 case CK_NoOp: 17782 case CK_DerivedToBase: 17783 case CK_UncheckedDerivedToBase: { 17784 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17785 if (!Sub.isUsable()) 17786 return Sub; 17787 CXXCastPath Path(ICE->path()); 17788 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17789 ICE->getValueKind(), &Path); 17790 } 17791 17792 default: 17793 break; 17794 } 17795 break; 17796 } 17797 17798 default: 17799 break; 17800 } 17801 17802 // Can't traverse through this node. Nothing to do. 17803 return ExprEmpty(); 17804 } 17805 17806 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17807 // Check whether the operand is or contains an object of non-trivial C union 17808 // type. 17809 if (E->getType().isVolatileQualified() && 17810 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17811 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17812 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17813 Sema::NTCUC_LValueToRValueVolatile, 17814 NTCUK_Destruct|NTCUK_Copy); 17815 17816 // C++2a [basic.def.odr]p4: 17817 // [...] an expression of non-volatile-qualified non-class type to which 17818 // the lvalue-to-rvalue conversion is applied [...] 17819 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17820 return E; 17821 17822 ExprResult Result = 17823 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17824 if (Result.isInvalid()) 17825 return ExprError(); 17826 return Result.get() ? Result : E; 17827 } 17828 17829 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17830 Res = CorrectDelayedTyposInExpr(Res); 17831 17832 if (!Res.isUsable()) 17833 return Res; 17834 17835 // If a constant-expression is a reference to a variable where we delay 17836 // deciding whether it is an odr-use, just assume we will apply the 17837 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17838 // (a non-type template argument), we have special handling anyway. 17839 return CheckLValueToRValueConversionOperand(Res.get()); 17840 } 17841 17842 void Sema::CleanupVarDeclMarking() { 17843 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17844 // call. 17845 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17846 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17847 17848 for (Expr *E : LocalMaybeODRUseExprs) { 17849 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17850 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17851 DRE->getLocation(), *this); 17852 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17853 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17854 *this); 17855 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17856 for (VarDecl *VD : *FP) 17857 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17858 } else { 17859 llvm_unreachable("Unexpected expression"); 17860 } 17861 } 17862 17863 assert(MaybeODRUseExprs.empty() && 17864 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17865 } 17866 17867 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17868 VarDecl *Var, Expr *E) { 17869 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17870 isa<FunctionParmPackExpr>(E)) && 17871 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17872 Var->setReferenced(); 17873 17874 if (Var->isInvalidDecl()) 17875 return; 17876 17877 // Record a CUDA/HIP static device/constant variable if it is referenced 17878 // by host code. This is done conservatively, when the variable is referenced 17879 // in any of the following contexts: 17880 // - a non-function context 17881 // - a host function 17882 // - a host device function 17883 // This also requires the reference of the static device/constant variable by 17884 // host code to be visible in the device compilation for the compiler to be 17885 // able to externalize the static device/constant variable. 17886 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 17887 auto *CurContext = SemaRef.CurContext; 17888 if (!CurContext || !isa<FunctionDecl>(CurContext) || 17889 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 17890 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 17891 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 17892 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 17893 } 17894 17895 auto *MSI = Var->getMemberSpecializationInfo(); 17896 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17897 : Var->getTemplateSpecializationKind(); 17898 17899 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17900 bool UsableInConstantExpr = 17901 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17902 17903 // C++20 [expr.const]p12: 17904 // A variable [...] is needed for constant evaluation if it is [...] a 17905 // variable whose name appears as a potentially constant evaluated 17906 // expression that is either a contexpr variable or is of non-volatile 17907 // const-qualified integral type or of reference type 17908 bool NeededForConstantEvaluation = 17909 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17910 17911 bool NeedDefinition = 17912 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17913 17914 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17915 "Can't instantiate a partial template specialization."); 17916 17917 // If this might be a member specialization of a static data member, check 17918 // the specialization is visible. We already did the checks for variable 17919 // template specializations when we created them. 17920 if (NeedDefinition && TSK != TSK_Undeclared && 17921 !isa<VarTemplateSpecializationDecl>(Var)) 17922 SemaRef.checkSpecializationVisibility(Loc, Var); 17923 17924 // Perform implicit instantiation of static data members, static data member 17925 // templates of class templates, and variable template specializations. Delay 17926 // instantiations of variable templates, except for those that could be used 17927 // in a constant expression. 17928 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17929 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17930 // instantiation declaration if a variable is usable in a constant 17931 // expression (among other cases). 17932 bool TryInstantiating = 17933 TSK == TSK_ImplicitInstantiation || 17934 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17935 17936 if (TryInstantiating) { 17937 SourceLocation PointOfInstantiation = 17938 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17939 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17940 if (FirstInstantiation) { 17941 PointOfInstantiation = Loc; 17942 if (MSI) 17943 MSI->setPointOfInstantiation(PointOfInstantiation); 17944 else 17945 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17946 } 17947 17948 if (UsableInConstantExpr) { 17949 // Do not defer instantiations of variables that could be used in a 17950 // constant expression. 17951 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17952 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17953 }); 17954 } else if (FirstInstantiation || 17955 isa<VarTemplateSpecializationDecl>(Var)) { 17956 // FIXME: For a specialization of a variable template, we don't 17957 // distinguish between "declaration and type implicitly instantiated" 17958 // and "implicit instantiation of definition requested", so we have 17959 // no direct way to avoid enqueueing the pending instantiation 17960 // multiple times. 17961 SemaRef.PendingInstantiations 17962 .push_back(std::make_pair(Var, PointOfInstantiation)); 17963 } 17964 } 17965 } 17966 17967 // C++2a [basic.def.odr]p4: 17968 // A variable x whose name appears as a potentially-evaluated expression e 17969 // is odr-used by e unless 17970 // -- x is a reference that is usable in constant expressions 17971 // -- x is a variable of non-reference type that is usable in constant 17972 // expressions and has no mutable subobjects [FIXME], and e is an 17973 // element of the set of potential results of an expression of 17974 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17975 // conversion is applied 17976 // -- x is a variable of non-reference type, and e is an element of the set 17977 // of potential results of a discarded-value expression to which the 17978 // lvalue-to-rvalue conversion is not applied [FIXME] 17979 // 17980 // We check the first part of the second bullet here, and 17981 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17982 // FIXME: To get the third bullet right, we need to delay this even for 17983 // variables that are not usable in constant expressions. 17984 17985 // If we already know this isn't an odr-use, there's nothing more to do. 17986 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17987 if (DRE->isNonOdrUse()) 17988 return; 17989 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17990 if (ME->isNonOdrUse()) 17991 return; 17992 17993 switch (OdrUse) { 17994 case OdrUseContext::None: 17995 assert((!E || isa<FunctionParmPackExpr>(E)) && 17996 "missing non-odr-use marking for unevaluated decl ref"); 17997 break; 17998 17999 case OdrUseContext::FormallyOdrUsed: 18000 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18001 // behavior. 18002 break; 18003 18004 case OdrUseContext::Used: 18005 // If we might later find that this expression isn't actually an odr-use, 18006 // delay the marking. 18007 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18008 SemaRef.MaybeODRUseExprs.insert(E); 18009 else 18010 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18011 break; 18012 18013 case OdrUseContext::Dependent: 18014 // If this is a dependent context, we don't need to mark variables as 18015 // odr-used, but we may still need to track them for lambda capture. 18016 // FIXME: Do we also need to do this inside dependent typeid expressions 18017 // (which are modeled as unevaluated at this point)? 18018 const bool RefersToEnclosingScope = 18019 (SemaRef.CurContext != Var->getDeclContext() && 18020 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18021 if (RefersToEnclosingScope) { 18022 LambdaScopeInfo *const LSI = 18023 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18024 if (LSI && (!LSI->CallOperator || 18025 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18026 // If a variable could potentially be odr-used, defer marking it so 18027 // until we finish analyzing the full expression for any 18028 // lvalue-to-rvalue 18029 // or discarded value conversions that would obviate odr-use. 18030 // Add it to the list of potential captures that will be analyzed 18031 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18032 // unless the variable is a reference that was initialized by a constant 18033 // expression (this will never need to be captured or odr-used). 18034 // 18035 // FIXME: We can simplify this a lot after implementing P0588R1. 18036 assert(E && "Capture variable should be used in an expression."); 18037 if (!Var->getType()->isReferenceType() || 18038 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18039 LSI->addPotentialCapture(E->IgnoreParens()); 18040 } 18041 } 18042 break; 18043 } 18044 } 18045 18046 /// Mark a variable referenced, and check whether it is odr-used 18047 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18048 /// used directly for normal expressions referring to VarDecl. 18049 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18050 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18051 } 18052 18053 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18054 Decl *D, Expr *E, bool MightBeOdrUse) { 18055 if (SemaRef.isInOpenMPDeclareTargetContext()) 18056 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18057 18058 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18059 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18060 return; 18061 } 18062 18063 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18064 18065 // If this is a call to a method via a cast, also mark the method in the 18066 // derived class used in case codegen can devirtualize the call. 18067 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18068 if (!ME) 18069 return; 18070 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18071 if (!MD) 18072 return; 18073 // Only attempt to devirtualize if this is truly a virtual call. 18074 bool IsVirtualCall = MD->isVirtual() && 18075 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18076 if (!IsVirtualCall) 18077 return; 18078 18079 // If it's possible to devirtualize the call, mark the called function 18080 // referenced. 18081 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18082 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18083 if (DM) 18084 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18085 } 18086 18087 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18088 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18089 // TODO: update this with DR# once a defect report is filed. 18090 // C++11 defect. The address of a pure member should not be an ODR use, even 18091 // if it's a qualified reference. 18092 bool OdrUse = true; 18093 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18094 if (Method->isVirtual() && 18095 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18096 OdrUse = false; 18097 18098 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18099 if (!isConstantEvaluated() && FD->isConsteval() && 18100 !RebuildingImmediateInvocation) 18101 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18102 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18103 } 18104 18105 /// Perform reference-marking and odr-use handling for a MemberExpr. 18106 void Sema::MarkMemberReferenced(MemberExpr *E) { 18107 // C++11 [basic.def.odr]p2: 18108 // A non-overloaded function whose name appears as a potentially-evaluated 18109 // expression or a member of a set of candidate functions, if selected by 18110 // overload resolution when referred to from a potentially-evaluated 18111 // expression, is odr-used, unless it is a pure virtual function and its 18112 // name is not explicitly qualified. 18113 bool MightBeOdrUse = true; 18114 if (E->performsVirtualDispatch(getLangOpts())) { 18115 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18116 if (Method->isPure()) 18117 MightBeOdrUse = false; 18118 } 18119 SourceLocation Loc = 18120 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18121 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18122 } 18123 18124 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18125 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18126 for (VarDecl *VD : *E) 18127 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18128 } 18129 18130 /// Perform marking for a reference to an arbitrary declaration. It 18131 /// marks the declaration referenced, and performs odr-use checking for 18132 /// functions and variables. This method should not be used when building a 18133 /// normal expression which refers to a variable. 18134 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18135 bool MightBeOdrUse) { 18136 if (MightBeOdrUse) { 18137 if (auto *VD = dyn_cast<VarDecl>(D)) { 18138 MarkVariableReferenced(Loc, VD); 18139 return; 18140 } 18141 } 18142 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18143 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18144 return; 18145 } 18146 D->setReferenced(); 18147 } 18148 18149 namespace { 18150 // Mark all of the declarations used by a type as referenced. 18151 // FIXME: Not fully implemented yet! We need to have a better understanding 18152 // of when we're entering a context we should not recurse into. 18153 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18154 // TreeTransforms rebuilding the type in a new context. Rather than 18155 // duplicating the TreeTransform logic, we should consider reusing it here. 18156 // Currently that causes problems when rebuilding LambdaExprs. 18157 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18158 Sema &S; 18159 SourceLocation Loc; 18160 18161 public: 18162 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18163 18164 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18165 18166 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18167 }; 18168 } 18169 18170 bool MarkReferencedDecls::TraverseTemplateArgument( 18171 const TemplateArgument &Arg) { 18172 { 18173 // A non-type template argument is a constant-evaluated context. 18174 EnterExpressionEvaluationContext Evaluated( 18175 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18176 if (Arg.getKind() == TemplateArgument::Declaration) { 18177 if (Decl *D = Arg.getAsDecl()) 18178 S.MarkAnyDeclReferenced(Loc, D, true); 18179 } else if (Arg.getKind() == TemplateArgument::Expression) { 18180 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18181 } 18182 } 18183 18184 return Inherited::TraverseTemplateArgument(Arg); 18185 } 18186 18187 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18188 MarkReferencedDecls Marker(*this, Loc); 18189 Marker.TraverseType(T); 18190 } 18191 18192 namespace { 18193 /// Helper class that marks all of the declarations referenced by 18194 /// potentially-evaluated subexpressions as "referenced". 18195 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18196 public: 18197 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18198 bool SkipLocalVariables; 18199 18200 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18201 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18202 18203 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18204 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18205 } 18206 18207 void VisitDeclRefExpr(DeclRefExpr *E) { 18208 // If we were asked not to visit local variables, don't. 18209 if (SkipLocalVariables) { 18210 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18211 if (VD->hasLocalStorage()) 18212 return; 18213 } 18214 S.MarkDeclRefReferenced(E); 18215 } 18216 18217 void VisitMemberExpr(MemberExpr *E) { 18218 S.MarkMemberReferenced(E); 18219 Visit(E->getBase()); 18220 } 18221 }; 18222 } // namespace 18223 18224 /// Mark any declarations that appear within this expression or any 18225 /// potentially-evaluated subexpressions as "referenced". 18226 /// 18227 /// \param SkipLocalVariables If true, don't mark local variables as 18228 /// 'referenced'. 18229 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18230 bool SkipLocalVariables) { 18231 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18232 } 18233 18234 /// Emit a diagnostic that describes an effect on the run-time behavior 18235 /// of the program being compiled. 18236 /// 18237 /// This routine emits the given diagnostic when the code currently being 18238 /// type-checked is "potentially evaluated", meaning that there is a 18239 /// possibility that the code will actually be executable. Code in sizeof() 18240 /// expressions, code used only during overload resolution, etc., are not 18241 /// potentially evaluated. This routine will suppress such diagnostics or, 18242 /// in the absolutely nutty case of potentially potentially evaluated 18243 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18244 /// later. 18245 /// 18246 /// This routine should be used for all diagnostics that describe the run-time 18247 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18248 /// Failure to do so will likely result in spurious diagnostics or failures 18249 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18250 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18251 const PartialDiagnostic &PD) { 18252 switch (ExprEvalContexts.back().Context) { 18253 case ExpressionEvaluationContext::Unevaluated: 18254 case ExpressionEvaluationContext::UnevaluatedList: 18255 case ExpressionEvaluationContext::UnevaluatedAbstract: 18256 case ExpressionEvaluationContext::DiscardedStatement: 18257 // The argument will never be evaluated, so don't complain. 18258 break; 18259 18260 case ExpressionEvaluationContext::ConstantEvaluated: 18261 // Relevant diagnostics should be produced by constant evaluation. 18262 break; 18263 18264 case ExpressionEvaluationContext::PotentiallyEvaluated: 18265 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18266 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18267 FunctionScopes.back()->PossiblyUnreachableDiags. 18268 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18269 return true; 18270 } 18271 18272 // The initializer of a constexpr variable or of the first declaration of a 18273 // static data member is not syntactically a constant evaluated constant, 18274 // but nonetheless is always required to be a constant expression, so we 18275 // can skip diagnosing. 18276 // FIXME: Using the mangling context here is a hack. 18277 if (auto *VD = dyn_cast_or_null<VarDecl>( 18278 ExprEvalContexts.back().ManglingContextDecl)) { 18279 if (VD->isConstexpr() || 18280 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18281 break; 18282 // FIXME: For any other kind of variable, we should build a CFG for its 18283 // initializer and check whether the context in question is reachable. 18284 } 18285 18286 Diag(Loc, PD); 18287 return true; 18288 } 18289 18290 return false; 18291 } 18292 18293 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18294 const PartialDiagnostic &PD) { 18295 return DiagRuntimeBehavior( 18296 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18297 } 18298 18299 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18300 CallExpr *CE, FunctionDecl *FD) { 18301 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18302 return false; 18303 18304 // If we're inside a decltype's expression, don't check for a valid return 18305 // type or construct temporaries until we know whether this is the last call. 18306 if (ExprEvalContexts.back().ExprContext == 18307 ExpressionEvaluationContextRecord::EK_Decltype) { 18308 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18309 return false; 18310 } 18311 18312 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18313 FunctionDecl *FD; 18314 CallExpr *CE; 18315 18316 public: 18317 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18318 : FD(FD), CE(CE) { } 18319 18320 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18321 if (!FD) { 18322 S.Diag(Loc, diag::err_call_incomplete_return) 18323 << T << CE->getSourceRange(); 18324 return; 18325 } 18326 18327 S.Diag(Loc, diag::err_call_function_incomplete_return) 18328 << CE->getSourceRange() << FD << T; 18329 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18330 << FD->getDeclName(); 18331 } 18332 } Diagnoser(FD, CE); 18333 18334 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18335 return true; 18336 18337 return false; 18338 } 18339 18340 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18341 // will prevent this condition from triggering, which is what we want. 18342 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18343 SourceLocation Loc; 18344 18345 unsigned diagnostic = diag::warn_condition_is_assignment; 18346 bool IsOrAssign = false; 18347 18348 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18349 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18350 return; 18351 18352 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18353 18354 // Greylist some idioms by putting them into a warning subcategory. 18355 if (ObjCMessageExpr *ME 18356 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18357 Selector Sel = ME->getSelector(); 18358 18359 // self = [<foo> init...] 18360 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18361 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18362 18363 // <foo> = [<bar> nextObject] 18364 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18365 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18366 } 18367 18368 Loc = Op->getOperatorLoc(); 18369 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18370 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18371 return; 18372 18373 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18374 Loc = Op->getOperatorLoc(); 18375 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18376 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18377 else { 18378 // Not an assignment. 18379 return; 18380 } 18381 18382 Diag(Loc, diagnostic) << E->getSourceRange(); 18383 18384 SourceLocation Open = E->getBeginLoc(); 18385 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18386 Diag(Loc, diag::note_condition_assign_silence) 18387 << FixItHint::CreateInsertion(Open, "(") 18388 << FixItHint::CreateInsertion(Close, ")"); 18389 18390 if (IsOrAssign) 18391 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18392 << FixItHint::CreateReplacement(Loc, "!="); 18393 else 18394 Diag(Loc, diag::note_condition_assign_to_comparison) 18395 << FixItHint::CreateReplacement(Loc, "=="); 18396 } 18397 18398 /// Redundant parentheses over an equality comparison can indicate 18399 /// that the user intended an assignment used as condition. 18400 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18401 // Don't warn if the parens came from a macro. 18402 SourceLocation parenLoc = ParenE->getBeginLoc(); 18403 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18404 return; 18405 // Don't warn for dependent expressions. 18406 if (ParenE->isTypeDependent()) 18407 return; 18408 18409 Expr *E = ParenE->IgnoreParens(); 18410 18411 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18412 if (opE->getOpcode() == BO_EQ && 18413 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18414 == Expr::MLV_Valid) { 18415 SourceLocation Loc = opE->getOperatorLoc(); 18416 18417 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18418 SourceRange ParenERange = ParenE->getSourceRange(); 18419 Diag(Loc, diag::note_equality_comparison_silence) 18420 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18421 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18422 Diag(Loc, diag::note_equality_comparison_to_assign) 18423 << FixItHint::CreateReplacement(Loc, "="); 18424 } 18425 } 18426 18427 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18428 bool IsConstexpr) { 18429 DiagnoseAssignmentAsCondition(E); 18430 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18431 DiagnoseEqualityWithExtraParens(parenE); 18432 18433 ExprResult result = CheckPlaceholderExpr(E); 18434 if (result.isInvalid()) return ExprError(); 18435 E = result.get(); 18436 18437 if (!E->isTypeDependent()) { 18438 if (getLangOpts().CPlusPlus) 18439 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18440 18441 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18442 if (ERes.isInvalid()) 18443 return ExprError(); 18444 E = ERes.get(); 18445 18446 QualType T = E->getType(); 18447 if (!T->isScalarType()) { // C99 6.8.4.1p1 18448 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18449 << T << E->getSourceRange(); 18450 return ExprError(); 18451 } 18452 CheckBoolLikeConversion(E, Loc); 18453 } 18454 18455 return E; 18456 } 18457 18458 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18459 Expr *SubExpr, ConditionKind CK) { 18460 // Empty conditions are valid in for-statements. 18461 if (!SubExpr) 18462 return ConditionResult(); 18463 18464 ExprResult Cond; 18465 switch (CK) { 18466 case ConditionKind::Boolean: 18467 Cond = CheckBooleanCondition(Loc, SubExpr); 18468 break; 18469 18470 case ConditionKind::ConstexprIf: 18471 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18472 break; 18473 18474 case ConditionKind::Switch: 18475 Cond = CheckSwitchCondition(Loc, SubExpr); 18476 break; 18477 } 18478 if (Cond.isInvalid()) { 18479 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18480 {SubExpr}); 18481 if (!Cond.get()) 18482 return ConditionError(); 18483 } 18484 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18485 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18486 if (!FullExpr.get()) 18487 return ConditionError(); 18488 18489 return ConditionResult(*this, nullptr, FullExpr, 18490 CK == ConditionKind::ConstexprIf); 18491 } 18492 18493 namespace { 18494 /// A visitor for rebuilding a call to an __unknown_any expression 18495 /// to have an appropriate type. 18496 struct RebuildUnknownAnyFunction 18497 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18498 18499 Sema &S; 18500 18501 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18502 18503 ExprResult VisitStmt(Stmt *S) { 18504 llvm_unreachable("unexpected statement!"); 18505 } 18506 18507 ExprResult VisitExpr(Expr *E) { 18508 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18509 << E->getSourceRange(); 18510 return ExprError(); 18511 } 18512 18513 /// Rebuild an expression which simply semantically wraps another 18514 /// expression which it shares the type and value kind of. 18515 template <class T> ExprResult rebuildSugarExpr(T *E) { 18516 ExprResult SubResult = Visit(E->getSubExpr()); 18517 if (SubResult.isInvalid()) return ExprError(); 18518 18519 Expr *SubExpr = SubResult.get(); 18520 E->setSubExpr(SubExpr); 18521 E->setType(SubExpr->getType()); 18522 E->setValueKind(SubExpr->getValueKind()); 18523 assert(E->getObjectKind() == OK_Ordinary); 18524 return E; 18525 } 18526 18527 ExprResult VisitParenExpr(ParenExpr *E) { 18528 return rebuildSugarExpr(E); 18529 } 18530 18531 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18532 return rebuildSugarExpr(E); 18533 } 18534 18535 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18536 ExprResult SubResult = Visit(E->getSubExpr()); 18537 if (SubResult.isInvalid()) return ExprError(); 18538 18539 Expr *SubExpr = SubResult.get(); 18540 E->setSubExpr(SubExpr); 18541 E->setType(S.Context.getPointerType(SubExpr->getType())); 18542 assert(E->getValueKind() == VK_RValue); 18543 assert(E->getObjectKind() == OK_Ordinary); 18544 return E; 18545 } 18546 18547 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18548 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18549 18550 E->setType(VD->getType()); 18551 18552 assert(E->getValueKind() == VK_RValue); 18553 if (S.getLangOpts().CPlusPlus && 18554 !(isa<CXXMethodDecl>(VD) && 18555 cast<CXXMethodDecl>(VD)->isInstance())) 18556 E->setValueKind(VK_LValue); 18557 18558 return E; 18559 } 18560 18561 ExprResult VisitMemberExpr(MemberExpr *E) { 18562 return resolveDecl(E, E->getMemberDecl()); 18563 } 18564 18565 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18566 return resolveDecl(E, E->getDecl()); 18567 } 18568 }; 18569 } 18570 18571 /// Given a function expression of unknown-any type, try to rebuild it 18572 /// to have a function type. 18573 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18574 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18575 if (Result.isInvalid()) return ExprError(); 18576 return S.DefaultFunctionArrayConversion(Result.get()); 18577 } 18578 18579 namespace { 18580 /// A visitor for rebuilding an expression of type __unknown_anytype 18581 /// into one which resolves the type directly on the referring 18582 /// expression. Strict preservation of the original source 18583 /// structure is not a goal. 18584 struct RebuildUnknownAnyExpr 18585 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18586 18587 Sema &S; 18588 18589 /// The current destination type. 18590 QualType DestType; 18591 18592 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18593 : S(S), DestType(CastType) {} 18594 18595 ExprResult VisitStmt(Stmt *S) { 18596 llvm_unreachable("unexpected statement!"); 18597 } 18598 18599 ExprResult VisitExpr(Expr *E) { 18600 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18601 << E->getSourceRange(); 18602 return ExprError(); 18603 } 18604 18605 ExprResult VisitCallExpr(CallExpr *E); 18606 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18607 18608 /// Rebuild an expression which simply semantically wraps another 18609 /// expression which it shares the type and value kind of. 18610 template <class T> ExprResult rebuildSugarExpr(T *E) { 18611 ExprResult SubResult = Visit(E->getSubExpr()); 18612 if (SubResult.isInvalid()) return ExprError(); 18613 Expr *SubExpr = SubResult.get(); 18614 E->setSubExpr(SubExpr); 18615 E->setType(SubExpr->getType()); 18616 E->setValueKind(SubExpr->getValueKind()); 18617 assert(E->getObjectKind() == OK_Ordinary); 18618 return E; 18619 } 18620 18621 ExprResult VisitParenExpr(ParenExpr *E) { 18622 return rebuildSugarExpr(E); 18623 } 18624 18625 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18626 return rebuildSugarExpr(E); 18627 } 18628 18629 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18630 const PointerType *Ptr = DestType->getAs<PointerType>(); 18631 if (!Ptr) { 18632 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18633 << E->getSourceRange(); 18634 return ExprError(); 18635 } 18636 18637 if (isa<CallExpr>(E->getSubExpr())) { 18638 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18639 << E->getSourceRange(); 18640 return ExprError(); 18641 } 18642 18643 assert(E->getValueKind() == VK_RValue); 18644 assert(E->getObjectKind() == OK_Ordinary); 18645 E->setType(DestType); 18646 18647 // Build the sub-expression as if it were an object of the pointee type. 18648 DestType = Ptr->getPointeeType(); 18649 ExprResult SubResult = Visit(E->getSubExpr()); 18650 if (SubResult.isInvalid()) return ExprError(); 18651 E->setSubExpr(SubResult.get()); 18652 return E; 18653 } 18654 18655 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18656 18657 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18658 18659 ExprResult VisitMemberExpr(MemberExpr *E) { 18660 return resolveDecl(E, E->getMemberDecl()); 18661 } 18662 18663 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18664 return resolveDecl(E, E->getDecl()); 18665 } 18666 }; 18667 } 18668 18669 /// Rebuilds a call expression which yielded __unknown_anytype. 18670 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18671 Expr *CalleeExpr = E->getCallee(); 18672 18673 enum FnKind { 18674 FK_MemberFunction, 18675 FK_FunctionPointer, 18676 FK_BlockPointer 18677 }; 18678 18679 FnKind Kind; 18680 QualType CalleeType = CalleeExpr->getType(); 18681 if (CalleeType == S.Context.BoundMemberTy) { 18682 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18683 Kind = FK_MemberFunction; 18684 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18685 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18686 CalleeType = Ptr->getPointeeType(); 18687 Kind = FK_FunctionPointer; 18688 } else { 18689 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18690 Kind = FK_BlockPointer; 18691 } 18692 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18693 18694 // Verify that this is a legal result type of a function. 18695 if (DestType->isArrayType() || DestType->isFunctionType()) { 18696 unsigned diagID = diag::err_func_returning_array_function; 18697 if (Kind == FK_BlockPointer) 18698 diagID = diag::err_block_returning_array_function; 18699 18700 S.Diag(E->getExprLoc(), diagID) 18701 << DestType->isFunctionType() << DestType; 18702 return ExprError(); 18703 } 18704 18705 // Otherwise, go ahead and set DestType as the call's result. 18706 E->setType(DestType.getNonLValueExprType(S.Context)); 18707 E->setValueKind(Expr::getValueKindForType(DestType)); 18708 assert(E->getObjectKind() == OK_Ordinary); 18709 18710 // Rebuild the function type, replacing the result type with DestType. 18711 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18712 if (Proto) { 18713 // __unknown_anytype(...) is a special case used by the debugger when 18714 // it has no idea what a function's signature is. 18715 // 18716 // We want to build this call essentially under the K&R 18717 // unprototyped rules, but making a FunctionNoProtoType in C++ 18718 // would foul up all sorts of assumptions. However, we cannot 18719 // simply pass all arguments as variadic arguments, nor can we 18720 // portably just call the function under a non-variadic type; see 18721 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18722 // However, it turns out that in practice it is generally safe to 18723 // call a function declared as "A foo(B,C,D);" under the prototype 18724 // "A foo(B,C,D,...);". The only known exception is with the 18725 // Windows ABI, where any variadic function is implicitly cdecl 18726 // regardless of its normal CC. Therefore we change the parameter 18727 // types to match the types of the arguments. 18728 // 18729 // This is a hack, but it is far superior to moving the 18730 // corresponding target-specific code from IR-gen to Sema/AST. 18731 18732 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18733 SmallVector<QualType, 8> ArgTypes; 18734 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18735 ArgTypes.reserve(E->getNumArgs()); 18736 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18737 Expr *Arg = E->getArg(i); 18738 QualType ArgType = Arg->getType(); 18739 if (E->isLValue()) { 18740 ArgType = S.Context.getLValueReferenceType(ArgType); 18741 } else if (E->isXValue()) { 18742 ArgType = S.Context.getRValueReferenceType(ArgType); 18743 } 18744 ArgTypes.push_back(ArgType); 18745 } 18746 ParamTypes = ArgTypes; 18747 } 18748 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18749 Proto->getExtProtoInfo()); 18750 } else { 18751 DestType = S.Context.getFunctionNoProtoType(DestType, 18752 FnType->getExtInfo()); 18753 } 18754 18755 // Rebuild the appropriate pointer-to-function type. 18756 switch (Kind) { 18757 case FK_MemberFunction: 18758 // Nothing to do. 18759 break; 18760 18761 case FK_FunctionPointer: 18762 DestType = S.Context.getPointerType(DestType); 18763 break; 18764 18765 case FK_BlockPointer: 18766 DestType = S.Context.getBlockPointerType(DestType); 18767 break; 18768 } 18769 18770 // Finally, we can recurse. 18771 ExprResult CalleeResult = Visit(CalleeExpr); 18772 if (!CalleeResult.isUsable()) return ExprError(); 18773 E->setCallee(CalleeResult.get()); 18774 18775 // Bind a temporary if necessary. 18776 return S.MaybeBindToTemporary(E); 18777 } 18778 18779 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18780 // Verify that this is a legal result type of a call. 18781 if (DestType->isArrayType() || DestType->isFunctionType()) { 18782 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18783 << DestType->isFunctionType() << DestType; 18784 return ExprError(); 18785 } 18786 18787 // Rewrite the method result type if available. 18788 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18789 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18790 Method->setReturnType(DestType); 18791 } 18792 18793 // Change the type of the message. 18794 E->setType(DestType.getNonReferenceType()); 18795 E->setValueKind(Expr::getValueKindForType(DestType)); 18796 18797 return S.MaybeBindToTemporary(E); 18798 } 18799 18800 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18801 // The only case we should ever see here is a function-to-pointer decay. 18802 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18803 assert(E->getValueKind() == VK_RValue); 18804 assert(E->getObjectKind() == OK_Ordinary); 18805 18806 E->setType(DestType); 18807 18808 // Rebuild the sub-expression as the pointee (function) type. 18809 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18810 18811 ExprResult Result = Visit(E->getSubExpr()); 18812 if (!Result.isUsable()) return ExprError(); 18813 18814 E->setSubExpr(Result.get()); 18815 return E; 18816 } else if (E->getCastKind() == CK_LValueToRValue) { 18817 assert(E->getValueKind() == VK_RValue); 18818 assert(E->getObjectKind() == OK_Ordinary); 18819 18820 assert(isa<BlockPointerType>(E->getType())); 18821 18822 E->setType(DestType); 18823 18824 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18825 DestType = S.Context.getLValueReferenceType(DestType); 18826 18827 ExprResult Result = Visit(E->getSubExpr()); 18828 if (!Result.isUsable()) return ExprError(); 18829 18830 E->setSubExpr(Result.get()); 18831 return E; 18832 } else { 18833 llvm_unreachable("Unhandled cast type!"); 18834 } 18835 } 18836 18837 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18838 ExprValueKind ValueKind = VK_LValue; 18839 QualType Type = DestType; 18840 18841 // We know how to make this work for certain kinds of decls: 18842 18843 // - functions 18844 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18845 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18846 DestType = Ptr->getPointeeType(); 18847 ExprResult Result = resolveDecl(E, VD); 18848 if (Result.isInvalid()) return ExprError(); 18849 return S.ImpCastExprToType(Result.get(), Type, 18850 CK_FunctionToPointerDecay, VK_RValue); 18851 } 18852 18853 if (!Type->isFunctionType()) { 18854 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18855 << VD << E->getSourceRange(); 18856 return ExprError(); 18857 } 18858 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18859 // We must match the FunctionDecl's type to the hack introduced in 18860 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18861 // type. See the lengthy commentary in that routine. 18862 QualType FDT = FD->getType(); 18863 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18864 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18865 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18866 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18867 SourceLocation Loc = FD->getLocation(); 18868 FunctionDecl *NewFD = FunctionDecl::Create( 18869 S.Context, FD->getDeclContext(), Loc, Loc, 18870 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18871 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18872 /*ConstexprKind*/ CSK_unspecified); 18873 18874 if (FD->getQualifier()) 18875 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18876 18877 SmallVector<ParmVarDecl*, 16> Params; 18878 for (const auto &AI : FT->param_types()) { 18879 ParmVarDecl *Param = 18880 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18881 Param->setScopeInfo(0, Params.size()); 18882 Params.push_back(Param); 18883 } 18884 NewFD->setParams(Params); 18885 DRE->setDecl(NewFD); 18886 VD = DRE->getDecl(); 18887 } 18888 } 18889 18890 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18891 if (MD->isInstance()) { 18892 ValueKind = VK_RValue; 18893 Type = S.Context.BoundMemberTy; 18894 } 18895 18896 // Function references aren't l-values in C. 18897 if (!S.getLangOpts().CPlusPlus) 18898 ValueKind = VK_RValue; 18899 18900 // - variables 18901 } else if (isa<VarDecl>(VD)) { 18902 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18903 Type = RefTy->getPointeeType(); 18904 } else if (Type->isFunctionType()) { 18905 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18906 << VD << E->getSourceRange(); 18907 return ExprError(); 18908 } 18909 18910 // - nothing else 18911 } else { 18912 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18913 << VD << E->getSourceRange(); 18914 return ExprError(); 18915 } 18916 18917 // Modifying the declaration like this is friendly to IR-gen but 18918 // also really dangerous. 18919 VD->setType(DestType); 18920 E->setType(Type); 18921 E->setValueKind(ValueKind); 18922 return E; 18923 } 18924 18925 /// Check a cast of an unknown-any type. We intentionally only 18926 /// trigger this for C-style casts. 18927 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18928 Expr *CastExpr, CastKind &CastKind, 18929 ExprValueKind &VK, CXXCastPath &Path) { 18930 // The type we're casting to must be either void or complete. 18931 if (!CastType->isVoidType() && 18932 RequireCompleteType(TypeRange.getBegin(), CastType, 18933 diag::err_typecheck_cast_to_incomplete)) 18934 return ExprError(); 18935 18936 // Rewrite the casted expression from scratch. 18937 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18938 if (!result.isUsable()) return ExprError(); 18939 18940 CastExpr = result.get(); 18941 VK = CastExpr->getValueKind(); 18942 CastKind = CK_NoOp; 18943 18944 return CastExpr; 18945 } 18946 18947 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18948 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18949 } 18950 18951 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18952 Expr *arg, QualType ¶mType) { 18953 // If the syntactic form of the argument is not an explicit cast of 18954 // any sort, just do default argument promotion. 18955 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18956 if (!castArg) { 18957 ExprResult result = DefaultArgumentPromotion(arg); 18958 if (result.isInvalid()) return ExprError(); 18959 paramType = result.get()->getType(); 18960 return result; 18961 } 18962 18963 // Otherwise, use the type that was written in the explicit cast. 18964 assert(!arg->hasPlaceholderType()); 18965 paramType = castArg->getTypeAsWritten(); 18966 18967 // Copy-initialize a parameter of that type. 18968 InitializedEntity entity = 18969 InitializedEntity::InitializeParameter(Context, paramType, 18970 /*consumed*/ false); 18971 return PerformCopyInitialization(entity, callLoc, arg); 18972 } 18973 18974 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18975 Expr *orig = E; 18976 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18977 while (true) { 18978 E = E->IgnoreParenImpCasts(); 18979 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18980 E = call->getCallee(); 18981 diagID = diag::err_uncasted_call_of_unknown_any; 18982 } else { 18983 break; 18984 } 18985 } 18986 18987 SourceLocation loc; 18988 NamedDecl *d; 18989 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18990 loc = ref->getLocation(); 18991 d = ref->getDecl(); 18992 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18993 loc = mem->getMemberLoc(); 18994 d = mem->getMemberDecl(); 18995 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18996 diagID = diag::err_uncasted_call_of_unknown_any; 18997 loc = msg->getSelectorStartLoc(); 18998 d = msg->getMethodDecl(); 18999 if (!d) { 19000 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19001 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19002 << orig->getSourceRange(); 19003 return ExprError(); 19004 } 19005 } else { 19006 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19007 << E->getSourceRange(); 19008 return ExprError(); 19009 } 19010 19011 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19012 19013 // Never recoverable. 19014 return ExprError(); 19015 } 19016 19017 /// Check for operands with placeholder types and complain if found. 19018 /// Returns ExprError() if there was an error and no recovery was possible. 19019 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19020 if (!getLangOpts().CPlusPlus) { 19021 // C cannot handle TypoExpr nodes on either side of a binop because it 19022 // doesn't handle dependent types properly, so make sure any TypoExprs have 19023 // been dealt with before checking the operands. 19024 ExprResult Result = CorrectDelayedTyposInExpr(E); 19025 if (!Result.isUsable()) return ExprError(); 19026 E = Result.get(); 19027 } 19028 19029 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19030 if (!placeholderType) return E; 19031 19032 switch (placeholderType->getKind()) { 19033 19034 // Overloaded expressions. 19035 case BuiltinType::Overload: { 19036 // Try to resolve a single function template specialization. 19037 // This is obligatory. 19038 ExprResult Result = E; 19039 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19040 return Result; 19041 19042 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19043 // leaves Result unchanged on failure. 19044 Result = E; 19045 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19046 return Result; 19047 19048 // If that failed, try to recover with a call. 19049 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19050 /*complain*/ true); 19051 return Result; 19052 } 19053 19054 // Bound member functions. 19055 case BuiltinType::BoundMember: { 19056 ExprResult result = E; 19057 const Expr *BME = E->IgnoreParens(); 19058 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19059 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19060 if (isa<CXXPseudoDestructorExpr>(BME)) { 19061 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19062 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19063 if (ME->getMemberNameInfo().getName().getNameKind() == 19064 DeclarationName::CXXDestructorName) 19065 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19066 } 19067 tryToRecoverWithCall(result, PD, 19068 /*complain*/ true); 19069 return result; 19070 } 19071 19072 // ARC unbridged casts. 19073 case BuiltinType::ARCUnbridgedCast: { 19074 Expr *realCast = stripARCUnbridgedCast(E); 19075 diagnoseARCUnbridgedCast(realCast); 19076 return realCast; 19077 } 19078 19079 // Expressions of unknown type. 19080 case BuiltinType::UnknownAny: 19081 return diagnoseUnknownAnyExpr(*this, E); 19082 19083 // Pseudo-objects. 19084 case BuiltinType::PseudoObject: 19085 return checkPseudoObjectRValue(E); 19086 19087 case BuiltinType::BuiltinFn: { 19088 // Accept __noop without parens by implicitly converting it to a call expr. 19089 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19090 if (DRE) { 19091 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19092 if (FD->getBuiltinID() == Builtin::BI__noop) { 19093 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19094 CK_BuiltinFnToFnPtr) 19095 .get(); 19096 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19097 VK_RValue, SourceLocation(), 19098 FPOptionsOverride()); 19099 } 19100 } 19101 19102 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19103 return ExprError(); 19104 } 19105 19106 case BuiltinType::IncompleteMatrixIdx: 19107 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19108 ->getRowIdx() 19109 ->getBeginLoc(), 19110 diag::err_matrix_incomplete_index); 19111 return ExprError(); 19112 19113 // Expressions of unknown type. 19114 case BuiltinType::OMPArraySection: 19115 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19116 return ExprError(); 19117 19118 // Expressions of unknown type. 19119 case BuiltinType::OMPArrayShaping: 19120 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19121 19122 case BuiltinType::OMPIterator: 19123 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19124 19125 // Everything else should be impossible. 19126 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19127 case BuiltinType::Id: 19128 #include "clang/Basic/OpenCLImageTypes.def" 19129 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19130 case BuiltinType::Id: 19131 #include "clang/Basic/OpenCLExtensionTypes.def" 19132 #define SVE_TYPE(Name, Id, SingletonId) \ 19133 case BuiltinType::Id: 19134 #include "clang/Basic/AArch64SVEACLETypes.def" 19135 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19136 #define PLACEHOLDER_TYPE(Id, SingletonId) 19137 #include "clang/AST/BuiltinTypes.def" 19138 break; 19139 } 19140 19141 llvm_unreachable("invalid placeholder type!"); 19142 } 19143 19144 bool Sema::CheckCaseExpression(Expr *E) { 19145 if (E->isTypeDependent()) 19146 return true; 19147 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19148 return E->getType()->isIntegralOrEnumerationType(); 19149 return false; 19150 } 19151 19152 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19153 ExprResult 19154 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19155 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19156 "Unknown Objective-C Boolean value!"); 19157 QualType BoolT = Context.ObjCBuiltinBoolTy; 19158 if (!Context.getBOOLDecl()) { 19159 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19160 Sema::LookupOrdinaryName); 19161 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19162 NamedDecl *ND = Result.getFoundDecl(); 19163 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19164 Context.setBOOLDecl(TD); 19165 } 19166 } 19167 if (Context.getBOOLDecl()) 19168 BoolT = Context.getBOOLType(); 19169 return new (Context) 19170 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19171 } 19172 19173 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19174 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19175 SourceLocation RParen) { 19176 19177 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19178 19179 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19180 return Spec.getPlatform() == Platform; 19181 }); 19182 19183 VersionTuple Version; 19184 if (Spec != AvailSpecs.end()) 19185 Version = Spec->getVersion(); 19186 19187 // The use of `@available` in the enclosing function should be analyzed to 19188 // warn when it's used inappropriately (i.e. not if(@available)). 19189 if (getCurFunctionOrMethodDecl()) 19190 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19191 else if (getCurBlock() || getCurLambda()) 19192 getCurFunction()->HasPotentialAvailabilityViolations = true; 19193 19194 return new (Context) 19195 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19196 } 19197 19198 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19199 ArrayRef<Expr *> SubExprs, QualType T) { 19200 if (!Context.getLangOpts().RecoveryAST) 19201 return ExprError(); 19202 19203 if (isSFINAEContext()) 19204 return ExprError(); 19205 19206 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19207 // We don't know the concrete type, fallback to dependent type. 19208 T = Context.DependentTy; 19209 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19210 } 19211