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->getDeclName(); 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 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 343 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 344 isa<VarDecl>(D)) { 345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 346 << DMD->getVarName().getAsString(); 347 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 348 return true; 349 } 350 351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 352 AvoidPartialAvailabilityChecks, ClassReceiver); 353 354 DiagnoseUnusedOfDecl(*this, D, Loc); 355 356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 357 358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 359 if (const auto *VD = dyn_cast<ValueDecl>(D)) 360 checkDeviceDecl(VD, Loc); 361 362 if (!Context.getTargetInfo().isTLSSupported()) 363 if (const auto *VD = dyn_cast<VarDecl>(D)) 364 if (VD->getTLSKind() != VarDecl::TLS_None) 365 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 366 } 367 368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 369 !isUnevaluatedContext()) { 370 // C++ [expr.prim.req.nested] p3 371 // A local parameter shall only appear as an unevaluated operand 372 // (Clause 8) within the constraint-expression. 373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 374 << D; 375 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 376 return true; 377 } 378 379 return false; 380 } 381 382 /// DiagnoseSentinelCalls - This routine checks whether a call or 383 /// message-send is to a declaration with the sentinel attribute, and 384 /// if so, it checks that the requirements of the sentinel are 385 /// satisfied. 386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 387 ArrayRef<Expr *> Args) { 388 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 389 if (!attr) 390 return; 391 392 // The number of formal parameters of the declaration. 393 unsigned numFormalParams; 394 395 // The kind of declaration. This is also an index into a %select in 396 // the diagnostic. 397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 398 399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 400 numFormalParams = MD->param_size(); 401 calleeType = CT_Method; 402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 403 numFormalParams = FD->param_size(); 404 calleeType = CT_Function; 405 } else if (isa<VarDecl>(D)) { 406 QualType type = cast<ValueDecl>(D)->getType(); 407 const FunctionType *fn = nullptr; 408 if (const PointerType *ptr = type->getAs<PointerType>()) { 409 fn = ptr->getPointeeType()->getAs<FunctionType>(); 410 if (!fn) return; 411 calleeType = CT_Function; 412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 413 fn = ptr->getPointeeType()->castAs<FunctionType>(); 414 calleeType = CT_Block; 415 } else { 416 return; 417 } 418 419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 420 numFormalParams = proto->getNumParams(); 421 } else { 422 numFormalParams = 0; 423 } 424 } else { 425 return; 426 } 427 428 // "nullPos" is the number of formal parameters at the end which 429 // effectively count as part of the variadic arguments. This is 430 // useful if you would prefer to not have *any* formal parameters, 431 // but the language forces you to have at least one. 432 unsigned nullPos = attr->getNullPos(); 433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 435 436 // The number of arguments which should follow the sentinel. 437 unsigned numArgsAfterSentinel = attr->getSentinel(); 438 439 // If there aren't enough arguments for all the formal parameters, 440 // the sentinel, and the args after the sentinel, complain. 441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 444 return; 445 } 446 447 // Otherwise, find the sentinel expression. 448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 449 if (!sentinelExpr) return; 450 if (sentinelExpr->isValueDependent()) return; 451 if (Context.isSentinelNullExpr(sentinelExpr)) return; 452 453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 454 // or 'NULL' if those are actually defined in the context. Only use 455 // 'nil' for ObjC methods, where it's much more likely that the 456 // variadic arguments form a list of object pointers. 457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 458 std::string NullValue; 459 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 460 NullValue = "nil"; 461 else if (getLangOpts().CPlusPlus11) 462 NullValue = "nullptr"; 463 else if (PP.isMacroDefined("NULL")) 464 NullValue = "NULL"; 465 else 466 NullValue = "(void*) 0"; 467 468 if (MissingNilLoc.isInvalid()) 469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 470 else 471 Diag(MissingNilLoc, diag::warn_missing_sentinel) 472 << int(calleeType) 473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 475 } 476 477 SourceRange Sema::getExprRange(Expr *E) const { 478 return E ? E->getSourceRange() : SourceRange(); 479 } 480 481 //===----------------------------------------------------------------------===// 482 // Standard Promotions and Conversions 483 //===----------------------------------------------------------------------===// 484 485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 487 // Handle any placeholder expressions which made it here. 488 if (E->getType()->isPlaceholderType()) { 489 ExprResult result = CheckPlaceholderExpr(E); 490 if (result.isInvalid()) return ExprError(); 491 E = result.get(); 492 } 493 494 QualType Ty = E->getType(); 495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 496 497 if (Ty->isFunctionType()) { 498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 501 return ExprError(); 502 503 E = ImpCastExprToType(E, Context.getPointerType(Ty), 504 CK_FunctionToPointerDecay).get(); 505 } else if (Ty->isArrayType()) { 506 // In C90 mode, arrays only promote to pointers if the array expression is 507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 508 // type 'array of type' is converted to an expression that has type 'pointer 509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 510 // that has type 'array of type' ...". The relevant change is "an lvalue" 511 // (C90) to "an expression" (C99). 512 // 513 // C++ 4.2p1: 514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 515 // T" can be converted to an rvalue of type "pointer to T". 516 // 517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 519 CK_ArrayToPointerDecay).get(); 520 } 521 return E; 522 } 523 524 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 525 // Check to see if we are dereferencing a null pointer. If so, 526 // and if not volatile-qualified, this is undefined behavior that the 527 // optimizer will delete, so warn about it. People sometimes try to use this 528 // to get a deterministic trap and are surprised by clang's behavior. This 529 // only handles the pattern "*null", which is a very syntactic check. 530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 531 if (UO && UO->getOpcode() == UO_Deref && 532 UO->getSubExpr()->getType()->isPointerType()) { 533 const LangAS AS = 534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 535 if ((!isTargetAddressSpace(AS) || 536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 538 S.Context, Expr::NPC_ValueDependentIsNotNull) && 539 !UO->getType().isVolatileQualified()) { 540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 541 S.PDiag(diag::warn_indirection_through_null) 542 << UO->getSubExpr()->getSourceRange()); 543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 544 S.PDiag(diag::note_indirection_through_null)); 545 } 546 } 547 } 548 549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 550 SourceLocation AssignLoc, 551 const Expr* RHS) { 552 const ObjCIvarDecl *IV = OIRE->getDecl(); 553 if (!IV) 554 return; 555 556 DeclarationName MemberName = IV->getDeclName(); 557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 558 if (!Member || !Member->isStr("isa")) 559 return; 560 561 const Expr *Base = OIRE->getBase(); 562 QualType BaseType = Base->getType(); 563 if (OIRE->isArrow()) 564 BaseType = BaseType->getPointeeType(); 565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 567 ObjCInterfaceDecl *ClassDeclared = nullptr; 568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 569 if (!ClassDeclared->getSuperClass() 570 && (*ClassDeclared->ivar_begin()) == IV) { 571 if (RHS) { 572 NamedDecl *ObjectSetClass = 573 S.LookupSingleName(S.TUScope, 574 &S.Context.Idents.get("object_setClass"), 575 SourceLocation(), S.LookupOrdinaryName); 576 if (ObjectSetClass) { 577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 580 "object_setClass(") 581 << FixItHint::CreateReplacement( 582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 583 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 584 } 585 else 586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 587 } else { 588 NamedDecl *ObjectGetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_getClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectGetClass) 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_getClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 598 else 599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 600 } 601 S.Diag(IV->getLocation(), diag::note_ivar_decl); 602 } 603 } 604 } 605 606 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 607 // Handle any placeholder expressions which made it here. 608 if (E->getType()->isPlaceholderType()) { 609 ExprResult result = CheckPlaceholderExpr(E); 610 if (result.isInvalid()) return ExprError(); 611 E = result.get(); 612 } 613 614 // C++ [conv.lval]p1: 615 // A glvalue of a non-function, non-array type T can be 616 // converted to a prvalue. 617 if (!E->isGLValue()) return E; 618 619 QualType T = E->getType(); 620 assert(!T.isNull() && "r-value conversion on typeless expression?"); 621 622 // lvalue-to-rvalue conversion cannot be applied to function or array types. 623 if (T->isFunctionType() || T->isArrayType()) 624 return E; 625 626 // We don't want to throw lvalue-to-rvalue casts on top of 627 // expressions of certain types in C++. 628 if (getLangOpts().CPlusPlus && 629 (E->getType() == Context.OverloadTy || 630 T->isDependentType() || 631 T->isRecordType())) 632 return E; 633 634 // The C standard is actually really unclear on this point, and 635 // DR106 tells us what the result should be but not why. It's 636 // generally best to say that void types just doesn't undergo 637 // lvalue-to-rvalue at all. Note that expressions of unqualified 638 // 'void' type are never l-values, but qualified void can be. 639 if (T->isVoidType()) 640 return E; 641 642 // OpenCL usually rejects direct accesses to values of 'half' type. 643 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 644 T->isHalfType()) { 645 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 646 << 0 << T; 647 return ExprError(); 648 } 649 650 CheckForNullPointerDereference(*this, E); 651 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 652 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 653 &Context.Idents.get("object_getClass"), 654 SourceLocation(), LookupOrdinaryName); 655 if (ObjectGetClass) 656 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 657 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 658 << FixItHint::CreateReplacement( 659 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 660 else 661 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 662 } 663 else if (const ObjCIvarRefExpr *OIRE = 664 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 665 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 666 667 // C++ [conv.lval]p1: 668 // [...] If T is a non-class type, the type of the prvalue is the 669 // cv-unqualified version of T. Otherwise, the type of the 670 // rvalue is T. 671 // 672 // C99 6.3.2.1p2: 673 // If the lvalue has qualified type, the value has the unqualified 674 // version of the type of the lvalue; otherwise, the value has the 675 // type of the lvalue. 676 if (T.hasQualifiers()) 677 T = T.getUnqualifiedType(); 678 679 // Under the MS ABI, lock down the inheritance model now. 680 if (T->isMemberPointerType() && 681 Context.getTargetInfo().getCXXABI().isMicrosoft()) 682 (void)isCompleteType(E->getExprLoc(), T); 683 684 ExprResult Res = CheckLValueToRValueConversionOperand(E); 685 if (Res.isInvalid()) 686 return Res; 687 E = Res.get(); 688 689 // Loading a __weak object implicitly retains the value, so we need a cleanup to 690 // balance that. 691 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 692 Cleanup.setExprNeedsCleanups(true); 693 694 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 695 Cleanup.setExprNeedsCleanups(true); 696 697 // C++ [conv.lval]p3: 698 // If T is cv std::nullptr_t, the result is a null pointer constant. 699 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 700 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 701 702 // C11 6.3.2.1p2: 703 // ... if the lvalue has atomic type, the value has the non-atomic version 704 // of the type of the lvalue ... 705 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 706 T = Atomic->getValueType().getUnqualifiedType(); 707 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 708 nullptr, VK_RValue); 709 } 710 711 return Res; 712 } 713 714 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 715 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 716 if (Res.isInvalid()) 717 return ExprError(); 718 Res = DefaultLvalueConversion(Res.get()); 719 if (Res.isInvalid()) 720 return ExprError(); 721 return Res; 722 } 723 724 /// CallExprUnaryConversions - a special case of an unary conversion 725 /// performed on a function designator of a call expression. 726 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 727 QualType Ty = E->getType(); 728 ExprResult Res = E; 729 // Only do implicit cast for a function type, but not for a pointer 730 // to function type. 731 if (Ty->isFunctionType()) { 732 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 733 CK_FunctionToPointerDecay); 734 if (Res.isInvalid()) 735 return ExprError(); 736 } 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res.get(); 741 } 742 743 /// UsualUnaryConversions - Performs various conversions that are common to most 744 /// operators (C99 6.3). The conversions of array and function types are 745 /// sometimes suppressed. For example, the array->pointer conversion doesn't 746 /// apply if the array is an argument to the sizeof or address (&) operators. 747 /// In these instances, this routine should *not* be called. 748 ExprResult Sema::UsualUnaryConversions(Expr *E) { 749 // First, convert to an r-value. 750 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 751 if (Res.isInvalid()) 752 return ExprError(); 753 E = Res.get(); 754 755 QualType Ty = E->getType(); 756 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 757 758 // Half FP have to be promoted to float unless it is natively supported 759 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 760 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 761 762 // Try to perform integral promotions if the object has a theoretically 763 // promotable type. 764 if (Ty->isIntegralOrUnscopedEnumerationType()) { 765 // C99 6.3.1.1p2: 766 // 767 // The following may be used in an expression wherever an int or 768 // unsigned int may be used: 769 // - an object or expression with an integer type whose integer 770 // conversion rank is less than or equal to the rank of int 771 // and unsigned int. 772 // - A bit-field of type _Bool, int, signed int, or unsigned int. 773 // 774 // If an int can represent all values of the original type, the 775 // value is converted to an int; otherwise, it is converted to an 776 // unsigned int. These are called the integer promotions. All 777 // other types are unchanged by the integer promotions. 778 779 QualType PTy = Context.isPromotableBitField(E); 780 if (!PTy.isNull()) { 781 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 782 return E; 783 } 784 if (Ty->isPromotableIntegerType()) { 785 QualType PT = Context.getPromotedIntegerType(Ty); 786 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 787 return E; 788 } 789 } 790 return E; 791 } 792 793 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 794 /// do not have a prototype. Arguments that have type float or __fp16 795 /// are promoted to double. All other argument types are converted by 796 /// UsualUnaryConversions(). 797 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 798 QualType Ty = E->getType(); 799 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 800 801 ExprResult Res = UsualUnaryConversions(E); 802 if (Res.isInvalid()) 803 return ExprError(); 804 E = Res.get(); 805 806 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 807 // promote to double. 808 // Note that default argument promotion applies only to float (and 809 // half/fp16); it does not apply to _Float16. 810 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 811 if (BTy && (BTy->getKind() == BuiltinType::Half || 812 BTy->getKind() == BuiltinType::Float)) { 813 if (getLangOpts().OpenCL && 814 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 815 if (BTy->getKind() == BuiltinType::Half) { 816 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 817 } 818 } else { 819 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 820 } 821 } 822 823 // C++ performs lvalue-to-rvalue conversion as a default argument 824 // promotion, even on class types, but note: 825 // C++11 [conv.lval]p2: 826 // When an lvalue-to-rvalue conversion occurs in an unevaluated 827 // operand or a subexpression thereof the value contained in the 828 // referenced object is not accessed. Otherwise, if the glvalue 829 // has a class type, the conversion copy-initializes a temporary 830 // of type T from the glvalue and the result of the conversion 831 // is a prvalue for the temporary. 832 // FIXME: add some way to gate this entire thing for correctness in 833 // potentially potentially evaluated contexts. 834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 835 ExprResult Temp = PerformCopyInitialization( 836 InitializedEntity::InitializeTemporary(E->getType()), 837 E->getExprLoc(), E); 838 if (Temp.isInvalid()) 839 return ExprError(); 840 E = Temp.get(); 841 } 842 843 return E; 844 } 845 846 /// Determine the degree of POD-ness for an expression. 847 /// Incomplete types are considered POD, since this check can be performed 848 /// when we're in an unevaluated context. 849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 850 if (Ty->isIncompleteType()) { 851 // C++11 [expr.call]p7: 852 // After these conversions, if the argument does not have arithmetic, 853 // enumeration, pointer, pointer to member, or class type, the program 854 // is ill-formed. 855 // 856 // Since we've already performed array-to-pointer and function-to-pointer 857 // decay, the only such type in C++ is cv void. This also handles 858 // initializer lists as variadic arguments. 859 if (Ty->isVoidType()) 860 return VAK_Invalid; 861 862 if (Ty->isObjCObjectType()) 863 return VAK_Invalid; 864 return VAK_Valid; 865 } 866 867 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 868 return VAK_Invalid; 869 870 if (Ty.isCXX98PODType(Context)) 871 return VAK_Valid; 872 873 // C++11 [expr.call]p7: 874 // Passing a potentially-evaluated argument of class type (Clause 9) 875 // having a non-trivial copy constructor, a non-trivial move constructor, 876 // or a non-trivial destructor, with no corresponding parameter, 877 // is conditionally-supported with implementation-defined semantics. 878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 880 if (!Record->hasNonTrivialCopyConstructor() && 881 !Record->hasNonTrivialMoveConstructor() && 882 !Record->hasNonTrivialDestructor()) 883 return VAK_ValidInCXX11; 884 885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 886 return VAK_Valid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 891 if (getLangOpts().MSVCCompat) 892 return VAK_MSVCUndefined; 893 894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 895 // permitted to reject them. We should consider doing so. 896 return VAK_Undefined; 897 } 898 899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 900 // Don't allow one to pass an Objective-C interface to a vararg. 901 const QualType &Ty = E->getType(); 902 VarArgKind VAK = isValidVarArgType(Ty); 903 904 // Complain about passing non-POD types through varargs. 905 switch (VAK) { 906 case VAK_ValidInCXX11: 907 DiagRuntimeBehavior( 908 E->getBeginLoc(), nullptr, 909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 910 LLVM_FALLTHROUGH; 911 case VAK_Valid: 912 if (Ty->isRecordType()) { 913 // This is unlikely to be what the user intended. If the class has a 914 // 'c_str' member function, the user probably meant to call that. 915 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 916 PDiag(diag::warn_pass_class_arg_to_vararg) 917 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 918 } 919 break; 920 921 case VAK_Undefined: 922 case VAK_MSVCUndefined: 923 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 924 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 925 << getLangOpts().CPlusPlus11 << Ty << CT); 926 break; 927 928 case VAK_Invalid: 929 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 930 Diag(E->getBeginLoc(), 931 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 932 << Ty << CT; 933 else if (Ty->isObjCObjectType()) 934 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 935 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 936 << Ty << CT); 937 else 938 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 939 << isa<InitListExpr>(E) << Ty << CT; 940 break; 941 } 942 } 943 944 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 945 /// will create a trap if the resulting type is not a POD type. 946 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 947 FunctionDecl *FDecl) { 948 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 949 // Strip the unbridged-cast placeholder expression off, if applicable. 950 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 951 (CT == VariadicMethod || 952 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 953 E = stripARCUnbridgedCast(E); 954 955 // Otherwise, do normal placeholder checking. 956 } else { 957 ExprResult ExprRes = CheckPlaceholderExpr(E); 958 if (ExprRes.isInvalid()) 959 return ExprError(); 960 E = ExprRes.get(); 961 } 962 } 963 964 ExprResult ExprRes = DefaultArgumentPromotion(E); 965 if (ExprRes.isInvalid()) 966 return ExprError(); 967 968 // Copy blocks to the heap. 969 if (ExprRes.get()->getType()->isBlockPointerType()) 970 maybeExtendBlockObject(ExprRes); 971 972 E = ExprRes.get(); 973 974 // Diagnostics regarding non-POD argument types are 975 // emitted along with format string checking in Sema::CheckFunctionCall(). 976 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 977 // Turn this into a trap. 978 CXXScopeSpec SS; 979 SourceLocation TemplateKWLoc; 980 UnqualifiedId Name; 981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 982 E->getBeginLoc()); 983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 984 /*HasTrailingLParen=*/true, 985 /*IsAddressOfOperand=*/false); 986 if (TrapFn.isInvalid()) 987 return ExprError(); 988 989 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 990 None, E->getEndLoc()); 991 if (Call.isInvalid()) 992 return ExprError(); 993 994 ExprResult Comma = 995 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 996 if (Comma.isInvalid()) 997 return ExprError(); 998 return Comma.get(); 999 } 1000 1001 if (!getLangOpts().CPlusPlus && 1002 RequireCompleteType(E->getExprLoc(), E->getType(), 1003 diag::err_call_incomplete_argument)) 1004 return ExprError(); 1005 1006 return E; 1007 } 1008 1009 /// Converts an integer to complex float type. Helper function of 1010 /// UsualArithmeticConversions() 1011 /// 1012 /// \return false if the integer expression is an integer type and is 1013 /// successfully converted to the complex type. 1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1015 ExprResult &ComplexExpr, 1016 QualType IntTy, 1017 QualType ComplexTy, 1018 bool SkipCast) { 1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1020 if (SkipCast) return false; 1021 if (IntTy->isIntegerType()) { 1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1025 CK_FloatingRealToComplex); 1026 } else { 1027 assert(IntTy->isComplexIntegerType()); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1029 CK_IntegralComplexToFloatingComplex); 1030 } 1031 return false; 1032 } 1033 1034 /// Handle arithmetic conversion with complex types. Helper function of 1035 /// UsualArithmeticConversions() 1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1037 ExprResult &RHS, QualType LHSType, 1038 QualType RHSType, 1039 bool IsCompAssign) { 1040 // if we have an integer operand, the result is the complex type. 1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1042 /*skipCast*/false)) 1043 return LHSType; 1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1045 /*skipCast*/IsCompAssign)) 1046 return RHSType; 1047 1048 // This handles complex/complex, complex/float, or float/complex. 1049 // When both operands are complex, the shorter operand is converted to the 1050 // type of the longer, and that is the type of the result. This corresponds 1051 // to what is done when combining two real floating-point operands. 1052 // The fun begins when size promotion occur across type domains. 1053 // From H&S 6.3.4: When one operand is complex and the other is a real 1054 // floating-point type, the less precise type is converted, within it's 1055 // real or complex domain, to the precision of the other type. For example, 1056 // when combining a "long double" with a "double _Complex", the 1057 // "double _Complex" is promoted to "long double _Complex". 1058 1059 // Compute the rank of the two types, regardless of whether they are complex. 1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1061 1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1064 QualType LHSElementType = 1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1066 QualType RHSElementType = 1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1068 1069 QualType ResultType = S.Context.getComplexType(LHSElementType); 1070 if (Order < 0) { 1071 // Promote the precision of the LHS if not an assignment. 1072 ResultType = S.Context.getComplexType(RHSElementType); 1073 if (!IsCompAssign) { 1074 if (LHSComplexType) 1075 LHS = 1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1077 else 1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1079 } 1080 } else if (Order > 0) { 1081 // Promote the precision of the RHS. 1082 if (RHSComplexType) 1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1084 else 1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1086 } 1087 return ResultType; 1088 } 1089 1090 /// Handle arithmetic conversion from integer to float. Helper function 1091 /// of UsualArithmeticConversions() 1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1093 ExprResult &IntExpr, 1094 QualType FloatTy, QualType IntTy, 1095 bool ConvertFloat, bool ConvertInt) { 1096 if (IntTy->isIntegerType()) { 1097 if (ConvertInt) 1098 // Convert intExpr to the lhs floating point type. 1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1100 CK_IntegralToFloating); 1101 return FloatTy; 1102 } 1103 1104 // Convert both sides to the appropriate complex float. 1105 assert(IntTy->isComplexIntegerType()); 1106 QualType result = S.Context.getComplexType(FloatTy); 1107 1108 // _Complex int -> _Complex float 1109 if (ConvertInt) 1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1111 CK_IntegralComplexToFloatingComplex); 1112 1113 // float -> _Complex float 1114 if (ConvertFloat) 1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1116 CK_FloatingRealToComplex); 1117 1118 return result; 1119 } 1120 1121 /// Handle arithmethic conversion with floating point types. Helper 1122 /// function of UsualArithmeticConversions() 1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1124 ExprResult &RHS, QualType LHSType, 1125 QualType RHSType, bool IsCompAssign) { 1126 bool LHSFloat = LHSType->isRealFloatingType(); 1127 bool RHSFloat = RHSType->isRealFloatingType(); 1128 1129 // If we have two real floating types, convert the smaller operand 1130 // to the bigger result. 1131 if (LHSFloat && RHSFloat) { 1132 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1133 if (order > 0) { 1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1135 return LHSType; 1136 } 1137 1138 assert(order < 0 && "illegal float comparison"); 1139 if (!IsCompAssign) 1140 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1141 return RHSType; 1142 } 1143 1144 if (LHSFloat) { 1145 // Half FP has to be promoted to float unless it is natively supported 1146 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1147 LHSType = S.Context.FloatTy; 1148 1149 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1150 /*ConvertFloat=*/!IsCompAssign, 1151 /*ConvertInt=*/ true); 1152 } 1153 assert(RHSFloat); 1154 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1155 /*convertInt=*/ true, 1156 /*convertFloat=*/!IsCompAssign); 1157 } 1158 1159 /// Diagnose attempts to convert between __float128 and long double if 1160 /// there is no support for such conversion. Helper function of 1161 /// UsualArithmeticConversions(). 1162 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1163 QualType RHSType) { 1164 /* No issue converting if at least one of the types is not a floating point 1165 type or the two types have the same rank. 1166 */ 1167 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1168 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1169 return false; 1170 1171 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1172 "The remaining types must be floating point types."); 1173 1174 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1175 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1176 1177 QualType LHSElemType = LHSComplex ? 1178 LHSComplex->getElementType() : LHSType; 1179 QualType RHSElemType = RHSComplex ? 1180 RHSComplex->getElementType() : RHSType; 1181 1182 // No issue if the two types have the same representation 1183 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1184 &S.Context.getFloatTypeSemantics(RHSElemType)) 1185 return false; 1186 1187 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1188 RHSElemType == S.Context.LongDoubleTy); 1189 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1190 RHSElemType == S.Context.Float128Ty); 1191 1192 // We've handled the situation where __float128 and long double have the same 1193 // representation. We allow all conversions for all possible long double types 1194 // except PPC's double double. 1195 return Float128AndLongDouble && 1196 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1197 &llvm::APFloat::PPCDoubleDouble()); 1198 } 1199 1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1201 1202 namespace { 1203 /// These helper callbacks are placed in an anonymous namespace to 1204 /// permit their use as function template parameters. 1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1206 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1207 } 1208 1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1210 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1211 CK_IntegralComplexCast); 1212 } 1213 } 1214 1215 /// Handle integer arithmetic conversions. Helper function of 1216 /// UsualArithmeticConversions() 1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1219 ExprResult &RHS, QualType LHSType, 1220 QualType RHSType, bool IsCompAssign) { 1221 // The rules for this case are in C99 6.3.1.8 1222 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1223 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1224 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1225 if (LHSSigned == RHSSigned) { 1226 // Same signedness; use the higher-ranked type 1227 if (order >= 0) { 1228 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1229 return LHSType; 1230 } else if (!IsCompAssign) 1231 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1232 return RHSType; 1233 } else if (order != (LHSSigned ? 1 : -1)) { 1234 // The unsigned type has greater than or equal rank to the 1235 // signed type, so use the unsigned type 1236 if (RHSSigned) { 1237 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1238 return LHSType; 1239 } else if (!IsCompAssign) 1240 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1241 return RHSType; 1242 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1243 // The two types are different widths; if we are here, that 1244 // means the signed type is larger than the unsigned type, so 1245 // use the signed type. 1246 if (LHSSigned) { 1247 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1248 return LHSType; 1249 } else if (!IsCompAssign) 1250 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1251 return RHSType; 1252 } else { 1253 // The signed type is higher-ranked than the unsigned type, 1254 // but isn't actually any bigger (like unsigned int and long 1255 // on most 32-bit systems). Use the unsigned type corresponding 1256 // to the signed type. 1257 QualType result = 1258 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1259 RHS = (*doRHSCast)(S, RHS.get(), result); 1260 if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), result); 1262 return result; 1263 } 1264 } 1265 1266 /// Handle conversions with GCC complex int extension. Helper function 1267 /// of UsualArithmeticConversions() 1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1269 ExprResult &RHS, QualType LHSType, 1270 QualType RHSType, 1271 bool IsCompAssign) { 1272 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1273 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1274 1275 if (LHSComplexInt && RHSComplexInt) { 1276 QualType LHSEltType = LHSComplexInt->getElementType(); 1277 QualType RHSEltType = RHSComplexInt->getElementType(); 1278 QualType ScalarType = 1279 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1280 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1281 1282 return S.Context.getComplexType(ScalarType); 1283 } 1284 1285 if (LHSComplexInt) { 1286 QualType LHSEltType = LHSComplexInt->getElementType(); 1287 QualType ScalarType = 1288 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1289 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1290 QualType ComplexType = S.Context.getComplexType(ScalarType); 1291 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1292 CK_IntegralRealToComplex); 1293 1294 return ComplexType; 1295 } 1296 1297 assert(RHSComplexInt); 1298 1299 QualType RHSEltType = RHSComplexInt->getElementType(); 1300 QualType ScalarType = 1301 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1302 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1303 QualType ComplexType = S.Context.getComplexType(ScalarType); 1304 1305 if (!IsCompAssign) 1306 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1307 CK_IntegralRealToComplex); 1308 return ComplexType; 1309 } 1310 1311 /// Return the rank of a given fixed point or integer type. The value itself 1312 /// doesn't matter, but the values must be increasing with proper increasing 1313 /// rank as described in N1169 4.1.1. 1314 static unsigned GetFixedPointRank(QualType Ty) { 1315 const auto *BTy = Ty->getAs<BuiltinType>(); 1316 assert(BTy && "Expected a builtin type."); 1317 1318 switch (BTy->getKind()) { 1319 case BuiltinType::ShortFract: 1320 case BuiltinType::UShortFract: 1321 case BuiltinType::SatShortFract: 1322 case BuiltinType::SatUShortFract: 1323 return 1; 1324 case BuiltinType::Fract: 1325 case BuiltinType::UFract: 1326 case BuiltinType::SatFract: 1327 case BuiltinType::SatUFract: 1328 return 2; 1329 case BuiltinType::LongFract: 1330 case BuiltinType::ULongFract: 1331 case BuiltinType::SatLongFract: 1332 case BuiltinType::SatULongFract: 1333 return 3; 1334 case BuiltinType::ShortAccum: 1335 case BuiltinType::UShortAccum: 1336 case BuiltinType::SatShortAccum: 1337 case BuiltinType::SatUShortAccum: 1338 return 4; 1339 case BuiltinType::Accum: 1340 case BuiltinType::UAccum: 1341 case BuiltinType::SatAccum: 1342 case BuiltinType::SatUAccum: 1343 return 5; 1344 case BuiltinType::LongAccum: 1345 case BuiltinType::ULongAccum: 1346 case BuiltinType::SatLongAccum: 1347 case BuiltinType::SatULongAccum: 1348 return 6; 1349 default: 1350 if (BTy->isInteger()) 1351 return 0; 1352 llvm_unreachable("Unexpected fixed point or integer type"); 1353 } 1354 } 1355 1356 /// handleFixedPointConversion - Fixed point operations between fixed 1357 /// point types and integers or other fixed point types do not fall under 1358 /// usual arithmetic conversion since these conversions could result in loss 1359 /// of precsision (N1169 4.1.4). These operations should be calculated with 1360 /// the full precision of their result type (N1169 4.1.6.2.1). 1361 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1362 QualType RHSTy) { 1363 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1364 "Expected at least one of the operands to be a fixed point type"); 1365 assert((LHSTy->isFixedPointOrIntegerType() || 1366 RHSTy->isFixedPointOrIntegerType()) && 1367 "Special fixed point arithmetic operation conversions are only " 1368 "applied to ints or other fixed point types"); 1369 1370 // If one operand has signed fixed-point type and the other operand has 1371 // unsigned fixed-point type, then the unsigned fixed-point operand is 1372 // converted to its corresponding signed fixed-point type and the resulting 1373 // type is the type of the converted operand. 1374 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1375 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1376 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1377 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1378 1379 // The result type is the type with the highest rank, whereby a fixed-point 1380 // conversion rank is always greater than an integer conversion rank; if the 1381 // type of either of the operands is a saturating fixedpoint type, the result 1382 // type shall be the saturating fixed-point type corresponding to the type 1383 // with the highest rank; the resulting value is converted (taking into 1384 // account rounding and overflow) to the precision of the resulting type. 1385 // Same ranks between signed and unsigned types are resolved earlier, so both 1386 // types are either signed or both unsigned at this point. 1387 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1388 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1389 1390 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1391 1392 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1393 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1394 1395 return ResultTy; 1396 } 1397 1398 /// Check that the usual arithmetic conversions can be performed on this pair of 1399 /// expressions that might be of enumeration type. 1400 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1401 SourceLocation Loc, 1402 Sema::ArithConvKind ACK) { 1403 // C++2a [expr.arith.conv]p1: 1404 // If one operand is of enumeration type and the other operand is of a 1405 // different enumeration type or a floating-point type, this behavior is 1406 // deprecated ([depr.arith.conv.enum]). 1407 // 1408 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1409 // Eventually we will presumably reject these cases (in C++23 onwards?). 1410 QualType L = LHS->getType(), R = RHS->getType(); 1411 bool LEnum = L->isUnscopedEnumerationType(), 1412 REnum = R->isUnscopedEnumerationType(); 1413 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1414 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1415 (REnum && L->isFloatingType())) { 1416 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1417 ? diag::warn_arith_conv_enum_float_cxx20 1418 : diag::warn_arith_conv_enum_float) 1419 << LHS->getSourceRange() << RHS->getSourceRange() 1420 << (int)ACK << LEnum << L << R; 1421 } else if (!IsCompAssign && LEnum && REnum && 1422 !S.Context.hasSameUnqualifiedType(L, R)) { 1423 unsigned DiagID; 1424 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1425 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1426 // If either enumeration type is unnamed, it's less likely that the 1427 // user cares about this, but this situation is still deprecated in 1428 // C++2a. Use a different warning group. 1429 DiagID = S.getLangOpts().CPlusPlus20 1430 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1431 : diag::warn_arith_conv_mixed_anon_enum_types; 1432 } else if (ACK == Sema::ACK_Conditional) { 1433 // Conditional expressions are separated out because they have 1434 // historically had a different warning flag. 1435 DiagID = S.getLangOpts().CPlusPlus20 1436 ? diag::warn_conditional_mixed_enum_types_cxx20 1437 : diag::warn_conditional_mixed_enum_types; 1438 } else if (ACK == Sema::ACK_Comparison) { 1439 // Comparison expressions are separated out because they have 1440 // historically had a different warning flag. 1441 DiagID = S.getLangOpts().CPlusPlus20 1442 ? diag::warn_comparison_mixed_enum_types_cxx20 1443 : diag::warn_comparison_mixed_enum_types; 1444 } else { 1445 DiagID = S.getLangOpts().CPlusPlus20 1446 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1447 : diag::warn_arith_conv_mixed_enum_types; 1448 } 1449 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1450 << (int)ACK << L << R; 1451 } 1452 } 1453 1454 /// UsualArithmeticConversions - Performs various conversions that are common to 1455 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1456 /// routine returns the first non-arithmetic type found. The client is 1457 /// responsible for emitting appropriate error diagnostics. 1458 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1459 SourceLocation Loc, 1460 ArithConvKind ACK) { 1461 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1462 1463 if (ACK != ACK_CompAssign) { 1464 LHS = UsualUnaryConversions(LHS.get()); 1465 if (LHS.isInvalid()) 1466 return QualType(); 1467 } 1468 1469 RHS = UsualUnaryConversions(RHS.get()); 1470 if (RHS.isInvalid()) 1471 return QualType(); 1472 1473 // For conversion purposes, we ignore any qualifiers. 1474 // For example, "const float" and "float" are equivalent. 1475 QualType LHSType = 1476 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1477 QualType RHSType = 1478 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1479 1480 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1481 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1482 LHSType = AtomicLHS->getValueType(); 1483 1484 // If both types are identical, no conversion is needed. 1485 if (LHSType == RHSType) 1486 return LHSType; 1487 1488 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1489 // The caller can deal with this (e.g. pointer + int). 1490 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1491 return QualType(); 1492 1493 // Apply unary and bitfield promotions to the LHS's type. 1494 QualType LHSUnpromotedType = LHSType; 1495 if (LHSType->isPromotableIntegerType()) 1496 LHSType = Context.getPromotedIntegerType(LHSType); 1497 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1498 if (!LHSBitfieldPromoteTy.isNull()) 1499 LHSType = LHSBitfieldPromoteTy; 1500 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1501 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1502 1503 // If both types are identical, no conversion is needed. 1504 if (LHSType == RHSType) 1505 return LHSType; 1506 1507 // ExtInt types aren't subject to conversions between them or normal integers, 1508 // so this fails. 1509 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1510 return QualType(); 1511 1512 // At this point, we have two different arithmetic types. 1513 1514 // Diagnose attempts to convert between __float128 and long double where 1515 // such conversions currently can't be handled. 1516 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1517 return QualType(); 1518 1519 // Handle complex types first (C99 6.3.1.8p1). 1520 if (LHSType->isComplexType() || RHSType->isComplexType()) 1521 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1522 ACK == ACK_CompAssign); 1523 1524 // Now handle "real" floating types (i.e. float, double, long double). 1525 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1526 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1527 ACK == ACK_CompAssign); 1528 1529 // Handle GCC complex int extension. 1530 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1531 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1532 ACK == ACK_CompAssign); 1533 1534 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1535 return handleFixedPointConversion(*this, LHSType, RHSType); 1536 1537 // Finally, we have two differing integer types. 1538 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1539 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1540 } 1541 1542 //===----------------------------------------------------------------------===// 1543 // Semantic Analysis for various Expression Types 1544 //===----------------------------------------------------------------------===// 1545 1546 1547 ExprResult 1548 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1549 SourceLocation DefaultLoc, 1550 SourceLocation RParenLoc, 1551 Expr *ControllingExpr, 1552 ArrayRef<ParsedType> ArgTypes, 1553 ArrayRef<Expr *> ArgExprs) { 1554 unsigned NumAssocs = ArgTypes.size(); 1555 assert(NumAssocs == ArgExprs.size()); 1556 1557 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1558 for (unsigned i = 0; i < NumAssocs; ++i) { 1559 if (ArgTypes[i]) 1560 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1561 else 1562 Types[i] = nullptr; 1563 } 1564 1565 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1566 ControllingExpr, 1567 llvm::makeArrayRef(Types, NumAssocs), 1568 ArgExprs); 1569 delete [] Types; 1570 return ER; 1571 } 1572 1573 ExprResult 1574 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1575 SourceLocation DefaultLoc, 1576 SourceLocation RParenLoc, 1577 Expr *ControllingExpr, 1578 ArrayRef<TypeSourceInfo *> Types, 1579 ArrayRef<Expr *> Exprs) { 1580 unsigned NumAssocs = Types.size(); 1581 assert(NumAssocs == Exprs.size()); 1582 1583 // Decay and strip qualifiers for the controlling expression type, and handle 1584 // placeholder type replacement. See committee discussion from WG14 DR423. 1585 { 1586 EnterExpressionEvaluationContext Unevaluated( 1587 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1588 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1589 if (R.isInvalid()) 1590 return ExprError(); 1591 ControllingExpr = R.get(); 1592 } 1593 1594 // The controlling expression is an unevaluated operand, so side effects are 1595 // likely unintended. 1596 if (!inTemplateInstantiation() && 1597 ControllingExpr->HasSideEffects(Context, false)) 1598 Diag(ControllingExpr->getExprLoc(), 1599 diag::warn_side_effects_unevaluated_context); 1600 1601 bool TypeErrorFound = false, 1602 IsResultDependent = ControllingExpr->isTypeDependent(), 1603 ContainsUnexpandedParameterPack 1604 = ControllingExpr->containsUnexpandedParameterPack(); 1605 1606 for (unsigned i = 0; i < NumAssocs; ++i) { 1607 if (Exprs[i]->containsUnexpandedParameterPack()) 1608 ContainsUnexpandedParameterPack = true; 1609 1610 if (Types[i]) { 1611 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1612 ContainsUnexpandedParameterPack = true; 1613 1614 if (Types[i]->getType()->isDependentType()) { 1615 IsResultDependent = true; 1616 } else { 1617 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1618 // complete object type other than a variably modified type." 1619 unsigned D = 0; 1620 if (Types[i]->getType()->isIncompleteType()) 1621 D = diag::err_assoc_type_incomplete; 1622 else if (!Types[i]->getType()->isObjectType()) 1623 D = diag::err_assoc_type_nonobject; 1624 else if (Types[i]->getType()->isVariablyModifiedType()) 1625 D = diag::err_assoc_type_variably_modified; 1626 1627 if (D != 0) { 1628 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1629 << Types[i]->getTypeLoc().getSourceRange() 1630 << Types[i]->getType(); 1631 TypeErrorFound = true; 1632 } 1633 1634 // C11 6.5.1.1p2 "No two generic associations in the same generic 1635 // selection shall specify compatible types." 1636 for (unsigned j = i+1; j < NumAssocs; ++j) 1637 if (Types[j] && !Types[j]->getType()->isDependentType() && 1638 Context.typesAreCompatible(Types[i]->getType(), 1639 Types[j]->getType())) { 1640 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1641 diag::err_assoc_compatible_types) 1642 << Types[j]->getTypeLoc().getSourceRange() 1643 << Types[j]->getType() 1644 << Types[i]->getType(); 1645 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1646 diag::note_compat_assoc) 1647 << Types[i]->getTypeLoc().getSourceRange() 1648 << Types[i]->getType(); 1649 TypeErrorFound = true; 1650 } 1651 } 1652 } 1653 } 1654 if (TypeErrorFound) 1655 return ExprError(); 1656 1657 // If we determined that the generic selection is result-dependent, don't 1658 // try to compute the result expression. 1659 if (IsResultDependent) 1660 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1661 Exprs, DefaultLoc, RParenLoc, 1662 ContainsUnexpandedParameterPack); 1663 1664 SmallVector<unsigned, 1> CompatIndices; 1665 unsigned DefaultIndex = -1U; 1666 for (unsigned i = 0; i < NumAssocs; ++i) { 1667 if (!Types[i]) 1668 DefaultIndex = i; 1669 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1670 Types[i]->getType())) 1671 CompatIndices.push_back(i); 1672 } 1673 1674 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1675 // type compatible with at most one of the types named in its generic 1676 // association list." 1677 if (CompatIndices.size() > 1) { 1678 // We strip parens here because the controlling expression is typically 1679 // parenthesized in macro definitions. 1680 ControllingExpr = ControllingExpr->IgnoreParens(); 1681 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1682 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1683 << (unsigned)CompatIndices.size(); 1684 for (unsigned I : CompatIndices) { 1685 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1686 diag::note_compat_assoc) 1687 << Types[I]->getTypeLoc().getSourceRange() 1688 << Types[I]->getType(); 1689 } 1690 return ExprError(); 1691 } 1692 1693 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1694 // its controlling expression shall have type compatible with exactly one of 1695 // the types named in its generic association list." 1696 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1697 // We strip parens here because the controlling expression is typically 1698 // parenthesized in macro definitions. 1699 ControllingExpr = ControllingExpr->IgnoreParens(); 1700 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1701 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1702 return ExprError(); 1703 } 1704 1705 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1706 // type name that is compatible with the type of the controlling expression, 1707 // then the result expression of the generic selection is the expression 1708 // in that generic association. Otherwise, the result expression of the 1709 // generic selection is the expression in the default generic association." 1710 unsigned ResultIndex = 1711 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1712 1713 return GenericSelectionExpr::Create( 1714 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1715 ContainsUnexpandedParameterPack, ResultIndex); 1716 } 1717 1718 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1719 /// location of the token and the offset of the ud-suffix within it. 1720 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1721 unsigned Offset) { 1722 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1723 S.getLangOpts()); 1724 } 1725 1726 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1727 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1728 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1729 IdentifierInfo *UDSuffix, 1730 SourceLocation UDSuffixLoc, 1731 ArrayRef<Expr*> Args, 1732 SourceLocation LitEndLoc) { 1733 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1734 1735 QualType ArgTy[2]; 1736 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1737 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1738 if (ArgTy[ArgIdx]->isArrayType()) 1739 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1740 } 1741 1742 DeclarationName OpName = 1743 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1744 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1745 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1746 1747 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1748 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1749 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1750 /*AllowStringTemplate*/ false, 1751 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1752 return ExprError(); 1753 1754 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1755 } 1756 1757 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1758 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1759 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1760 /// multiple tokens. However, the common case is that StringToks points to one 1761 /// string. 1762 /// 1763 ExprResult 1764 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1765 assert(!StringToks.empty() && "Must have at least one string!"); 1766 1767 StringLiteralParser Literal(StringToks, PP); 1768 if (Literal.hadError) 1769 return ExprError(); 1770 1771 SmallVector<SourceLocation, 4> StringTokLocs; 1772 for (const Token &Tok : StringToks) 1773 StringTokLocs.push_back(Tok.getLocation()); 1774 1775 QualType CharTy = Context.CharTy; 1776 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1777 if (Literal.isWide()) { 1778 CharTy = Context.getWideCharType(); 1779 Kind = StringLiteral::Wide; 1780 } else if (Literal.isUTF8()) { 1781 if (getLangOpts().Char8) 1782 CharTy = Context.Char8Ty; 1783 Kind = StringLiteral::UTF8; 1784 } else if (Literal.isUTF16()) { 1785 CharTy = Context.Char16Ty; 1786 Kind = StringLiteral::UTF16; 1787 } else if (Literal.isUTF32()) { 1788 CharTy = Context.Char32Ty; 1789 Kind = StringLiteral::UTF32; 1790 } else if (Literal.isPascal()) { 1791 CharTy = Context.UnsignedCharTy; 1792 } 1793 1794 // Warn on initializing an array of char from a u8 string literal; this 1795 // becomes ill-formed in C++2a. 1796 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1797 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1798 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1799 1800 // Create removals for all 'u8' prefixes in the string literal(s). This 1801 // ensures C++2a compatibility (but may change the program behavior when 1802 // built by non-Clang compilers for which the execution character set is 1803 // not always UTF-8). 1804 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1805 SourceLocation RemovalDiagLoc; 1806 for (const Token &Tok : StringToks) { 1807 if (Tok.getKind() == tok::utf8_string_literal) { 1808 if (RemovalDiagLoc.isInvalid()) 1809 RemovalDiagLoc = Tok.getLocation(); 1810 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1811 Tok.getLocation(), 1812 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1813 getSourceManager(), getLangOpts()))); 1814 } 1815 } 1816 Diag(RemovalDiagLoc, RemovalDiag); 1817 } 1818 1819 QualType StrTy = 1820 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1821 1822 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1823 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1824 Kind, Literal.Pascal, StrTy, 1825 &StringTokLocs[0], 1826 StringTokLocs.size()); 1827 if (Literal.getUDSuffix().empty()) 1828 return Lit; 1829 1830 // We're building a user-defined literal. 1831 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1832 SourceLocation UDSuffixLoc = 1833 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1834 Literal.getUDSuffixOffset()); 1835 1836 // Make sure we're allowed user-defined literals here. 1837 if (!UDLScope) 1838 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1839 1840 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1841 // operator "" X (str, len) 1842 QualType SizeType = Context.getSizeType(); 1843 1844 DeclarationName OpName = 1845 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1846 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1847 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1848 1849 QualType ArgTy[] = { 1850 Context.getArrayDecayedType(StrTy), SizeType 1851 }; 1852 1853 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1854 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1855 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1856 /*AllowStringTemplate*/ true, 1857 /*DiagnoseMissing*/ true)) { 1858 1859 case LOLR_Cooked: { 1860 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1861 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1862 StringTokLocs[0]); 1863 Expr *Args[] = { Lit, LenArg }; 1864 1865 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1866 } 1867 1868 case LOLR_StringTemplate: { 1869 TemplateArgumentListInfo ExplicitArgs; 1870 1871 unsigned CharBits = Context.getIntWidth(CharTy); 1872 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1873 llvm::APSInt Value(CharBits, CharIsUnsigned); 1874 1875 TemplateArgument TypeArg(CharTy); 1876 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1877 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1878 1879 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1880 Value = Lit->getCodeUnit(I); 1881 TemplateArgument Arg(Context, Value, CharTy); 1882 TemplateArgumentLocInfo ArgInfo; 1883 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1884 } 1885 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1886 &ExplicitArgs); 1887 } 1888 case LOLR_Raw: 1889 case LOLR_Template: 1890 case LOLR_ErrorNoDiagnostic: 1891 llvm_unreachable("unexpected literal operator lookup result"); 1892 case LOLR_Error: 1893 return ExprError(); 1894 } 1895 llvm_unreachable("unexpected literal operator lookup result"); 1896 } 1897 1898 DeclRefExpr * 1899 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1900 SourceLocation Loc, 1901 const CXXScopeSpec *SS) { 1902 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1903 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1904 } 1905 1906 DeclRefExpr * 1907 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1908 const DeclarationNameInfo &NameInfo, 1909 const CXXScopeSpec *SS, NamedDecl *FoundD, 1910 SourceLocation TemplateKWLoc, 1911 const TemplateArgumentListInfo *TemplateArgs) { 1912 NestedNameSpecifierLoc NNS = 1913 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1914 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1915 TemplateArgs); 1916 } 1917 1918 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1919 // A declaration named in an unevaluated operand never constitutes an odr-use. 1920 if (isUnevaluatedContext()) 1921 return NOUR_Unevaluated; 1922 1923 // C++2a [basic.def.odr]p4: 1924 // A variable x whose name appears as a potentially-evaluated expression e 1925 // is odr-used by e unless [...] x is a reference that is usable in 1926 // constant expressions. 1927 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1928 if (VD->getType()->isReferenceType() && 1929 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1930 VD->isUsableInConstantExpressions(Context)) 1931 return NOUR_Constant; 1932 } 1933 1934 // All remaining non-variable cases constitute an odr-use. For variables, we 1935 // need to wait and see how the expression is used. 1936 return NOUR_None; 1937 } 1938 1939 /// BuildDeclRefExpr - Build an expression that references a 1940 /// declaration that does not require a closure capture. 1941 DeclRefExpr * 1942 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1943 const DeclarationNameInfo &NameInfo, 1944 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1945 SourceLocation TemplateKWLoc, 1946 const TemplateArgumentListInfo *TemplateArgs) { 1947 bool RefersToCapturedVariable = 1948 isa<VarDecl>(D) && 1949 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1950 1951 DeclRefExpr *E = DeclRefExpr::Create( 1952 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1953 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1954 MarkDeclRefReferenced(E); 1955 1956 // C++ [except.spec]p17: 1957 // An exception-specification is considered to be needed when: 1958 // - in an expression, the function is the unique lookup result or 1959 // the selected member of a set of overloaded functions. 1960 // 1961 // We delay doing this until after we've built the function reference and 1962 // marked it as used so that: 1963 // a) if the function is defaulted, we get errors from defining it before / 1964 // instead of errors from computing its exception specification, and 1965 // b) if the function is a defaulted comparison, we can use the body we 1966 // build when defining it as input to the exception specification 1967 // computation rather than computing a new body. 1968 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1969 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1970 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1971 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1972 } 1973 } 1974 1975 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1976 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1977 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1978 getCurFunction()->recordUseOfWeak(E); 1979 1980 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1981 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1982 FD = IFD->getAnonField(); 1983 if (FD) { 1984 UnusedPrivateFields.remove(FD); 1985 // Just in case we're building an illegal pointer-to-member. 1986 if (FD->isBitField()) 1987 E->setObjectKind(OK_BitField); 1988 } 1989 1990 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1991 // designates a bit-field. 1992 if (auto *BD = dyn_cast<BindingDecl>(D)) 1993 if (auto *BE = BD->getBinding()) 1994 E->setObjectKind(BE->getObjectKind()); 1995 1996 return E; 1997 } 1998 1999 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2000 /// possibly a list of template arguments. 2001 /// 2002 /// If this produces template arguments, it is permitted to call 2003 /// DecomposeTemplateName. 2004 /// 2005 /// This actually loses a lot of source location information for 2006 /// non-standard name kinds; we should consider preserving that in 2007 /// some way. 2008 void 2009 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2010 TemplateArgumentListInfo &Buffer, 2011 DeclarationNameInfo &NameInfo, 2012 const TemplateArgumentListInfo *&TemplateArgs) { 2013 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2014 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2015 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2016 2017 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2018 Id.TemplateId->NumArgs); 2019 translateTemplateArguments(TemplateArgsPtr, Buffer); 2020 2021 TemplateName TName = Id.TemplateId->Template.get(); 2022 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2023 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2024 TemplateArgs = &Buffer; 2025 } else { 2026 NameInfo = GetNameFromUnqualifiedId(Id); 2027 TemplateArgs = nullptr; 2028 } 2029 } 2030 2031 static void emitEmptyLookupTypoDiagnostic( 2032 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2033 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2034 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2035 DeclContext *Ctx = 2036 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2037 if (!TC) { 2038 // Emit a special diagnostic for failed member lookups. 2039 // FIXME: computing the declaration context might fail here (?) 2040 if (Ctx) 2041 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2042 << SS.getRange(); 2043 else 2044 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2045 return; 2046 } 2047 2048 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2049 bool DroppedSpecifier = 2050 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2051 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2052 ? diag::note_implicit_param_decl 2053 : diag::note_previous_decl; 2054 if (!Ctx) 2055 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2056 SemaRef.PDiag(NoteID)); 2057 else 2058 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2059 << Typo << Ctx << DroppedSpecifier 2060 << SS.getRange(), 2061 SemaRef.PDiag(NoteID)); 2062 } 2063 2064 /// Diagnose an empty lookup. 2065 /// 2066 /// \return false if new lookup candidates were found 2067 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2068 CorrectionCandidateCallback &CCC, 2069 TemplateArgumentListInfo *ExplicitTemplateArgs, 2070 ArrayRef<Expr *> Args, TypoExpr **Out) { 2071 DeclarationName Name = R.getLookupName(); 2072 2073 unsigned diagnostic = diag::err_undeclared_var_use; 2074 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2075 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2076 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2077 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2078 diagnostic = diag::err_undeclared_use; 2079 diagnostic_suggest = diag::err_undeclared_use_suggest; 2080 } 2081 2082 // If the original lookup was an unqualified lookup, fake an 2083 // unqualified lookup. This is useful when (for example) the 2084 // original lookup would not have found something because it was a 2085 // dependent name. 2086 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2087 while (DC) { 2088 if (isa<CXXRecordDecl>(DC)) { 2089 LookupQualifiedName(R, DC); 2090 2091 if (!R.empty()) { 2092 // Don't give errors about ambiguities in this lookup. 2093 R.suppressDiagnostics(); 2094 2095 // During a default argument instantiation the CurContext points 2096 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2097 // function parameter list, hence add an explicit check. 2098 bool isDefaultArgument = 2099 !CodeSynthesisContexts.empty() && 2100 CodeSynthesisContexts.back().Kind == 2101 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2102 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2103 bool isInstance = CurMethod && 2104 CurMethod->isInstance() && 2105 DC == CurMethod->getParent() && !isDefaultArgument; 2106 2107 // Give a code modification hint to insert 'this->'. 2108 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2109 // Actually quite difficult! 2110 if (getLangOpts().MSVCCompat) 2111 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2112 if (isInstance) { 2113 Diag(R.getNameLoc(), diagnostic) << Name 2114 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2115 CheckCXXThisCapture(R.getNameLoc()); 2116 } else { 2117 Diag(R.getNameLoc(), diagnostic) << Name; 2118 } 2119 2120 // Do we really want to note all of these? 2121 for (NamedDecl *D : R) 2122 Diag(D->getLocation(), diag::note_dependent_var_use); 2123 2124 // Return true if we are inside a default argument instantiation 2125 // and the found name refers to an instance member function, otherwise 2126 // the function calling DiagnoseEmptyLookup will try to create an 2127 // implicit member call and this is wrong for default argument. 2128 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2129 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2130 return true; 2131 } 2132 2133 // Tell the callee to try to recover. 2134 return false; 2135 } 2136 2137 R.clear(); 2138 } 2139 2140 DC = DC->getLookupParent(); 2141 } 2142 2143 // We didn't find anything, so try to correct for a typo. 2144 TypoCorrection Corrected; 2145 if (S && Out) { 2146 SourceLocation TypoLoc = R.getNameLoc(); 2147 assert(!ExplicitTemplateArgs && 2148 "Diagnosing an empty lookup with explicit template args!"); 2149 *Out = CorrectTypoDelayed( 2150 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2151 [=](const TypoCorrection &TC) { 2152 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2153 diagnostic, diagnostic_suggest); 2154 }, 2155 nullptr, CTK_ErrorRecovery); 2156 if (*Out) 2157 return true; 2158 } else if (S && 2159 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2160 S, &SS, CCC, CTK_ErrorRecovery))) { 2161 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2162 bool DroppedSpecifier = 2163 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2164 R.setLookupName(Corrected.getCorrection()); 2165 2166 bool AcceptableWithRecovery = false; 2167 bool AcceptableWithoutRecovery = false; 2168 NamedDecl *ND = Corrected.getFoundDecl(); 2169 if (ND) { 2170 if (Corrected.isOverloaded()) { 2171 OverloadCandidateSet OCS(R.getNameLoc(), 2172 OverloadCandidateSet::CSK_Normal); 2173 OverloadCandidateSet::iterator Best; 2174 for (NamedDecl *CD : Corrected) { 2175 if (FunctionTemplateDecl *FTD = 2176 dyn_cast<FunctionTemplateDecl>(CD)) 2177 AddTemplateOverloadCandidate( 2178 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2179 Args, OCS); 2180 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2181 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2182 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2183 Args, OCS); 2184 } 2185 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2186 case OR_Success: 2187 ND = Best->FoundDecl; 2188 Corrected.setCorrectionDecl(ND); 2189 break; 2190 default: 2191 // FIXME: Arbitrarily pick the first declaration for the note. 2192 Corrected.setCorrectionDecl(ND); 2193 break; 2194 } 2195 } 2196 R.addDecl(ND); 2197 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2198 CXXRecordDecl *Record = nullptr; 2199 if (Corrected.getCorrectionSpecifier()) { 2200 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2201 Record = Ty->getAsCXXRecordDecl(); 2202 } 2203 if (!Record) 2204 Record = cast<CXXRecordDecl>( 2205 ND->getDeclContext()->getRedeclContext()); 2206 R.setNamingClass(Record); 2207 } 2208 2209 auto *UnderlyingND = ND->getUnderlyingDecl(); 2210 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2211 isa<FunctionTemplateDecl>(UnderlyingND); 2212 // FIXME: If we ended up with a typo for a type name or 2213 // Objective-C class name, we're in trouble because the parser 2214 // is in the wrong place to recover. Suggest the typo 2215 // correction, but don't make it a fix-it since we're not going 2216 // to recover well anyway. 2217 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2218 getAsTypeTemplateDecl(UnderlyingND) || 2219 isa<ObjCInterfaceDecl>(UnderlyingND); 2220 } else { 2221 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2222 // because we aren't able to recover. 2223 AcceptableWithoutRecovery = true; 2224 } 2225 2226 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2227 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2228 ? diag::note_implicit_param_decl 2229 : diag::note_previous_decl; 2230 if (SS.isEmpty()) 2231 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2232 PDiag(NoteID), AcceptableWithRecovery); 2233 else 2234 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2235 << Name << computeDeclContext(SS, false) 2236 << DroppedSpecifier << SS.getRange(), 2237 PDiag(NoteID), AcceptableWithRecovery); 2238 2239 // Tell the callee whether to try to recover. 2240 return !AcceptableWithRecovery; 2241 } 2242 } 2243 R.clear(); 2244 2245 // Emit a special diagnostic for failed member lookups. 2246 // FIXME: computing the declaration context might fail here (?) 2247 if (!SS.isEmpty()) { 2248 Diag(R.getNameLoc(), diag::err_no_member) 2249 << Name << computeDeclContext(SS, false) 2250 << SS.getRange(); 2251 return true; 2252 } 2253 2254 // Give up, we can't recover. 2255 Diag(R.getNameLoc(), diagnostic) << Name; 2256 return true; 2257 } 2258 2259 /// In Microsoft mode, if we are inside a template class whose parent class has 2260 /// dependent base classes, and we can't resolve an unqualified identifier, then 2261 /// assume the identifier is a member of a dependent base class. We can only 2262 /// recover successfully in static methods, instance methods, and other contexts 2263 /// where 'this' is available. This doesn't precisely match MSVC's 2264 /// instantiation model, but it's close enough. 2265 static Expr * 2266 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2267 DeclarationNameInfo &NameInfo, 2268 SourceLocation TemplateKWLoc, 2269 const TemplateArgumentListInfo *TemplateArgs) { 2270 // Only try to recover from lookup into dependent bases in static methods or 2271 // contexts where 'this' is available. 2272 QualType ThisType = S.getCurrentThisType(); 2273 const CXXRecordDecl *RD = nullptr; 2274 if (!ThisType.isNull()) 2275 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2276 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2277 RD = MD->getParent(); 2278 if (!RD || !RD->hasAnyDependentBases()) 2279 return nullptr; 2280 2281 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2282 // is available, suggest inserting 'this->' as a fixit. 2283 SourceLocation Loc = NameInfo.getLoc(); 2284 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2285 DB << NameInfo.getName() << RD; 2286 2287 if (!ThisType.isNull()) { 2288 DB << FixItHint::CreateInsertion(Loc, "this->"); 2289 return CXXDependentScopeMemberExpr::Create( 2290 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2291 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2292 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2293 } 2294 2295 // Synthesize a fake NNS that points to the derived class. This will 2296 // perform name lookup during template instantiation. 2297 CXXScopeSpec SS; 2298 auto *NNS = 2299 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2300 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2301 return DependentScopeDeclRefExpr::Create( 2302 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2303 TemplateArgs); 2304 } 2305 2306 ExprResult 2307 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2308 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2309 bool HasTrailingLParen, bool IsAddressOfOperand, 2310 CorrectionCandidateCallback *CCC, 2311 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2312 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2313 "cannot be direct & operand and have a trailing lparen"); 2314 if (SS.isInvalid()) 2315 return ExprError(); 2316 2317 TemplateArgumentListInfo TemplateArgsBuffer; 2318 2319 // Decompose the UnqualifiedId into the following data. 2320 DeclarationNameInfo NameInfo; 2321 const TemplateArgumentListInfo *TemplateArgs; 2322 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2323 2324 DeclarationName Name = NameInfo.getName(); 2325 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2326 SourceLocation NameLoc = NameInfo.getLoc(); 2327 2328 if (II && II->isEditorPlaceholder()) { 2329 // FIXME: When typed placeholders are supported we can create a typed 2330 // placeholder expression node. 2331 return ExprError(); 2332 } 2333 2334 // C++ [temp.dep.expr]p3: 2335 // An id-expression is type-dependent if it contains: 2336 // -- an identifier that was declared with a dependent type, 2337 // (note: handled after lookup) 2338 // -- a template-id that is dependent, 2339 // (note: handled in BuildTemplateIdExpr) 2340 // -- a conversion-function-id that specifies a dependent type, 2341 // -- a nested-name-specifier that contains a class-name that 2342 // names a dependent type. 2343 // Determine whether this is a member of an unknown specialization; 2344 // we need to handle these differently. 2345 bool DependentID = false; 2346 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2347 Name.getCXXNameType()->isDependentType()) { 2348 DependentID = true; 2349 } else if (SS.isSet()) { 2350 if (DeclContext *DC = computeDeclContext(SS, false)) { 2351 if (RequireCompleteDeclContext(SS, DC)) 2352 return ExprError(); 2353 } else { 2354 DependentID = true; 2355 } 2356 } 2357 2358 if (DependentID) 2359 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2360 IsAddressOfOperand, TemplateArgs); 2361 2362 // Perform the required lookup. 2363 LookupResult R(*this, NameInfo, 2364 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2365 ? LookupObjCImplicitSelfParam 2366 : LookupOrdinaryName); 2367 if (TemplateKWLoc.isValid() || TemplateArgs) { 2368 // Lookup the template name again to correctly establish the context in 2369 // which it was found. This is really unfortunate as we already did the 2370 // lookup to determine that it was a template name in the first place. If 2371 // this becomes a performance hit, we can work harder to preserve those 2372 // results until we get here but it's likely not worth it. 2373 bool MemberOfUnknownSpecialization; 2374 AssumedTemplateKind AssumedTemplate; 2375 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2376 MemberOfUnknownSpecialization, TemplateKWLoc, 2377 &AssumedTemplate)) 2378 return ExprError(); 2379 2380 if (MemberOfUnknownSpecialization || 2381 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2382 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2383 IsAddressOfOperand, TemplateArgs); 2384 } else { 2385 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2386 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2387 2388 // If the result might be in a dependent base class, this is a dependent 2389 // id-expression. 2390 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2391 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2392 IsAddressOfOperand, TemplateArgs); 2393 2394 // If this reference is in an Objective-C method, then we need to do 2395 // some special Objective-C lookup, too. 2396 if (IvarLookupFollowUp) { 2397 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2398 if (E.isInvalid()) 2399 return ExprError(); 2400 2401 if (Expr *Ex = E.getAs<Expr>()) 2402 return Ex; 2403 } 2404 } 2405 2406 if (R.isAmbiguous()) 2407 return ExprError(); 2408 2409 // This could be an implicitly declared function reference (legal in C90, 2410 // extension in C99, forbidden in C++). 2411 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2412 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2413 if (D) R.addDecl(D); 2414 } 2415 2416 // Determine whether this name might be a candidate for 2417 // argument-dependent lookup. 2418 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2419 2420 if (R.empty() && !ADL) { 2421 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2422 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2423 TemplateKWLoc, TemplateArgs)) 2424 return E; 2425 } 2426 2427 // Don't diagnose an empty lookup for inline assembly. 2428 if (IsInlineAsmIdentifier) 2429 return ExprError(); 2430 2431 // If this name wasn't predeclared and if this is not a function 2432 // call, diagnose the problem. 2433 TypoExpr *TE = nullptr; 2434 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2435 : nullptr); 2436 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2437 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2438 "Typo correction callback misconfigured"); 2439 if (CCC) { 2440 // Make sure the callback knows what the typo being diagnosed is. 2441 CCC->setTypoName(II); 2442 if (SS.isValid()) 2443 CCC->setTypoNNS(SS.getScopeRep()); 2444 } 2445 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2446 // a template name, but we happen to have always already looked up the name 2447 // before we get here if it must be a template name. 2448 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2449 None, &TE)) { 2450 if (TE && KeywordReplacement) { 2451 auto &State = getTypoExprState(TE); 2452 auto BestTC = State.Consumer->getNextCorrection(); 2453 if (BestTC.isKeyword()) { 2454 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2455 if (State.DiagHandler) 2456 State.DiagHandler(BestTC); 2457 KeywordReplacement->startToken(); 2458 KeywordReplacement->setKind(II->getTokenID()); 2459 KeywordReplacement->setIdentifierInfo(II); 2460 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2461 // Clean up the state associated with the TypoExpr, since it has 2462 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2463 clearDelayedTypo(TE); 2464 // Signal that a correction to a keyword was performed by returning a 2465 // valid-but-null ExprResult. 2466 return (Expr*)nullptr; 2467 } 2468 State.Consumer->resetCorrectionStream(); 2469 } 2470 return TE ? TE : ExprError(); 2471 } 2472 2473 assert(!R.empty() && 2474 "DiagnoseEmptyLookup returned false but added no results"); 2475 2476 // If we found an Objective-C instance variable, let 2477 // LookupInObjCMethod build the appropriate expression to 2478 // reference the ivar. 2479 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2480 R.clear(); 2481 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2482 // In a hopelessly buggy code, Objective-C instance variable 2483 // lookup fails and no expression will be built to reference it. 2484 if (!E.isInvalid() && !E.get()) 2485 return ExprError(); 2486 return E; 2487 } 2488 } 2489 2490 // This is guaranteed from this point on. 2491 assert(!R.empty() || ADL); 2492 2493 // Check whether this might be a C++ implicit instance member access. 2494 // C++ [class.mfct.non-static]p3: 2495 // When an id-expression that is not part of a class member access 2496 // syntax and not used to form a pointer to member is used in the 2497 // body of a non-static member function of class X, if name lookup 2498 // resolves the name in the id-expression to a non-static non-type 2499 // member of some class C, the id-expression is transformed into a 2500 // class member access expression using (*this) as the 2501 // postfix-expression to the left of the . operator. 2502 // 2503 // But we don't actually need to do this for '&' operands if R 2504 // resolved to a function or overloaded function set, because the 2505 // expression is ill-formed if it actually works out to be a 2506 // non-static member function: 2507 // 2508 // C++ [expr.ref]p4: 2509 // Otherwise, if E1.E2 refers to a non-static member function. . . 2510 // [t]he expression can be used only as the left-hand operand of a 2511 // member function call. 2512 // 2513 // There are other safeguards against such uses, but it's important 2514 // to get this right here so that we don't end up making a 2515 // spuriously dependent expression if we're inside a dependent 2516 // instance method. 2517 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2518 bool MightBeImplicitMember; 2519 if (!IsAddressOfOperand) 2520 MightBeImplicitMember = true; 2521 else if (!SS.isEmpty()) 2522 MightBeImplicitMember = false; 2523 else if (R.isOverloadedResult()) 2524 MightBeImplicitMember = false; 2525 else if (R.isUnresolvableResult()) 2526 MightBeImplicitMember = true; 2527 else 2528 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2529 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2530 isa<MSPropertyDecl>(R.getFoundDecl()); 2531 2532 if (MightBeImplicitMember) 2533 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2534 R, TemplateArgs, S); 2535 } 2536 2537 if (TemplateArgs || TemplateKWLoc.isValid()) { 2538 2539 // In C++1y, if this is a variable template id, then check it 2540 // in BuildTemplateIdExpr(). 2541 // The single lookup result must be a variable template declaration. 2542 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2543 Id.TemplateId->Kind == TNK_Var_template) { 2544 assert(R.getAsSingle<VarTemplateDecl>() && 2545 "There should only be one declaration found."); 2546 } 2547 2548 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2549 } 2550 2551 return BuildDeclarationNameExpr(SS, R, ADL); 2552 } 2553 2554 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2555 /// declaration name, generally during template instantiation. 2556 /// There's a large number of things which don't need to be done along 2557 /// this path. 2558 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2559 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2560 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2561 DeclContext *DC = computeDeclContext(SS, false); 2562 if (!DC) 2563 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2564 NameInfo, /*TemplateArgs=*/nullptr); 2565 2566 if (RequireCompleteDeclContext(SS, DC)) 2567 return ExprError(); 2568 2569 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2570 LookupQualifiedName(R, DC); 2571 2572 if (R.isAmbiguous()) 2573 return ExprError(); 2574 2575 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2576 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2577 NameInfo, /*TemplateArgs=*/nullptr); 2578 2579 if (R.empty()) { 2580 Diag(NameInfo.getLoc(), diag::err_no_member) 2581 << NameInfo.getName() << DC << SS.getRange(); 2582 return ExprError(); 2583 } 2584 2585 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2586 // Diagnose a missing typename if this resolved unambiguously to a type in 2587 // a dependent context. If we can recover with a type, downgrade this to 2588 // a warning in Microsoft compatibility mode. 2589 unsigned DiagID = diag::err_typename_missing; 2590 if (RecoveryTSI && getLangOpts().MSVCCompat) 2591 DiagID = diag::ext_typename_missing; 2592 SourceLocation Loc = SS.getBeginLoc(); 2593 auto D = Diag(Loc, DiagID); 2594 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2595 << SourceRange(Loc, NameInfo.getEndLoc()); 2596 2597 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2598 // context. 2599 if (!RecoveryTSI) 2600 return ExprError(); 2601 2602 // Only issue the fixit if we're prepared to recover. 2603 D << FixItHint::CreateInsertion(Loc, "typename "); 2604 2605 // Recover by pretending this was an elaborated type. 2606 QualType Ty = Context.getTypeDeclType(TD); 2607 TypeLocBuilder TLB; 2608 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2609 2610 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2611 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2612 QTL.setElaboratedKeywordLoc(SourceLocation()); 2613 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2614 2615 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2616 2617 return ExprEmpty(); 2618 } 2619 2620 // Defend against this resolving to an implicit member access. We usually 2621 // won't get here if this might be a legitimate a class member (we end up in 2622 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2623 // a pointer-to-member or in an unevaluated context in C++11. 2624 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2625 return BuildPossibleImplicitMemberExpr(SS, 2626 /*TemplateKWLoc=*/SourceLocation(), 2627 R, /*TemplateArgs=*/nullptr, S); 2628 2629 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2630 } 2631 2632 /// The parser has read a name in, and Sema has detected that we're currently 2633 /// inside an ObjC method. Perform some additional checks and determine if we 2634 /// should form a reference to an ivar. 2635 /// 2636 /// Ideally, most of this would be done by lookup, but there's 2637 /// actually quite a lot of extra work involved. 2638 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2639 IdentifierInfo *II) { 2640 SourceLocation Loc = Lookup.getNameLoc(); 2641 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2642 2643 // Check for error condition which is already reported. 2644 if (!CurMethod) 2645 return DeclResult(true); 2646 2647 // There are two cases to handle here. 1) scoped lookup could have failed, 2648 // in which case we should look for an ivar. 2) scoped lookup could have 2649 // found a decl, but that decl is outside the current instance method (i.e. 2650 // a global variable). In these two cases, we do a lookup for an ivar with 2651 // this name, if the lookup sucedes, we replace it our current decl. 2652 2653 // If we're in a class method, we don't normally want to look for 2654 // ivars. But if we don't find anything else, and there's an 2655 // ivar, that's an error. 2656 bool IsClassMethod = CurMethod->isClassMethod(); 2657 2658 bool LookForIvars; 2659 if (Lookup.empty()) 2660 LookForIvars = true; 2661 else if (IsClassMethod) 2662 LookForIvars = false; 2663 else 2664 LookForIvars = (Lookup.isSingleResult() && 2665 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2666 ObjCInterfaceDecl *IFace = nullptr; 2667 if (LookForIvars) { 2668 IFace = CurMethod->getClassInterface(); 2669 ObjCInterfaceDecl *ClassDeclared; 2670 ObjCIvarDecl *IV = nullptr; 2671 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2672 // Diagnose using an ivar in a class method. 2673 if (IsClassMethod) { 2674 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2675 return DeclResult(true); 2676 } 2677 2678 // Diagnose the use of an ivar outside of the declaring class. 2679 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2680 !declaresSameEntity(ClassDeclared, IFace) && 2681 !getLangOpts().DebuggerSupport) 2682 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2683 2684 // Success. 2685 return IV; 2686 } 2687 } else if (CurMethod->isInstanceMethod()) { 2688 // We should warn if a local variable hides an ivar. 2689 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2690 ObjCInterfaceDecl *ClassDeclared; 2691 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2692 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2693 declaresSameEntity(IFace, ClassDeclared)) 2694 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2695 } 2696 } 2697 } else if (Lookup.isSingleResult() && 2698 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2699 // If accessing a stand-alone ivar in a class method, this is an error. 2700 if (const ObjCIvarDecl *IV = 2701 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2702 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2703 return DeclResult(true); 2704 } 2705 } 2706 2707 // Didn't encounter an error, didn't find an ivar. 2708 return DeclResult(false); 2709 } 2710 2711 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2712 ObjCIvarDecl *IV) { 2713 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2714 assert(CurMethod && CurMethod->isInstanceMethod() && 2715 "should not reference ivar from this context"); 2716 2717 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2718 assert(IFace && "should not reference ivar from this context"); 2719 2720 // If we're referencing an invalid decl, just return this as a silent 2721 // error node. The error diagnostic was already emitted on the decl. 2722 if (IV->isInvalidDecl()) 2723 return ExprError(); 2724 2725 // Check if referencing a field with __attribute__((deprecated)). 2726 if (DiagnoseUseOfDecl(IV, Loc)) 2727 return ExprError(); 2728 2729 // FIXME: This should use a new expr for a direct reference, don't 2730 // turn this into Self->ivar, just return a BareIVarExpr or something. 2731 IdentifierInfo &II = Context.Idents.get("self"); 2732 UnqualifiedId SelfName; 2733 SelfName.setIdentifier(&II, SourceLocation()); 2734 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2735 CXXScopeSpec SelfScopeSpec; 2736 SourceLocation TemplateKWLoc; 2737 ExprResult SelfExpr = 2738 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2739 /*HasTrailingLParen=*/false, 2740 /*IsAddressOfOperand=*/false); 2741 if (SelfExpr.isInvalid()) 2742 return ExprError(); 2743 2744 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2745 if (SelfExpr.isInvalid()) 2746 return ExprError(); 2747 2748 MarkAnyDeclReferenced(Loc, IV, true); 2749 2750 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2751 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2752 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2753 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2754 2755 ObjCIvarRefExpr *Result = new (Context) 2756 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2757 IV->getLocation(), SelfExpr.get(), true, true); 2758 2759 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2760 if (!isUnevaluatedContext() && 2761 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2762 getCurFunction()->recordUseOfWeak(Result); 2763 } 2764 if (getLangOpts().ObjCAutoRefCount) 2765 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2766 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2767 2768 return Result; 2769 } 2770 2771 /// The parser has read a name in, and Sema has detected that we're currently 2772 /// inside an ObjC method. Perform some additional checks and determine if we 2773 /// should form a reference to an ivar. If so, build an expression referencing 2774 /// that ivar. 2775 ExprResult 2776 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2777 IdentifierInfo *II, bool AllowBuiltinCreation) { 2778 // FIXME: Integrate this lookup step into LookupParsedName. 2779 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2780 if (Ivar.isInvalid()) 2781 return ExprError(); 2782 if (Ivar.isUsable()) 2783 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2784 cast<ObjCIvarDecl>(Ivar.get())); 2785 2786 if (Lookup.empty() && II && AllowBuiltinCreation) 2787 LookupBuiltin(Lookup); 2788 2789 // Sentinel value saying that we didn't do anything special. 2790 return ExprResult(false); 2791 } 2792 2793 /// Cast a base object to a member's actual type. 2794 /// 2795 /// Logically this happens in three phases: 2796 /// 2797 /// * First we cast from the base type to the naming class. 2798 /// The naming class is the class into which we were looking 2799 /// when we found the member; it's the qualifier type if a 2800 /// qualifier was provided, and otherwise it's the base type. 2801 /// 2802 /// * Next we cast from the naming class to the declaring class. 2803 /// If the member we found was brought into a class's scope by 2804 /// a using declaration, this is that class; otherwise it's 2805 /// the class declaring the member. 2806 /// 2807 /// * Finally we cast from the declaring class to the "true" 2808 /// declaring class of the member. This conversion does not 2809 /// obey access control. 2810 ExprResult 2811 Sema::PerformObjectMemberConversion(Expr *From, 2812 NestedNameSpecifier *Qualifier, 2813 NamedDecl *FoundDecl, 2814 NamedDecl *Member) { 2815 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2816 if (!RD) 2817 return From; 2818 2819 QualType DestRecordType; 2820 QualType DestType; 2821 QualType FromRecordType; 2822 QualType FromType = From->getType(); 2823 bool PointerConversions = false; 2824 if (isa<FieldDecl>(Member)) { 2825 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2826 auto FromPtrType = FromType->getAs<PointerType>(); 2827 DestRecordType = Context.getAddrSpaceQualType( 2828 DestRecordType, FromPtrType 2829 ? FromType->getPointeeType().getAddressSpace() 2830 : FromType.getAddressSpace()); 2831 2832 if (FromPtrType) { 2833 DestType = Context.getPointerType(DestRecordType); 2834 FromRecordType = FromPtrType->getPointeeType(); 2835 PointerConversions = true; 2836 } else { 2837 DestType = DestRecordType; 2838 FromRecordType = FromType; 2839 } 2840 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2841 if (Method->isStatic()) 2842 return From; 2843 2844 DestType = Method->getThisType(); 2845 DestRecordType = DestType->getPointeeType(); 2846 2847 if (FromType->getAs<PointerType>()) { 2848 FromRecordType = FromType->getPointeeType(); 2849 PointerConversions = true; 2850 } else { 2851 FromRecordType = FromType; 2852 DestType = DestRecordType; 2853 } 2854 2855 LangAS FromAS = FromRecordType.getAddressSpace(); 2856 LangAS DestAS = DestRecordType.getAddressSpace(); 2857 if (FromAS != DestAS) { 2858 QualType FromRecordTypeWithoutAS = 2859 Context.removeAddrSpaceQualType(FromRecordType); 2860 QualType FromTypeWithDestAS = 2861 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2862 if (PointerConversions) 2863 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2864 From = ImpCastExprToType(From, FromTypeWithDestAS, 2865 CK_AddressSpaceConversion, From->getValueKind()) 2866 .get(); 2867 } 2868 } else { 2869 // No conversion necessary. 2870 return From; 2871 } 2872 2873 if (DestType->isDependentType() || FromType->isDependentType()) 2874 return From; 2875 2876 // If the unqualified types are the same, no conversion is necessary. 2877 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2878 return From; 2879 2880 SourceRange FromRange = From->getSourceRange(); 2881 SourceLocation FromLoc = FromRange.getBegin(); 2882 2883 ExprValueKind VK = From->getValueKind(); 2884 2885 // C++ [class.member.lookup]p8: 2886 // [...] Ambiguities can often be resolved by qualifying a name with its 2887 // class name. 2888 // 2889 // If the member was a qualified name and the qualified referred to a 2890 // specific base subobject type, we'll cast to that intermediate type 2891 // first and then to the object in which the member is declared. That allows 2892 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2893 // 2894 // class Base { public: int x; }; 2895 // class Derived1 : public Base { }; 2896 // class Derived2 : public Base { }; 2897 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2898 // 2899 // void VeryDerived::f() { 2900 // x = 17; // error: ambiguous base subobjects 2901 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2902 // } 2903 if (Qualifier && Qualifier->getAsType()) { 2904 QualType QType = QualType(Qualifier->getAsType(), 0); 2905 assert(QType->isRecordType() && "lookup done with non-record type"); 2906 2907 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2908 2909 // In C++98, the qualifier type doesn't actually have to be a base 2910 // type of the object type, in which case we just ignore it. 2911 // Otherwise build the appropriate casts. 2912 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2913 CXXCastPath BasePath; 2914 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2915 FromLoc, FromRange, &BasePath)) 2916 return ExprError(); 2917 2918 if (PointerConversions) 2919 QType = Context.getPointerType(QType); 2920 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2921 VK, &BasePath).get(); 2922 2923 FromType = QType; 2924 FromRecordType = QRecordType; 2925 2926 // If the qualifier type was the same as the destination type, 2927 // we're done. 2928 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2929 return From; 2930 } 2931 } 2932 2933 bool IgnoreAccess = false; 2934 2935 // If we actually found the member through a using declaration, cast 2936 // down to the using declaration's type. 2937 // 2938 // Pointer equality is fine here because only one declaration of a 2939 // class ever has member declarations. 2940 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2941 assert(isa<UsingShadowDecl>(FoundDecl)); 2942 QualType URecordType = Context.getTypeDeclType( 2943 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2944 2945 // We only need to do this if the naming-class to declaring-class 2946 // conversion is non-trivial. 2947 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2948 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2949 CXXCastPath BasePath; 2950 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2951 FromLoc, FromRange, &BasePath)) 2952 return ExprError(); 2953 2954 QualType UType = URecordType; 2955 if (PointerConversions) 2956 UType = Context.getPointerType(UType); 2957 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2958 VK, &BasePath).get(); 2959 FromType = UType; 2960 FromRecordType = URecordType; 2961 } 2962 2963 // We don't do access control for the conversion from the 2964 // declaring class to the true declaring class. 2965 IgnoreAccess = true; 2966 } 2967 2968 CXXCastPath BasePath; 2969 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2970 FromLoc, FromRange, &BasePath, 2971 IgnoreAccess)) 2972 return ExprError(); 2973 2974 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2975 VK, &BasePath); 2976 } 2977 2978 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2979 const LookupResult &R, 2980 bool HasTrailingLParen) { 2981 // Only when used directly as the postfix-expression of a call. 2982 if (!HasTrailingLParen) 2983 return false; 2984 2985 // Never if a scope specifier was provided. 2986 if (SS.isSet()) 2987 return false; 2988 2989 // Only in C++ or ObjC++. 2990 if (!getLangOpts().CPlusPlus) 2991 return false; 2992 2993 // Turn off ADL when we find certain kinds of declarations during 2994 // normal lookup: 2995 for (NamedDecl *D : R) { 2996 // C++0x [basic.lookup.argdep]p3: 2997 // -- a declaration of a class member 2998 // Since using decls preserve this property, we check this on the 2999 // original decl. 3000 if (D->isCXXClassMember()) 3001 return false; 3002 3003 // C++0x [basic.lookup.argdep]p3: 3004 // -- a block-scope function declaration that is not a 3005 // using-declaration 3006 // NOTE: we also trigger this for function templates (in fact, we 3007 // don't check the decl type at all, since all other decl types 3008 // turn off ADL anyway). 3009 if (isa<UsingShadowDecl>(D)) 3010 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3011 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3012 return false; 3013 3014 // C++0x [basic.lookup.argdep]p3: 3015 // -- a declaration that is neither a function or a function 3016 // template 3017 // And also for builtin functions. 3018 if (isa<FunctionDecl>(D)) { 3019 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3020 3021 // But also builtin functions. 3022 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3023 return false; 3024 } else if (!isa<FunctionTemplateDecl>(D)) 3025 return false; 3026 } 3027 3028 return true; 3029 } 3030 3031 3032 /// Diagnoses obvious problems with the use of the given declaration 3033 /// as an expression. This is only actually called for lookups that 3034 /// were not overloaded, and it doesn't promise that the declaration 3035 /// will in fact be used. 3036 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3037 if (D->isInvalidDecl()) 3038 return true; 3039 3040 if (isa<TypedefNameDecl>(D)) { 3041 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3042 return true; 3043 } 3044 3045 if (isa<ObjCInterfaceDecl>(D)) { 3046 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3047 return true; 3048 } 3049 3050 if (isa<NamespaceDecl>(D)) { 3051 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3052 return true; 3053 } 3054 3055 return false; 3056 } 3057 3058 // Certain multiversion types should be treated as overloaded even when there is 3059 // only one result. 3060 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3061 assert(R.isSingleResult() && "Expected only a single result"); 3062 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3063 return FD && 3064 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3065 } 3066 3067 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3068 LookupResult &R, bool NeedsADL, 3069 bool AcceptInvalidDecl) { 3070 // If this is a single, fully-resolved result and we don't need ADL, 3071 // just build an ordinary singleton decl ref. 3072 if (!NeedsADL && R.isSingleResult() && 3073 !R.getAsSingle<FunctionTemplateDecl>() && 3074 !ShouldLookupResultBeMultiVersionOverload(R)) 3075 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3076 R.getRepresentativeDecl(), nullptr, 3077 AcceptInvalidDecl); 3078 3079 // We only need to check the declaration if there's exactly one 3080 // result, because in the overloaded case the results can only be 3081 // functions and function templates. 3082 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3083 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3084 return ExprError(); 3085 3086 // Otherwise, just build an unresolved lookup expression. Suppress 3087 // any lookup-related diagnostics; we'll hash these out later, when 3088 // we've picked a target. 3089 R.suppressDiagnostics(); 3090 3091 UnresolvedLookupExpr *ULE 3092 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3093 SS.getWithLocInContext(Context), 3094 R.getLookupNameInfo(), 3095 NeedsADL, R.isOverloadedResult(), 3096 R.begin(), R.end()); 3097 3098 return ULE; 3099 } 3100 3101 static void 3102 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3103 ValueDecl *var, DeclContext *DC); 3104 3105 /// Complete semantic analysis for a reference to the given declaration. 3106 ExprResult Sema::BuildDeclarationNameExpr( 3107 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3108 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3109 bool AcceptInvalidDecl) { 3110 assert(D && "Cannot refer to a NULL declaration"); 3111 assert(!isa<FunctionTemplateDecl>(D) && 3112 "Cannot refer unambiguously to a function template"); 3113 3114 SourceLocation Loc = NameInfo.getLoc(); 3115 if (CheckDeclInExpr(*this, Loc, D)) 3116 return ExprError(); 3117 3118 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3119 // Specifically diagnose references to class templates that are missing 3120 // a template argument list. 3121 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3122 return ExprError(); 3123 } 3124 3125 // Make sure that we're referring to a value. 3126 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3127 if (!VD) { 3128 Diag(Loc, diag::err_ref_non_value) 3129 << D << SS.getRange(); 3130 Diag(D->getLocation(), diag::note_declared_at); 3131 return ExprError(); 3132 } 3133 3134 // Check whether this declaration can be used. Note that we suppress 3135 // this check when we're going to perform argument-dependent lookup 3136 // on this function name, because this might not be the function 3137 // that overload resolution actually selects. 3138 if (DiagnoseUseOfDecl(VD, Loc)) 3139 return ExprError(); 3140 3141 // Only create DeclRefExpr's for valid Decl's. 3142 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3143 return ExprError(); 3144 3145 // Handle members of anonymous structs and unions. If we got here, 3146 // and the reference is to a class member indirect field, then this 3147 // must be the subject of a pointer-to-member expression. 3148 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3149 if (!indirectField->isCXXClassMember()) 3150 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3151 indirectField); 3152 3153 { 3154 QualType type = VD->getType(); 3155 if (type.isNull()) 3156 return ExprError(); 3157 ExprValueKind valueKind = VK_RValue; 3158 3159 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3160 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3161 // is expanded by some outer '...' in the context of the use. 3162 type = type.getNonPackExpansionType(); 3163 3164 switch (D->getKind()) { 3165 // Ignore all the non-ValueDecl kinds. 3166 #define ABSTRACT_DECL(kind) 3167 #define VALUE(type, base) 3168 #define DECL(type, base) \ 3169 case Decl::type: 3170 #include "clang/AST/DeclNodes.inc" 3171 llvm_unreachable("invalid value decl kind"); 3172 3173 // These shouldn't make it here. 3174 case Decl::ObjCAtDefsField: 3175 llvm_unreachable("forming non-member reference to ivar?"); 3176 3177 // Enum constants are always r-values and never references. 3178 // Unresolved using declarations are dependent. 3179 case Decl::EnumConstant: 3180 case Decl::UnresolvedUsingValue: 3181 case Decl::OMPDeclareReduction: 3182 case Decl::OMPDeclareMapper: 3183 valueKind = VK_RValue; 3184 break; 3185 3186 // Fields and indirect fields that got here must be for 3187 // pointer-to-member expressions; we just call them l-values for 3188 // internal consistency, because this subexpression doesn't really 3189 // exist in the high-level semantics. 3190 case Decl::Field: 3191 case Decl::IndirectField: 3192 case Decl::ObjCIvar: 3193 assert(getLangOpts().CPlusPlus && 3194 "building reference to field in C?"); 3195 3196 // These can't have reference type in well-formed programs, but 3197 // for internal consistency we do this anyway. 3198 type = type.getNonReferenceType(); 3199 valueKind = VK_LValue; 3200 break; 3201 3202 // Non-type template parameters are either l-values or r-values 3203 // depending on the type. 3204 case Decl::NonTypeTemplateParm: { 3205 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3206 type = reftype->getPointeeType(); 3207 valueKind = VK_LValue; // even if the parameter is an r-value reference 3208 break; 3209 } 3210 3211 // For non-references, we need to strip qualifiers just in case 3212 // the template parameter was declared as 'const int' or whatever. 3213 valueKind = VK_RValue; 3214 type = type.getUnqualifiedType(); 3215 break; 3216 } 3217 3218 case Decl::Var: 3219 case Decl::VarTemplateSpecialization: 3220 case Decl::VarTemplatePartialSpecialization: 3221 case Decl::Decomposition: 3222 case Decl::OMPCapturedExpr: 3223 // In C, "extern void blah;" is valid and is an r-value. 3224 if (!getLangOpts().CPlusPlus && 3225 !type.hasQualifiers() && 3226 type->isVoidType()) { 3227 valueKind = VK_RValue; 3228 break; 3229 } 3230 LLVM_FALLTHROUGH; 3231 3232 case Decl::ImplicitParam: 3233 case Decl::ParmVar: { 3234 // These are always l-values. 3235 valueKind = VK_LValue; 3236 type = type.getNonReferenceType(); 3237 3238 // FIXME: Does the addition of const really only apply in 3239 // potentially-evaluated contexts? Since the variable isn't actually 3240 // captured in an unevaluated context, it seems that the answer is no. 3241 if (!isUnevaluatedContext()) { 3242 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3243 if (!CapturedType.isNull()) 3244 type = CapturedType; 3245 } 3246 3247 break; 3248 } 3249 3250 case Decl::Binding: { 3251 // These are always lvalues. 3252 valueKind = VK_LValue; 3253 type = type.getNonReferenceType(); 3254 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3255 // decides how that's supposed to work. 3256 auto *BD = cast<BindingDecl>(VD); 3257 if (BD->getDeclContext() != CurContext) { 3258 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3259 if (DD && DD->hasLocalStorage()) 3260 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3261 } 3262 break; 3263 } 3264 3265 case Decl::Function: { 3266 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3267 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3268 type = Context.BuiltinFnTy; 3269 valueKind = VK_RValue; 3270 break; 3271 } 3272 } 3273 3274 const FunctionType *fty = type->castAs<FunctionType>(); 3275 3276 // If we're referring to a function with an __unknown_anytype 3277 // result type, make the entire expression __unknown_anytype. 3278 if (fty->getReturnType() == Context.UnknownAnyTy) { 3279 type = Context.UnknownAnyTy; 3280 valueKind = VK_RValue; 3281 break; 3282 } 3283 3284 // Functions are l-values in C++. 3285 if (getLangOpts().CPlusPlus) { 3286 valueKind = VK_LValue; 3287 break; 3288 } 3289 3290 // C99 DR 316 says that, if a function type comes from a 3291 // function definition (without a prototype), that type is only 3292 // used for checking compatibility. Therefore, when referencing 3293 // the function, we pretend that we don't have the full function 3294 // type. 3295 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3296 isa<FunctionProtoType>(fty)) 3297 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3298 fty->getExtInfo()); 3299 3300 // Functions are r-values in C. 3301 valueKind = VK_RValue; 3302 break; 3303 } 3304 3305 case Decl::CXXDeductionGuide: 3306 llvm_unreachable("building reference to deduction guide"); 3307 3308 case Decl::MSProperty: 3309 case Decl::MSGuid: 3310 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3311 // or duplicated between host and device? 3312 valueKind = VK_LValue; 3313 break; 3314 3315 case Decl::CXXMethod: 3316 // If we're referring to a method with an __unknown_anytype 3317 // result type, make the entire expression __unknown_anytype. 3318 // This should only be possible with a type written directly. 3319 if (const FunctionProtoType *proto 3320 = dyn_cast<FunctionProtoType>(VD->getType())) 3321 if (proto->getReturnType() == Context.UnknownAnyTy) { 3322 type = Context.UnknownAnyTy; 3323 valueKind = VK_RValue; 3324 break; 3325 } 3326 3327 // C++ methods are l-values if static, r-values if non-static. 3328 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3329 valueKind = VK_LValue; 3330 break; 3331 } 3332 LLVM_FALLTHROUGH; 3333 3334 case Decl::CXXConversion: 3335 case Decl::CXXDestructor: 3336 case Decl::CXXConstructor: 3337 valueKind = VK_RValue; 3338 break; 3339 } 3340 3341 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3342 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3343 TemplateArgs); 3344 } 3345 } 3346 3347 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3348 SmallString<32> &Target) { 3349 Target.resize(CharByteWidth * (Source.size() + 1)); 3350 char *ResultPtr = &Target[0]; 3351 const llvm::UTF8 *ErrorPtr; 3352 bool success = 3353 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3354 (void)success; 3355 assert(success); 3356 Target.resize(ResultPtr - &Target[0]); 3357 } 3358 3359 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3360 PredefinedExpr::IdentKind IK) { 3361 // Pick the current block, lambda, captured statement or function. 3362 Decl *currentDecl = nullptr; 3363 if (const BlockScopeInfo *BSI = getCurBlock()) 3364 currentDecl = BSI->TheDecl; 3365 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3366 currentDecl = LSI->CallOperator; 3367 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3368 currentDecl = CSI->TheCapturedDecl; 3369 else 3370 currentDecl = getCurFunctionOrMethodDecl(); 3371 3372 if (!currentDecl) { 3373 Diag(Loc, diag::ext_predef_outside_function); 3374 currentDecl = Context.getTranslationUnitDecl(); 3375 } 3376 3377 QualType ResTy; 3378 StringLiteral *SL = nullptr; 3379 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3380 ResTy = Context.DependentTy; 3381 else { 3382 // Pre-defined identifiers are of type char[x], where x is the length of 3383 // the string. 3384 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3385 unsigned Length = Str.length(); 3386 3387 llvm::APInt LengthI(32, Length + 1); 3388 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3389 ResTy = 3390 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3391 SmallString<32> RawChars; 3392 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3393 Str, RawChars); 3394 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3395 ArrayType::Normal, 3396 /*IndexTypeQuals*/ 0); 3397 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3398 /*Pascal*/ false, ResTy, Loc); 3399 } else { 3400 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3401 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3402 ArrayType::Normal, 3403 /*IndexTypeQuals*/ 0); 3404 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3405 /*Pascal*/ false, ResTy, Loc); 3406 } 3407 } 3408 3409 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3410 } 3411 3412 static std::pair<QualType, StringLiteral *> 3413 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3414 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3415 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3416 3417 if (OpType->isDependentType()) { 3418 Result.first = Context.DependentTy; 3419 return Result; 3420 } 3421 3422 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3423 llvm::APInt Length(32, Str.length() + 1); 3424 Result.first = 3425 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3426 Result.first = Context.getConstantArrayType( 3427 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3428 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3429 /*Pascal*/ false, Result.first, OpLoc); 3430 return Result; 3431 } 3432 3433 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3434 TypeSourceInfo *Operand) { 3435 QualType ResultTy; 3436 StringLiteral *SL; 3437 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3438 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3439 3440 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3441 PredefinedExpr::UniqueStableNameType, SL, 3442 Operand); 3443 } 3444 3445 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3446 Expr *E) { 3447 QualType ResultTy; 3448 StringLiteral *SL; 3449 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3450 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3451 3452 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3453 PredefinedExpr::UniqueStableNameExpr, SL, E); 3454 } 3455 3456 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3457 SourceLocation L, SourceLocation R, 3458 ParsedType Ty) { 3459 TypeSourceInfo *TInfo = nullptr; 3460 QualType T = GetTypeFromParser(Ty, &TInfo); 3461 3462 if (T.isNull()) 3463 return ExprError(); 3464 if (!TInfo) 3465 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3466 3467 return BuildUniqueStableName(OpLoc, TInfo); 3468 } 3469 3470 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3471 SourceLocation L, SourceLocation R, 3472 Expr *E) { 3473 return BuildUniqueStableName(OpLoc, E); 3474 } 3475 3476 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3477 PredefinedExpr::IdentKind IK; 3478 3479 switch (Kind) { 3480 default: llvm_unreachable("Unknown simple primary expr!"); 3481 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3482 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3483 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3484 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3485 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3486 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3487 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3488 } 3489 3490 return BuildPredefinedExpr(Loc, IK); 3491 } 3492 3493 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3494 SmallString<16> CharBuffer; 3495 bool Invalid = false; 3496 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3497 if (Invalid) 3498 return ExprError(); 3499 3500 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3501 PP, Tok.getKind()); 3502 if (Literal.hadError()) 3503 return ExprError(); 3504 3505 QualType Ty; 3506 if (Literal.isWide()) 3507 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3508 else if (Literal.isUTF8() && getLangOpts().Char8) 3509 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3510 else if (Literal.isUTF16()) 3511 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3512 else if (Literal.isUTF32()) 3513 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3514 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3515 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3516 else 3517 Ty = Context.CharTy; // 'x' -> char in C++ 3518 3519 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3520 if (Literal.isWide()) 3521 Kind = CharacterLiteral::Wide; 3522 else if (Literal.isUTF16()) 3523 Kind = CharacterLiteral::UTF16; 3524 else if (Literal.isUTF32()) 3525 Kind = CharacterLiteral::UTF32; 3526 else if (Literal.isUTF8()) 3527 Kind = CharacterLiteral::UTF8; 3528 3529 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3530 Tok.getLocation()); 3531 3532 if (Literal.getUDSuffix().empty()) 3533 return Lit; 3534 3535 // We're building a user-defined literal. 3536 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3537 SourceLocation UDSuffixLoc = 3538 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3539 3540 // Make sure we're allowed user-defined literals here. 3541 if (!UDLScope) 3542 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3543 3544 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3545 // operator "" X (ch) 3546 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3547 Lit, Tok.getLocation()); 3548 } 3549 3550 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3551 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3552 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3553 Context.IntTy, Loc); 3554 } 3555 3556 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3557 QualType Ty, SourceLocation Loc) { 3558 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3559 3560 using llvm::APFloat; 3561 APFloat Val(Format); 3562 3563 APFloat::opStatus result = Literal.GetFloatValue(Val); 3564 3565 // Overflow is always an error, but underflow is only an error if 3566 // we underflowed to zero (APFloat reports denormals as underflow). 3567 if ((result & APFloat::opOverflow) || 3568 ((result & APFloat::opUnderflow) && Val.isZero())) { 3569 unsigned diagnostic; 3570 SmallString<20> buffer; 3571 if (result & APFloat::opOverflow) { 3572 diagnostic = diag::warn_float_overflow; 3573 APFloat::getLargest(Format).toString(buffer); 3574 } else { 3575 diagnostic = diag::warn_float_underflow; 3576 APFloat::getSmallest(Format).toString(buffer); 3577 } 3578 3579 S.Diag(Loc, diagnostic) 3580 << Ty 3581 << StringRef(buffer.data(), buffer.size()); 3582 } 3583 3584 bool isExact = (result == APFloat::opOK); 3585 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3586 } 3587 3588 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3589 assert(E && "Invalid expression"); 3590 3591 if (E->isValueDependent()) 3592 return false; 3593 3594 QualType QT = E->getType(); 3595 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3596 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3597 return true; 3598 } 3599 3600 llvm::APSInt ValueAPS; 3601 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3602 3603 if (R.isInvalid()) 3604 return true; 3605 3606 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3607 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3608 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3609 << ValueAPS.toString(10) << ValueIsPositive; 3610 return true; 3611 } 3612 3613 return false; 3614 } 3615 3616 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3617 // Fast path for a single digit (which is quite common). A single digit 3618 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3619 if (Tok.getLength() == 1) { 3620 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3621 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3622 } 3623 3624 SmallString<128> SpellingBuffer; 3625 // NumericLiteralParser wants to overread by one character. Add padding to 3626 // the buffer in case the token is copied to the buffer. If getSpelling() 3627 // returns a StringRef to the memory buffer, it should have a null char at 3628 // the EOF, so it is also safe. 3629 SpellingBuffer.resize(Tok.getLength() + 1); 3630 3631 // Get the spelling of the token, which eliminates trigraphs, etc. 3632 bool Invalid = false; 3633 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3634 if (Invalid) 3635 return ExprError(); 3636 3637 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3638 PP.getSourceManager(), PP.getLangOpts(), 3639 PP.getTargetInfo(), PP.getDiagnostics()); 3640 if (Literal.hadError) 3641 return ExprError(); 3642 3643 if (Literal.hasUDSuffix()) { 3644 // We're building a user-defined literal. 3645 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3646 SourceLocation UDSuffixLoc = 3647 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3648 3649 // Make sure we're allowed user-defined literals here. 3650 if (!UDLScope) 3651 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3652 3653 QualType CookedTy; 3654 if (Literal.isFloatingLiteral()) { 3655 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3656 // long double, the literal is treated as a call of the form 3657 // operator "" X (f L) 3658 CookedTy = Context.LongDoubleTy; 3659 } else { 3660 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3661 // unsigned long long, the literal is treated as a call of the form 3662 // operator "" X (n ULL) 3663 CookedTy = Context.UnsignedLongLongTy; 3664 } 3665 3666 DeclarationName OpName = 3667 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3668 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3669 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3670 3671 SourceLocation TokLoc = Tok.getLocation(); 3672 3673 // Perform literal operator lookup to determine if we're building a raw 3674 // literal or a cooked one. 3675 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3676 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3677 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3678 /*AllowStringTemplate*/ false, 3679 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3680 case LOLR_ErrorNoDiagnostic: 3681 // Lookup failure for imaginary constants isn't fatal, there's still the 3682 // GNU extension producing _Complex types. 3683 break; 3684 case LOLR_Error: 3685 return ExprError(); 3686 case LOLR_Cooked: { 3687 Expr *Lit; 3688 if (Literal.isFloatingLiteral()) { 3689 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3690 } else { 3691 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3692 if (Literal.GetIntegerValue(ResultVal)) 3693 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3694 << /* Unsigned */ 1; 3695 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3696 Tok.getLocation()); 3697 } 3698 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3699 } 3700 3701 case LOLR_Raw: { 3702 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3703 // literal is treated as a call of the form 3704 // operator "" X ("n") 3705 unsigned Length = Literal.getUDSuffixOffset(); 3706 QualType StrTy = Context.getConstantArrayType( 3707 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3708 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3709 Expr *Lit = StringLiteral::Create( 3710 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3711 /*Pascal*/false, StrTy, &TokLoc, 1); 3712 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3713 } 3714 3715 case LOLR_Template: { 3716 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3717 // template), L is treated as a call fo the form 3718 // operator "" X <'c1', 'c2', ... 'ck'>() 3719 // where n is the source character sequence c1 c2 ... ck. 3720 TemplateArgumentListInfo ExplicitArgs; 3721 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3722 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3723 llvm::APSInt Value(CharBits, CharIsUnsigned); 3724 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3725 Value = TokSpelling[I]; 3726 TemplateArgument Arg(Context, Value, Context.CharTy); 3727 TemplateArgumentLocInfo ArgInfo; 3728 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3729 } 3730 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3731 &ExplicitArgs); 3732 } 3733 case LOLR_StringTemplate: 3734 llvm_unreachable("unexpected literal operator lookup result"); 3735 } 3736 } 3737 3738 Expr *Res; 3739 3740 if (Literal.isFixedPointLiteral()) { 3741 QualType Ty; 3742 3743 if (Literal.isAccum) { 3744 if (Literal.isHalf) { 3745 Ty = Context.ShortAccumTy; 3746 } else if (Literal.isLong) { 3747 Ty = Context.LongAccumTy; 3748 } else { 3749 Ty = Context.AccumTy; 3750 } 3751 } else if (Literal.isFract) { 3752 if (Literal.isHalf) { 3753 Ty = Context.ShortFractTy; 3754 } else if (Literal.isLong) { 3755 Ty = Context.LongFractTy; 3756 } else { 3757 Ty = Context.FractTy; 3758 } 3759 } 3760 3761 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3762 3763 bool isSigned = !Literal.isUnsigned; 3764 unsigned scale = Context.getFixedPointScale(Ty); 3765 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3766 3767 llvm::APInt Val(bit_width, 0, isSigned); 3768 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3769 bool ValIsZero = Val.isNullValue() && !Overflowed; 3770 3771 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3772 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3773 // Clause 6.4.4 - The value of a constant shall be in the range of 3774 // representable values for its type, with exception for constants of a 3775 // fract type with a value of exactly 1; such a constant shall denote 3776 // the maximal value for the type. 3777 --Val; 3778 else if (Val.ugt(MaxVal) || Overflowed) 3779 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3780 3781 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3782 Tok.getLocation(), scale); 3783 } else if (Literal.isFloatingLiteral()) { 3784 QualType Ty; 3785 if (Literal.isHalf){ 3786 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3787 Ty = Context.HalfTy; 3788 else { 3789 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3790 return ExprError(); 3791 } 3792 } else if (Literal.isFloat) 3793 Ty = Context.FloatTy; 3794 else if (Literal.isLong) 3795 Ty = Context.LongDoubleTy; 3796 else if (Literal.isFloat16) 3797 Ty = Context.Float16Ty; 3798 else if (Literal.isFloat128) 3799 Ty = Context.Float128Ty; 3800 else 3801 Ty = Context.DoubleTy; 3802 3803 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3804 3805 if (Ty == Context.DoubleTy) { 3806 if (getLangOpts().SinglePrecisionConstants) { 3807 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3808 if (BTy->getKind() != BuiltinType::Float) { 3809 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3810 } 3811 } else if (getLangOpts().OpenCL && 3812 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3813 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3814 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3815 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3816 } 3817 } 3818 } else if (!Literal.isIntegerLiteral()) { 3819 return ExprError(); 3820 } else { 3821 QualType Ty; 3822 3823 // 'long long' is a C99 or C++11 feature. 3824 if (!getLangOpts().C99 && Literal.isLongLong) { 3825 if (getLangOpts().CPlusPlus) 3826 Diag(Tok.getLocation(), 3827 getLangOpts().CPlusPlus11 ? 3828 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3829 else 3830 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3831 } 3832 3833 // Get the value in the widest-possible width. 3834 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3835 llvm::APInt ResultVal(MaxWidth, 0); 3836 3837 if (Literal.GetIntegerValue(ResultVal)) { 3838 // If this value didn't fit into uintmax_t, error and force to ull. 3839 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3840 << /* Unsigned */ 1; 3841 Ty = Context.UnsignedLongLongTy; 3842 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3843 "long long is not intmax_t?"); 3844 } else { 3845 // If this value fits into a ULL, try to figure out what else it fits into 3846 // according to the rules of C99 6.4.4.1p5. 3847 3848 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3849 // be an unsigned int. 3850 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3851 3852 // Check from smallest to largest, picking the smallest type we can. 3853 unsigned Width = 0; 3854 3855 // Microsoft specific integer suffixes are explicitly sized. 3856 if (Literal.MicrosoftInteger) { 3857 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3858 Width = 8; 3859 Ty = Context.CharTy; 3860 } else { 3861 Width = Literal.MicrosoftInteger; 3862 Ty = Context.getIntTypeForBitwidth(Width, 3863 /*Signed=*/!Literal.isUnsigned); 3864 } 3865 } 3866 3867 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3868 // Are int/unsigned possibilities? 3869 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3870 3871 // Does it fit in a unsigned int? 3872 if (ResultVal.isIntN(IntSize)) { 3873 // Does it fit in a signed int? 3874 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3875 Ty = Context.IntTy; 3876 else if (AllowUnsigned) 3877 Ty = Context.UnsignedIntTy; 3878 Width = IntSize; 3879 } 3880 } 3881 3882 // Are long/unsigned long possibilities? 3883 if (Ty.isNull() && !Literal.isLongLong) { 3884 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3885 3886 // Does it fit in a unsigned long? 3887 if (ResultVal.isIntN(LongSize)) { 3888 // Does it fit in a signed long? 3889 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3890 Ty = Context.LongTy; 3891 else if (AllowUnsigned) 3892 Ty = Context.UnsignedLongTy; 3893 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3894 // is compatible. 3895 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3896 const unsigned LongLongSize = 3897 Context.getTargetInfo().getLongLongWidth(); 3898 Diag(Tok.getLocation(), 3899 getLangOpts().CPlusPlus 3900 ? Literal.isLong 3901 ? diag::warn_old_implicitly_unsigned_long_cxx 3902 : /*C++98 UB*/ diag:: 3903 ext_old_implicitly_unsigned_long_cxx 3904 : diag::warn_old_implicitly_unsigned_long) 3905 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3906 : /*will be ill-formed*/ 1); 3907 Ty = Context.UnsignedLongTy; 3908 } 3909 Width = LongSize; 3910 } 3911 } 3912 3913 // Check long long if needed. 3914 if (Ty.isNull()) { 3915 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3916 3917 // Does it fit in a unsigned long long? 3918 if (ResultVal.isIntN(LongLongSize)) { 3919 // Does it fit in a signed long long? 3920 // To be compatible with MSVC, hex integer literals ending with the 3921 // LL or i64 suffix are always signed in Microsoft mode. 3922 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3923 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3924 Ty = Context.LongLongTy; 3925 else if (AllowUnsigned) 3926 Ty = Context.UnsignedLongLongTy; 3927 Width = LongLongSize; 3928 } 3929 } 3930 3931 // If we still couldn't decide a type, we probably have something that 3932 // does not fit in a signed long long, but has no U suffix. 3933 if (Ty.isNull()) { 3934 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3935 Ty = Context.UnsignedLongLongTy; 3936 Width = Context.getTargetInfo().getLongLongWidth(); 3937 } 3938 3939 if (ResultVal.getBitWidth() != Width) 3940 ResultVal = ResultVal.trunc(Width); 3941 } 3942 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3943 } 3944 3945 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3946 if (Literal.isImaginary) { 3947 Res = new (Context) ImaginaryLiteral(Res, 3948 Context.getComplexType(Res->getType())); 3949 3950 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3951 } 3952 return Res; 3953 } 3954 3955 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3956 assert(E && "ActOnParenExpr() missing expr"); 3957 return new (Context) ParenExpr(L, R, E); 3958 } 3959 3960 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3961 SourceLocation Loc, 3962 SourceRange ArgRange) { 3963 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3964 // scalar or vector data type argument..." 3965 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3966 // type (C99 6.2.5p18) or void. 3967 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3968 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3969 << T << ArgRange; 3970 return true; 3971 } 3972 3973 assert((T->isVoidType() || !T->isIncompleteType()) && 3974 "Scalar types should always be complete"); 3975 return false; 3976 } 3977 3978 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3979 SourceLocation Loc, 3980 SourceRange ArgRange, 3981 UnaryExprOrTypeTrait TraitKind) { 3982 // Invalid types must be hard errors for SFINAE in C++. 3983 if (S.LangOpts.CPlusPlus) 3984 return true; 3985 3986 // C99 6.5.3.4p1: 3987 if (T->isFunctionType() && 3988 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3989 TraitKind == UETT_PreferredAlignOf)) { 3990 // sizeof(function)/alignof(function) is allowed as an extension. 3991 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3992 << getTraitSpelling(TraitKind) << ArgRange; 3993 return false; 3994 } 3995 3996 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3997 // this is an error (OpenCL v1.1 s6.3.k) 3998 if (T->isVoidType()) { 3999 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4000 : diag::ext_sizeof_alignof_void_type; 4001 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4002 return false; 4003 } 4004 4005 return true; 4006 } 4007 4008 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4009 SourceLocation Loc, 4010 SourceRange ArgRange, 4011 UnaryExprOrTypeTrait TraitKind) { 4012 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4013 // runtime doesn't allow it. 4014 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4015 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4016 << T << (TraitKind == UETT_SizeOf) 4017 << ArgRange; 4018 return true; 4019 } 4020 4021 return false; 4022 } 4023 4024 /// Check whether E is a pointer from a decayed array type (the decayed 4025 /// pointer type is equal to T) and emit a warning if it is. 4026 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4027 Expr *E) { 4028 // Don't warn if the operation changed the type. 4029 if (T != E->getType()) 4030 return; 4031 4032 // Now look for array decays. 4033 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4034 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4035 return; 4036 4037 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4038 << ICE->getType() 4039 << ICE->getSubExpr()->getType(); 4040 } 4041 4042 /// Check the constraints on expression operands to unary type expression 4043 /// and type traits. 4044 /// 4045 /// Completes any types necessary and validates the constraints on the operand 4046 /// expression. The logic mostly mirrors the type-based overload, but may modify 4047 /// the expression as it completes the type for that expression through template 4048 /// instantiation, etc. 4049 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4050 UnaryExprOrTypeTrait ExprKind) { 4051 QualType ExprTy = E->getType(); 4052 assert(!ExprTy->isReferenceType()); 4053 4054 bool IsUnevaluatedOperand = 4055 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4056 ExprKind == UETT_PreferredAlignOf); 4057 if (IsUnevaluatedOperand) { 4058 ExprResult Result = CheckUnevaluatedOperand(E); 4059 if (Result.isInvalid()) 4060 return true; 4061 E = Result.get(); 4062 } 4063 4064 if (ExprKind == UETT_VecStep) 4065 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4066 E->getSourceRange()); 4067 4068 // Explicitly list some types as extensions. 4069 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4070 E->getSourceRange(), ExprKind)) 4071 return false; 4072 4073 // 'alignof' applied to an expression only requires the base element type of 4074 // the expression to be complete. 'sizeof' requires the expression's type to 4075 // be complete (and will attempt to complete it if it's an array of unknown 4076 // bound). 4077 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4078 if (RequireCompleteSizedType( 4079 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4080 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4081 getTraitSpelling(ExprKind), E->getSourceRange())) 4082 return true; 4083 } else { 4084 if (RequireCompleteSizedExprType( 4085 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4086 getTraitSpelling(ExprKind), E->getSourceRange())) 4087 return true; 4088 } 4089 4090 // Completing the expression's type may have changed it. 4091 ExprTy = E->getType(); 4092 assert(!ExprTy->isReferenceType()); 4093 4094 if (ExprTy->isFunctionType()) { 4095 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4096 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4097 return true; 4098 } 4099 4100 // The operand for sizeof and alignof is in an unevaluated expression context, 4101 // so side effects could result in unintended consequences. 4102 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4103 E->HasSideEffects(Context, false)) 4104 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4105 4106 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4107 E->getSourceRange(), ExprKind)) 4108 return true; 4109 4110 if (ExprKind == UETT_SizeOf) { 4111 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4112 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4113 QualType OType = PVD->getOriginalType(); 4114 QualType Type = PVD->getType(); 4115 if (Type->isPointerType() && OType->isArrayType()) { 4116 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4117 << Type << OType; 4118 Diag(PVD->getLocation(), diag::note_declared_at); 4119 } 4120 } 4121 } 4122 4123 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4124 // decays into a pointer and returns an unintended result. This is most 4125 // likely a typo for "sizeof(array) op x". 4126 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4127 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4128 BO->getLHS()); 4129 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4130 BO->getRHS()); 4131 } 4132 } 4133 4134 return false; 4135 } 4136 4137 /// Check the constraints on operands to unary expression and type 4138 /// traits. 4139 /// 4140 /// This will complete any types necessary, and validate the various constraints 4141 /// on those operands. 4142 /// 4143 /// The UsualUnaryConversions() function is *not* called by this routine. 4144 /// C99 6.3.2.1p[2-4] all state: 4145 /// Except when it is the operand of the sizeof operator ... 4146 /// 4147 /// C++ [expr.sizeof]p4 4148 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4149 /// standard conversions are not applied to the operand of sizeof. 4150 /// 4151 /// This policy is followed for all of the unary trait expressions. 4152 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4153 SourceLocation OpLoc, 4154 SourceRange ExprRange, 4155 UnaryExprOrTypeTrait ExprKind) { 4156 if (ExprType->isDependentType()) 4157 return false; 4158 4159 // C++ [expr.sizeof]p2: 4160 // When applied to a reference or a reference type, the result 4161 // is the size of the referenced type. 4162 // C++11 [expr.alignof]p3: 4163 // When alignof is applied to a reference type, the result 4164 // shall be the alignment of the referenced type. 4165 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4166 ExprType = Ref->getPointeeType(); 4167 4168 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4169 // When alignof or _Alignof is applied to an array type, the result 4170 // is the alignment of the element type. 4171 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4172 ExprKind == UETT_OpenMPRequiredSimdAlign) 4173 ExprType = Context.getBaseElementType(ExprType); 4174 4175 if (ExprKind == UETT_VecStep) 4176 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4177 4178 // Explicitly list some types as extensions. 4179 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4180 ExprKind)) 4181 return false; 4182 4183 if (RequireCompleteSizedType( 4184 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4185 getTraitSpelling(ExprKind), ExprRange)) 4186 return true; 4187 4188 if (ExprType->isFunctionType()) { 4189 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4190 << getTraitSpelling(ExprKind) << ExprRange; 4191 return true; 4192 } 4193 4194 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4195 ExprKind)) 4196 return true; 4197 4198 return false; 4199 } 4200 4201 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4202 // Cannot know anything else if the expression is dependent. 4203 if (E->isTypeDependent()) 4204 return false; 4205 4206 if (E->getObjectKind() == OK_BitField) { 4207 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4208 << 1 << E->getSourceRange(); 4209 return true; 4210 } 4211 4212 ValueDecl *D = nullptr; 4213 Expr *Inner = E->IgnoreParens(); 4214 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4215 D = DRE->getDecl(); 4216 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4217 D = ME->getMemberDecl(); 4218 } 4219 4220 // If it's a field, require the containing struct to have a 4221 // complete definition so that we can compute the layout. 4222 // 4223 // This can happen in C++11 onwards, either by naming the member 4224 // in a way that is not transformed into a member access expression 4225 // (in an unevaluated operand, for instance), or by naming the member 4226 // in a trailing-return-type. 4227 // 4228 // For the record, since __alignof__ on expressions is a GCC 4229 // extension, GCC seems to permit this but always gives the 4230 // nonsensical answer 0. 4231 // 4232 // We don't really need the layout here --- we could instead just 4233 // directly check for all the appropriate alignment-lowing 4234 // attributes --- but that would require duplicating a lot of 4235 // logic that just isn't worth duplicating for such a marginal 4236 // use-case. 4237 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4238 // Fast path this check, since we at least know the record has a 4239 // definition if we can find a member of it. 4240 if (!FD->getParent()->isCompleteDefinition()) { 4241 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4242 << E->getSourceRange(); 4243 return true; 4244 } 4245 4246 // Otherwise, if it's a field, and the field doesn't have 4247 // reference type, then it must have a complete type (or be a 4248 // flexible array member, which we explicitly want to 4249 // white-list anyway), which makes the following checks trivial. 4250 if (!FD->getType()->isReferenceType()) 4251 return false; 4252 } 4253 4254 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4255 } 4256 4257 bool Sema::CheckVecStepExpr(Expr *E) { 4258 E = E->IgnoreParens(); 4259 4260 // Cannot know anything else if the expression is dependent. 4261 if (E->isTypeDependent()) 4262 return false; 4263 4264 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4265 } 4266 4267 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4268 CapturingScopeInfo *CSI) { 4269 assert(T->isVariablyModifiedType()); 4270 assert(CSI != nullptr); 4271 4272 // We're going to walk down into the type and look for VLA expressions. 4273 do { 4274 const Type *Ty = T.getTypePtr(); 4275 switch (Ty->getTypeClass()) { 4276 #define TYPE(Class, Base) 4277 #define ABSTRACT_TYPE(Class, Base) 4278 #define NON_CANONICAL_TYPE(Class, Base) 4279 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4280 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4281 #include "clang/AST/TypeNodes.inc" 4282 T = QualType(); 4283 break; 4284 // These types are never variably-modified. 4285 case Type::Builtin: 4286 case Type::Complex: 4287 case Type::Vector: 4288 case Type::ExtVector: 4289 case Type::ConstantMatrix: 4290 case Type::Record: 4291 case Type::Enum: 4292 case Type::Elaborated: 4293 case Type::TemplateSpecialization: 4294 case Type::ObjCObject: 4295 case Type::ObjCInterface: 4296 case Type::ObjCObjectPointer: 4297 case Type::ObjCTypeParam: 4298 case Type::Pipe: 4299 case Type::ExtInt: 4300 llvm_unreachable("type class is never variably-modified!"); 4301 case Type::Adjusted: 4302 T = cast<AdjustedType>(Ty)->getOriginalType(); 4303 break; 4304 case Type::Decayed: 4305 T = cast<DecayedType>(Ty)->getPointeeType(); 4306 break; 4307 case Type::Pointer: 4308 T = cast<PointerType>(Ty)->getPointeeType(); 4309 break; 4310 case Type::BlockPointer: 4311 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4312 break; 4313 case Type::LValueReference: 4314 case Type::RValueReference: 4315 T = cast<ReferenceType>(Ty)->getPointeeType(); 4316 break; 4317 case Type::MemberPointer: 4318 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4319 break; 4320 case Type::ConstantArray: 4321 case Type::IncompleteArray: 4322 // Losing element qualification here is fine. 4323 T = cast<ArrayType>(Ty)->getElementType(); 4324 break; 4325 case Type::VariableArray: { 4326 // Losing element qualification here is fine. 4327 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4328 4329 // Unknown size indication requires no size computation. 4330 // Otherwise, evaluate and record it. 4331 auto Size = VAT->getSizeExpr(); 4332 if (Size && !CSI->isVLATypeCaptured(VAT) && 4333 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4334 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4335 4336 T = VAT->getElementType(); 4337 break; 4338 } 4339 case Type::FunctionProto: 4340 case Type::FunctionNoProto: 4341 T = cast<FunctionType>(Ty)->getReturnType(); 4342 break; 4343 case Type::Paren: 4344 case Type::TypeOf: 4345 case Type::UnaryTransform: 4346 case Type::Attributed: 4347 case Type::SubstTemplateTypeParm: 4348 case Type::PackExpansion: 4349 case Type::MacroQualified: 4350 // Keep walking after single level desugaring. 4351 T = T.getSingleStepDesugaredType(Context); 4352 break; 4353 case Type::Typedef: 4354 T = cast<TypedefType>(Ty)->desugar(); 4355 break; 4356 case Type::Decltype: 4357 T = cast<DecltypeType>(Ty)->desugar(); 4358 break; 4359 case Type::Auto: 4360 case Type::DeducedTemplateSpecialization: 4361 T = cast<DeducedType>(Ty)->getDeducedType(); 4362 break; 4363 case Type::TypeOfExpr: 4364 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4365 break; 4366 case Type::Atomic: 4367 T = cast<AtomicType>(Ty)->getValueType(); 4368 break; 4369 } 4370 } while (!T.isNull() && T->isVariablyModifiedType()); 4371 } 4372 4373 /// Build a sizeof or alignof expression given a type operand. 4374 ExprResult 4375 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4376 SourceLocation OpLoc, 4377 UnaryExprOrTypeTrait ExprKind, 4378 SourceRange R) { 4379 if (!TInfo) 4380 return ExprError(); 4381 4382 QualType T = TInfo->getType(); 4383 4384 if (!T->isDependentType() && 4385 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4386 return ExprError(); 4387 4388 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4389 if (auto *TT = T->getAs<TypedefType>()) { 4390 for (auto I = FunctionScopes.rbegin(), 4391 E = std::prev(FunctionScopes.rend()); 4392 I != E; ++I) { 4393 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4394 if (CSI == nullptr) 4395 break; 4396 DeclContext *DC = nullptr; 4397 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4398 DC = LSI->CallOperator; 4399 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4400 DC = CRSI->TheCapturedDecl; 4401 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4402 DC = BSI->TheDecl; 4403 if (DC) { 4404 if (DC->containsDecl(TT->getDecl())) 4405 break; 4406 captureVariablyModifiedType(Context, T, CSI); 4407 } 4408 } 4409 } 4410 } 4411 4412 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4413 return new (Context) UnaryExprOrTypeTraitExpr( 4414 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4415 } 4416 4417 /// Build a sizeof or alignof expression given an expression 4418 /// operand. 4419 ExprResult 4420 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4421 UnaryExprOrTypeTrait ExprKind) { 4422 ExprResult PE = CheckPlaceholderExpr(E); 4423 if (PE.isInvalid()) 4424 return ExprError(); 4425 4426 E = PE.get(); 4427 4428 // Verify that the operand is valid. 4429 bool isInvalid = false; 4430 if (E->isTypeDependent()) { 4431 // Delay type-checking for type-dependent expressions. 4432 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4433 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4434 } else if (ExprKind == UETT_VecStep) { 4435 isInvalid = CheckVecStepExpr(E); 4436 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4437 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4438 isInvalid = true; 4439 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4440 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4441 isInvalid = true; 4442 } else { 4443 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4444 } 4445 4446 if (isInvalid) 4447 return ExprError(); 4448 4449 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4450 PE = TransformToPotentiallyEvaluated(E); 4451 if (PE.isInvalid()) return ExprError(); 4452 E = PE.get(); 4453 } 4454 4455 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4456 return new (Context) UnaryExprOrTypeTraitExpr( 4457 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4458 } 4459 4460 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4461 /// expr and the same for @c alignof and @c __alignof 4462 /// Note that the ArgRange is invalid if isType is false. 4463 ExprResult 4464 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4465 UnaryExprOrTypeTrait ExprKind, bool IsType, 4466 void *TyOrEx, SourceRange ArgRange) { 4467 // If error parsing type, ignore. 4468 if (!TyOrEx) return ExprError(); 4469 4470 if (IsType) { 4471 TypeSourceInfo *TInfo; 4472 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4473 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4474 } 4475 4476 Expr *ArgEx = (Expr *)TyOrEx; 4477 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4478 return Result; 4479 } 4480 4481 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4482 bool IsReal) { 4483 if (V.get()->isTypeDependent()) 4484 return S.Context.DependentTy; 4485 4486 // _Real and _Imag are only l-values for normal l-values. 4487 if (V.get()->getObjectKind() != OK_Ordinary) { 4488 V = S.DefaultLvalueConversion(V.get()); 4489 if (V.isInvalid()) 4490 return QualType(); 4491 } 4492 4493 // These operators return the element type of a complex type. 4494 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4495 return CT->getElementType(); 4496 4497 // Otherwise they pass through real integer and floating point types here. 4498 if (V.get()->getType()->isArithmeticType()) 4499 return V.get()->getType(); 4500 4501 // Test for placeholders. 4502 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4503 if (PR.isInvalid()) return QualType(); 4504 if (PR.get() != V.get()) { 4505 V = PR; 4506 return CheckRealImagOperand(S, V, Loc, IsReal); 4507 } 4508 4509 // Reject anything else. 4510 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4511 << (IsReal ? "__real" : "__imag"); 4512 return QualType(); 4513 } 4514 4515 4516 4517 ExprResult 4518 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4519 tok::TokenKind Kind, Expr *Input) { 4520 UnaryOperatorKind Opc; 4521 switch (Kind) { 4522 default: llvm_unreachable("Unknown unary op!"); 4523 case tok::plusplus: Opc = UO_PostInc; break; 4524 case tok::minusminus: Opc = UO_PostDec; break; 4525 } 4526 4527 // Since this might is a postfix expression, get rid of ParenListExprs. 4528 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4529 if (Result.isInvalid()) return ExprError(); 4530 Input = Result.get(); 4531 4532 return BuildUnaryOp(S, OpLoc, Opc, Input); 4533 } 4534 4535 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4536 /// 4537 /// \return true on error 4538 static bool checkArithmeticOnObjCPointer(Sema &S, 4539 SourceLocation opLoc, 4540 Expr *op) { 4541 assert(op->getType()->isObjCObjectPointerType()); 4542 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4543 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4544 return false; 4545 4546 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4547 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4548 << op->getSourceRange(); 4549 return true; 4550 } 4551 4552 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4553 auto *BaseNoParens = Base->IgnoreParens(); 4554 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4555 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4556 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4557 } 4558 4559 ExprResult 4560 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4561 Expr *idx, SourceLocation rbLoc) { 4562 if (base && !base->getType().isNull() && 4563 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4564 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4565 SourceLocation(), /*Length*/ nullptr, 4566 /*Stride=*/nullptr, rbLoc); 4567 4568 // Since this might be a postfix expression, get rid of ParenListExprs. 4569 if (isa<ParenListExpr>(base)) { 4570 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4571 if (result.isInvalid()) return ExprError(); 4572 base = result.get(); 4573 } 4574 4575 // Check if base and idx form a MatrixSubscriptExpr. 4576 // 4577 // Helper to check for comma expressions, which are not allowed as indices for 4578 // matrix subscript expressions. 4579 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4580 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4581 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4582 << SourceRange(base->getBeginLoc(), rbLoc); 4583 return true; 4584 } 4585 return false; 4586 }; 4587 // The matrix subscript operator ([][])is considered a single operator. 4588 // Separating the index expressions by parenthesis is not allowed. 4589 if (base->getType()->isSpecificPlaceholderType( 4590 BuiltinType::IncompleteMatrixIdx) && 4591 !isa<MatrixSubscriptExpr>(base)) { 4592 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4593 << SourceRange(base->getBeginLoc(), rbLoc); 4594 return ExprError(); 4595 } 4596 // If the base is either a MatrixSubscriptExpr or a matrix type, try to create 4597 // a new MatrixSubscriptExpr. 4598 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4599 if (matSubscriptE) { 4600 if (CheckAndReportCommaError(idx)) 4601 return ExprError(); 4602 4603 assert(matSubscriptE->isIncomplete() && 4604 "base has to be an incomplete matrix subscript"); 4605 return CreateBuiltinMatrixSubscriptExpr( 4606 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4607 } 4608 Expr *matrixBase = base; 4609 bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4610 if (!IsMSPropertySubscript) { 4611 ExprResult result = CheckPlaceholderExpr(base); 4612 if (!result.isInvalid()) 4613 matrixBase = result.get(); 4614 } 4615 if (matrixBase->getType()->isMatrixType()) { 4616 if (CheckAndReportCommaError(idx)) 4617 return ExprError(); 4618 4619 return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc); 4620 } 4621 4622 // A comma-expression as the index is deprecated in C++2a onwards. 4623 if (getLangOpts().CPlusPlus20 && 4624 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4625 (isa<CXXOperatorCallExpr>(idx) && 4626 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4627 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4628 << SourceRange(base->getBeginLoc(), rbLoc); 4629 } 4630 4631 // Handle any non-overload placeholder types in the base and index 4632 // expressions. We can't handle overloads here because the other 4633 // operand might be an overloadable type, in which case the overload 4634 // resolution for the operator overload should get the first crack 4635 // at the overload. 4636 if (base->getType()->isNonOverloadPlaceholderType()) { 4637 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4638 if (!IsMSPropertySubscript) { 4639 ExprResult result = CheckPlaceholderExpr(base); 4640 if (result.isInvalid()) 4641 return ExprError(); 4642 base = result.get(); 4643 } 4644 } 4645 if (idx->getType()->isNonOverloadPlaceholderType()) { 4646 ExprResult result = CheckPlaceholderExpr(idx); 4647 if (result.isInvalid()) return ExprError(); 4648 idx = result.get(); 4649 } 4650 4651 // Build an unanalyzed expression if either operand is type-dependent. 4652 if (getLangOpts().CPlusPlus && 4653 (base->isTypeDependent() || idx->isTypeDependent())) { 4654 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4655 VK_LValue, OK_Ordinary, rbLoc); 4656 } 4657 4658 // MSDN, property (C++) 4659 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4660 // This attribute can also be used in the declaration of an empty array in a 4661 // class or structure definition. For example: 4662 // __declspec(property(get=GetX, put=PutX)) int x[]; 4663 // The above statement indicates that x[] can be used with one or more array 4664 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4665 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4666 if (IsMSPropertySubscript) { 4667 // Build MS property subscript expression if base is MS property reference 4668 // or MS property subscript. 4669 return new (Context) MSPropertySubscriptExpr( 4670 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4671 } 4672 4673 // Use C++ overloaded-operator rules if either operand has record 4674 // type. The spec says to do this if either type is *overloadable*, 4675 // but enum types can't declare subscript operators or conversion 4676 // operators, so there's nothing interesting for overload resolution 4677 // to do if there aren't any record types involved. 4678 // 4679 // ObjC pointers have their own subscripting logic that is not tied 4680 // to overload resolution and so should not take this path. 4681 if (getLangOpts().CPlusPlus && 4682 (base->getType()->isRecordType() || 4683 (!base->getType()->isObjCObjectPointerType() && 4684 idx->getType()->isRecordType()))) { 4685 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4686 } 4687 4688 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4689 4690 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4691 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4692 4693 return Res; 4694 } 4695 4696 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4697 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4698 InitializationKind Kind = 4699 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4700 InitializationSequence InitSeq(*this, Entity, Kind, E); 4701 return InitSeq.Perform(*this, Entity, Kind, E); 4702 } 4703 4704 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4705 Expr *ColumnIdx, 4706 SourceLocation RBLoc) { 4707 ExprResult BaseR = CheckPlaceholderExpr(Base); 4708 if (BaseR.isInvalid()) 4709 return BaseR; 4710 Base = BaseR.get(); 4711 4712 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4713 if (RowR.isInvalid()) 4714 return RowR; 4715 RowIdx = RowR.get(); 4716 4717 if (!ColumnIdx) 4718 return new (Context) MatrixSubscriptExpr( 4719 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4720 4721 // Build an unanalyzed expression if any of the operands is type-dependent. 4722 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4723 ColumnIdx->isTypeDependent()) 4724 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4725 Context.DependentTy, RBLoc); 4726 4727 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4728 if (ColumnR.isInvalid()) 4729 return ColumnR; 4730 ColumnIdx = ColumnR.get(); 4731 4732 // Check that IndexExpr is an integer expression. If it is a constant 4733 // expression, check that it is less than Dim (= the number of elements in the 4734 // corresponding dimension). 4735 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4736 bool IsColumnIdx) -> Expr * { 4737 if (!IndexExpr->getType()->isIntegerType() && 4738 !IndexExpr->isTypeDependent()) { 4739 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4740 << IsColumnIdx; 4741 return nullptr; 4742 } 4743 4744 llvm::APSInt Idx; 4745 if (IndexExpr->isIntegerConstantExpr(Idx, Context) && 4746 (Idx < 0 || Idx >= Dim)) { 4747 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4748 << IsColumnIdx << Dim; 4749 return nullptr; 4750 } 4751 4752 ExprResult ConvExpr = 4753 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4754 assert(!ConvExpr.isInvalid() && 4755 "should be able to convert any integer type to size type"); 4756 return ConvExpr.get(); 4757 }; 4758 4759 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4760 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4761 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4762 if (!RowIdx || !ColumnIdx) 4763 return ExprError(); 4764 4765 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4766 MTy->getElementType(), RBLoc); 4767 } 4768 4769 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4770 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4771 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4772 4773 // For expressions like `&(*s).b`, the base is recorded and what should be 4774 // checked. 4775 const MemberExpr *Member = nullptr; 4776 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4777 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4778 4779 LastRecord.PossibleDerefs.erase(StrippedExpr); 4780 } 4781 4782 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4783 QualType ResultTy = E->getType(); 4784 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4785 4786 // Bail if the element is an array since it is not memory access. 4787 if (isa<ArrayType>(ResultTy)) 4788 return; 4789 4790 if (ResultTy->hasAttr(attr::NoDeref)) { 4791 LastRecord.PossibleDerefs.insert(E); 4792 return; 4793 } 4794 4795 // Check if the base type is a pointer to a member access of a struct 4796 // marked with noderef. 4797 const Expr *Base = E->getBase(); 4798 QualType BaseTy = Base->getType(); 4799 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4800 // Not a pointer access 4801 return; 4802 4803 const MemberExpr *Member = nullptr; 4804 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4805 Member->isArrow()) 4806 Base = Member->getBase(); 4807 4808 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4809 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4810 LastRecord.PossibleDerefs.insert(E); 4811 } 4812 } 4813 4814 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4815 Expr *LowerBound, 4816 SourceLocation ColonLocFirst, 4817 SourceLocation ColonLocSecond, 4818 Expr *Length, Expr *Stride, 4819 SourceLocation RBLoc) { 4820 if (Base->getType()->isPlaceholderType() && 4821 !Base->getType()->isSpecificPlaceholderType( 4822 BuiltinType::OMPArraySection)) { 4823 ExprResult Result = CheckPlaceholderExpr(Base); 4824 if (Result.isInvalid()) 4825 return ExprError(); 4826 Base = Result.get(); 4827 } 4828 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4829 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4830 if (Result.isInvalid()) 4831 return ExprError(); 4832 Result = DefaultLvalueConversion(Result.get()); 4833 if (Result.isInvalid()) 4834 return ExprError(); 4835 LowerBound = Result.get(); 4836 } 4837 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4838 ExprResult Result = CheckPlaceholderExpr(Length); 4839 if (Result.isInvalid()) 4840 return ExprError(); 4841 Result = DefaultLvalueConversion(Result.get()); 4842 if (Result.isInvalid()) 4843 return ExprError(); 4844 Length = Result.get(); 4845 } 4846 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4847 ExprResult Result = CheckPlaceholderExpr(Stride); 4848 if (Result.isInvalid()) 4849 return ExprError(); 4850 Result = DefaultLvalueConversion(Result.get()); 4851 if (Result.isInvalid()) 4852 return ExprError(); 4853 Stride = Result.get(); 4854 } 4855 4856 // Build an unanalyzed expression if either operand is type-dependent. 4857 if (Base->isTypeDependent() || 4858 (LowerBound && 4859 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4860 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4861 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4862 return new (Context) OMPArraySectionExpr( 4863 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4864 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4865 } 4866 4867 // Perform default conversions. 4868 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4869 QualType ResultTy; 4870 if (OriginalTy->isAnyPointerType()) { 4871 ResultTy = OriginalTy->getPointeeType(); 4872 } else if (OriginalTy->isArrayType()) { 4873 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4874 } else { 4875 return ExprError( 4876 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4877 << Base->getSourceRange()); 4878 } 4879 // C99 6.5.2.1p1 4880 if (LowerBound) { 4881 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4882 LowerBound); 4883 if (Res.isInvalid()) 4884 return ExprError(Diag(LowerBound->getExprLoc(), 4885 diag::err_omp_typecheck_section_not_integer) 4886 << 0 << LowerBound->getSourceRange()); 4887 LowerBound = Res.get(); 4888 4889 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4890 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4891 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4892 << 0 << LowerBound->getSourceRange(); 4893 } 4894 if (Length) { 4895 auto Res = 4896 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4897 if (Res.isInvalid()) 4898 return ExprError(Diag(Length->getExprLoc(), 4899 diag::err_omp_typecheck_section_not_integer) 4900 << 1 << Length->getSourceRange()); 4901 Length = Res.get(); 4902 4903 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4904 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4905 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4906 << 1 << Length->getSourceRange(); 4907 } 4908 if (Stride) { 4909 ExprResult Res = 4910 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4911 if (Res.isInvalid()) 4912 return ExprError(Diag(Stride->getExprLoc(), 4913 diag::err_omp_typecheck_section_not_integer) 4914 << 1 << Stride->getSourceRange()); 4915 Stride = Res.get(); 4916 4917 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4918 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4919 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4920 << 1 << Stride->getSourceRange(); 4921 } 4922 4923 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4924 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4925 // type. Note that functions are not objects, and that (in C99 parlance) 4926 // incomplete types are not object types. 4927 if (ResultTy->isFunctionType()) { 4928 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4929 << ResultTy << Base->getSourceRange(); 4930 return ExprError(); 4931 } 4932 4933 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4934 diag::err_omp_section_incomplete_type, Base)) 4935 return ExprError(); 4936 4937 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4938 Expr::EvalResult Result; 4939 if (LowerBound->EvaluateAsInt(Result, Context)) { 4940 // OpenMP 5.0, [2.1.5 Array Sections] 4941 // The array section must be a subset of the original array. 4942 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4943 if (LowerBoundValue.isNegative()) { 4944 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4945 << LowerBound->getSourceRange(); 4946 return ExprError(); 4947 } 4948 } 4949 } 4950 4951 if (Length) { 4952 Expr::EvalResult Result; 4953 if (Length->EvaluateAsInt(Result, Context)) { 4954 // OpenMP 5.0, [2.1.5 Array Sections] 4955 // The length must evaluate to non-negative integers. 4956 llvm::APSInt LengthValue = Result.Val.getInt(); 4957 if (LengthValue.isNegative()) { 4958 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4959 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4960 << Length->getSourceRange(); 4961 return ExprError(); 4962 } 4963 } 4964 } else if (ColonLocFirst.isValid() && 4965 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4966 !OriginalTy->isVariableArrayType()))) { 4967 // OpenMP 5.0, [2.1.5 Array Sections] 4968 // When the size of the array dimension is not known, the length must be 4969 // specified explicitly. 4970 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 4971 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4972 return ExprError(); 4973 } 4974 4975 if (Stride) { 4976 Expr::EvalResult Result; 4977 if (Stride->EvaluateAsInt(Result, Context)) { 4978 // OpenMP 5.0, [2.1.5 Array Sections] 4979 // The stride must evaluate to a positive integer. 4980 llvm::APSInt StrideValue = Result.Val.getInt(); 4981 if (!StrideValue.isStrictlyPositive()) { 4982 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 4983 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 4984 << Stride->getSourceRange(); 4985 return ExprError(); 4986 } 4987 } 4988 } 4989 4990 if (!Base->getType()->isSpecificPlaceholderType( 4991 BuiltinType::OMPArraySection)) { 4992 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4993 if (Result.isInvalid()) 4994 return ExprError(); 4995 Base = Result.get(); 4996 } 4997 return new (Context) OMPArraySectionExpr( 4998 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 4999 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5000 } 5001 5002 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5003 SourceLocation RParenLoc, 5004 ArrayRef<Expr *> Dims, 5005 ArrayRef<SourceRange> Brackets) { 5006 if (Base->getType()->isPlaceholderType()) { 5007 ExprResult Result = CheckPlaceholderExpr(Base); 5008 if (Result.isInvalid()) 5009 return ExprError(); 5010 Result = DefaultLvalueConversion(Result.get()); 5011 if (Result.isInvalid()) 5012 return ExprError(); 5013 Base = Result.get(); 5014 } 5015 QualType BaseTy = Base->getType(); 5016 // Delay analysis of the types/expressions if instantiation/specialization is 5017 // required. 5018 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5019 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5020 LParenLoc, RParenLoc, Dims, Brackets); 5021 if (!BaseTy->isPointerType() || 5022 (!Base->isTypeDependent() && 5023 BaseTy->getPointeeType()->isIncompleteType())) 5024 return ExprError(Diag(Base->getExprLoc(), 5025 diag::err_omp_non_pointer_type_array_shaping_base) 5026 << Base->getSourceRange()); 5027 5028 SmallVector<Expr *, 4> NewDims; 5029 bool ErrorFound = false; 5030 for (Expr *Dim : Dims) { 5031 if (Dim->getType()->isPlaceholderType()) { 5032 ExprResult Result = CheckPlaceholderExpr(Dim); 5033 if (Result.isInvalid()) { 5034 ErrorFound = true; 5035 continue; 5036 } 5037 Result = DefaultLvalueConversion(Result.get()); 5038 if (Result.isInvalid()) { 5039 ErrorFound = true; 5040 continue; 5041 } 5042 Dim = Result.get(); 5043 } 5044 if (!Dim->isTypeDependent()) { 5045 ExprResult Result = 5046 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5047 if (Result.isInvalid()) { 5048 ErrorFound = true; 5049 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5050 << Dim->getSourceRange(); 5051 continue; 5052 } 5053 Dim = Result.get(); 5054 Expr::EvalResult EvResult; 5055 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5056 // OpenMP 5.0, [2.1.4 Array Shaping] 5057 // Each si is an integral type expression that must evaluate to a 5058 // positive integer. 5059 llvm::APSInt Value = EvResult.Val.getInt(); 5060 if (!Value.isStrictlyPositive()) { 5061 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5062 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5063 << Dim->getSourceRange(); 5064 ErrorFound = true; 5065 continue; 5066 } 5067 } 5068 } 5069 NewDims.push_back(Dim); 5070 } 5071 if (ErrorFound) 5072 return ExprError(); 5073 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5074 LParenLoc, RParenLoc, NewDims, Brackets); 5075 } 5076 5077 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5078 SourceLocation LLoc, SourceLocation RLoc, 5079 ArrayRef<OMPIteratorData> Data) { 5080 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5081 bool IsCorrect = true; 5082 for (const OMPIteratorData &D : Data) { 5083 TypeSourceInfo *TInfo = nullptr; 5084 SourceLocation StartLoc; 5085 QualType DeclTy; 5086 if (!D.Type.getAsOpaquePtr()) { 5087 // OpenMP 5.0, 2.1.6 Iterators 5088 // In an iterator-specifier, if the iterator-type is not specified then 5089 // the type of that iterator is of int type. 5090 DeclTy = Context.IntTy; 5091 StartLoc = D.DeclIdentLoc; 5092 } else { 5093 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5094 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5095 } 5096 5097 bool IsDeclTyDependent = DeclTy->isDependentType() || 5098 DeclTy->containsUnexpandedParameterPack() || 5099 DeclTy->isInstantiationDependentType(); 5100 if (!IsDeclTyDependent) { 5101 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5102 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5103 // The iterator-type must be an integral or pointer type. 5104 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5105 << DeclTy; 5106 IsCorrect = false; 5107 continue; 5108 } 5109 if (DeclTy.isConstant(Context)) { 5110 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5111 // The iterator-type must not be const qualified. 5112 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5113 << DeclTy; 5114 IsCorrect = false; 5115 continue; 5116 } 5117 } 5118 5119 // Iterator declaration. 5120 assert(D.DeclIdent && "Identifier expected."); 5121 // Always try to create iterator declarator to avoid extra error messages 5122 // about unknown declarations use. 5123 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5124 D.DeclIdent, DeclTy, TInfo, SC_None); 5125 VD->setImplicit(); 5126 if (S) { 5127 // Check for conflicting previous declaration. 5128 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5129 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5130 ForVisibleRedeclaration); 5131 Previous.suppressDiagnostics(); 5132 LookupName(Previous, S); 5133 5134 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5135 /*AllowInlineNamespace=*/false); 5136 if (!Previous.empty()) { 5137 NamedDecl *Old = Previous.getRepresentativeDecl(); 5138 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5139 Diag(Old->getLocation(), diag::note_previous_definition); 5140 } else { 5141 PushOnScopeChains(VD, S); 5142 } 5143 } else { 5144 CurContext->addDecl(VD); 5145 } 5146 Expr *Begin = D.Range.Begin; 5147 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5148 ExprResult BeginRes = 5149 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5150 Begin = BeginRes.get(); 5151 } 5152 Expr *End = D.Range.End; 5153 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5154 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5155 End = EndRes.get(); 5156 } 5157 Expr *Step = D.Range.Step; 5158 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5159 if (!Step->getType()->isIntegralType(Context)) { 5160 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5161 << Step << Step->getSourceRange(); 5162 IsCorrect = false; 5163 continue; 5164 } 5165 llvm::APSInt Result; 5166 bool IsConstant = Step->isIntegerConstantExpr(Result, Context); 5167 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5168 // If the step expression of a range-specification equals zero, the 5169 // behavior is unspecified. 5170 if (IsConstant && Result.isNullValue()) { 5171 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5172 << Step << Step->getSourceRange(); 5173 IsCorrect = false; 5174 continue; 5175 } 5176 } 5177 if (!Begin || !End || !IsCorrect) { 5178 IsCorrect = false; 5179 continue; 5180 } 5181 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5182 IDElem.IteratorDecl = VD; 5183 IDElem.AssignmentLoc = D.AssignLoc; 5184 IDElem.Range.Begin = Begin; 5185 IDElem.Range.End = End; 5186 IDElem.Range.Step = Step; 5187 IDElem.ColonLoc = D.ColonLoc; 5188 IDElem.SecondColonLoc = D.SecColonLoc; 5189 } 5190 if (!IsCorrect) { 5191 // Invalidate all created iterator declarations if error is found. 5192 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5193 if (Decl *ID = D.IteratorDecl) 5194 ID->setInvalidDecl(); 5195 } 5196 return ExprError(); 5197 } 5198 SmallVector<OMPIteratorHelperData, 4> Helpers; 5199 if (!CurContext->isDependentContext()) { 5200 // Build number of ityeration for each iteration range. 5201 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5202 // ((Begini-Stepi-1-Endi) / -Stepi); 5203 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5204 // (Endi - Begini) 5205 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5206 D.Range.Begin); 5207 if(!Res.isUsable()) { 5208 IsCorrect = false; 5209 continue; 5210 } 5211 ExprResult St, St1; 5212 if (D.Range.Step) { 5213 St = D.Range.Step; 5214 // (Endi - Begini) + Stepi 5215 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5216 if (!Res.isUsable()) { 5217 IsCorrect = false; 5218 continue; 5219 } 5220 // (Endi - Begini) + Stepi - 1 5221 Res = 5222 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5223 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5224 if (!Res.isUsable()) { 5225 IsCorrect = false; 5226 continue; 5227 } 5228 // ((Endi - Begini) + Stepi - 1) / Stepi 5229 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5230 if (!Res.isUsable()) { 5231 IsCorrect = false; 5232 continue; 5233 } 5234 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5235 // (Begini - Endi) 5236 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5237 D.Range.Begin, D.Range.End); 5238 if (!Res1.isUsable()) { 5239 IsCorrect = false; 5240 continue; 5241 } 5242 // (Begini - Endi) - Stepi 5243 Res1 = 5244 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5245 if (!Res1.isUsable()) { 5246 IsCorrect = false; 5247 continue; 5248 } 5249 // (Begini - Endi) - Stepi - 1 5250 Res1 = 5251 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5252 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5253 if (!Res1.isUsable()) { 5254 IsCorrect = false; 5255 continue; 5256 } 5257 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5258 Res1 = 5259 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5260 if (!Res1.isUsable()) { 5261 IsCorrect = false; 5262 continue; 5263 } 5264 // Stepi > 0. 5265 ExprResult CmpRes = 5266 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5267 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5268 if (!CmpRes.isUsable()) { 5269 IsCorrect = false; 5270 continue; 5271 } 5272 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5273 Res.get(), Res1.get()); 5274 if (!Res.isUsable()) { 5275 IsCorrect = false; 5276 continue; 5277 } 5278 } 5279 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5280 if (!Res.isUsable()) { 5281 IsCorrect = false; 5282 continue; 5283 } 5284 5285 // Build counter update. 5286 // Build counter. 5287 auto *CounterVD = 5288 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5289 D.IteratorDecl->getBeginLoc(), nullptr, 5290 Res.get()->getType(), nullptr, SC_None); 5291 CounterVD->setImplicit(); 5292 ExprResult RefRes = 5293 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5294 D.IteratorDecl->getBeginLoc()); 5295 // Build counter update. 5296 // I = Begini + counter * Stepi; 5297 ExprResult UpdateRes; 5298 if (D.Range.Step) { 5299 UpdateRes = CreateBuiltinBinOp( 5300 D.AssignmentLoc, BO_Mul, 5301 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5302 } else { 5303 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5304 } 5305 if (!UpdateRes.isUsable()) { 5306 IsCorrect = false; 5307 continue; 5308 } 5309 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5310 UpdateRes.get()); 5311 if (!UpdateRes.isUsable()) { 5312 IsCorrect = false; 5313 continue; 5314 } 5315 ExprResult VDRes = 5316 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5317 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5318 D.IteratorDecl->getBeginLoc()); 5319 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5320 UpdateRes.get()); 5321 if (!UpdateRes.isUsable()) { 5322 IsCorrect = false; 5323 continue; 5324 } 5325 UpdateRes = 5326 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5327 if (!UpdateRes.isUsable()) { 5328 IsCorrect = false; 5329 continue; 5330 } 5331 ExprResult CounterUpdateRes = 5332 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5333 if (!CounterUpdateRes.isUsable()) { 5334 IsCorrect = false; 5335 continue; 5336 } 5337 CounterUpdateRes = 5338 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5339 if (!CounterUpdateRes.isUsable()) { 5340 IsCorrect = false; 5341 continue; 5342 } 5343 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5344 HD.CounterVD = CounterVD; 5345 HD.Upper = Res.get(); 5346 HD.Update = UpdateRes.get(); 5347 HD.CounterUpdate = CounterUpdateRes.get(); 5348 } 5349 } else { 5350 Helpers.assign(ID.size(), {}); 5351 } 5352 if (!IsCorrect) { 5353 // Invalidate all created iterator declarations if error is found. 5354 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5355 if (Decl *ID = D.IteratorDecl) 5356 ID->setInvalidDecl(); 5357 } 5358 return ExprError(); 5359 } 5360 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5361 LLoc, RLoc, ID, Helpers); 5362 } 5363 5364 ExprResult 5365 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5366 Expr *Idx, SourceLocation RLoc) { 5367 Expr *LHSExp = Base; 5368 Expr *RHSExp = Idx; 5369 5370 ExprValueKind VK = VK_LValue; 5371 ExprObjectKind OK = OK_Ordinary; 5372 5373 // Per C++ core issue 1213, the result is an xvalue if either operand is 5374 // a non-lvalue array, and an lvalue otherwise. 5375 if (getLangOpts().CPlusPlus11) { 5376 for (auto *Op : {LHSExp, RHSExp}) { 5377 Op = Op->IgnoreImplicit(); 5378 if (Op->getType()->isArrayType() && !Op->isLValue()) 5379 VK = VK_XValue; 5380 } 5381 } 5382 5383 // Perform default conversions. 5384 if (!LHSExp->getType()->getAs<VectorType>()) { 5385 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5386 if (Result.isInvalid()) 5387 return ExprError(); 5388 LHSExp = Result.get(); 5389 } 5390 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5391 if (Result.isInvalid()) 5392 return ExprError(); 5393 RHSExp = Result.get(); 5394 5395 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5396 5397 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5398 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5399 // in the subscript position. As a result, we need to derive the array base 5400 // and index from the expression types. 5401 Expr *BaseExpr, *IndexExpr; 5402 QualType ResultType; 5403 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5404 BaseExpr = LHSExp; 5405 IndexExpr = RHSExp; 5406 ResultType = Context.DependentTy; 5407 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5408 BaseExpr = LHSExp; 5409 IndexExpr = RHSExp; 5410 ResultType = PTy->getPointeeType(); 5411 } else if (const ObjCObjectPointerType *PTy = 5412 LHSTy->getAs<ObjCObjectPointerType>()) { 5413 BaseExpr = LHSExp; 5414 IndexExpr = RHSExp; 5415 5416 // Use custom logic if this should be the pseudo-object subscript 5417 // expression. 5418 if (!LangOpts.isSubscriptPointerArithmetic()) 5419 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5420 nullptr); 5421 5422 ResultType = PTy->getPointeeType(); 5423 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5424 // Handle the uncommon case of "123[Ptr]". 5425 BaseExpr = RHSExp; 5426 IndexExpr = LHSExp; 5427 ResultType = PTy->getPointeeType(); 5428 } else if (const ObjCObjectPointerType *PTy = 5429 RHSTy->getAs<ObjCObjectPointerType>()) { 5430 // Handle the uncommon case of "123[Ptr]". 5431 BaseExpr = RHSExp; 5432 IndexExpr = LHSExp; 5433 ResultType = PTy->getPointeeType(); 5434 if (!LangOpts.isSubscriptPointerArithmetic()) { 5435 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5436 << ResultType << BaseExpr->getSourceRange(); 5437 return ExprError(); 5438 } 5439 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5440 BaseExpr = LHSExp; // vectors: V[123] 5441 IndexExpr = RHSExp; 5442 // We apply C++ DR1213 to vector subscripting too. 5443 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5444 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5445 if (Materialized.isInvalid()) 5446 return ExprError(); 5447 LHSExp = Materialized.get(); 5448 } 5449 VK = LHSExp->getValueKind(); 5450 if (VK != VK_RValue) 5451 OK = OK_VectorComponent; 5452 5453 ResultType = VTy->getElementType(); 5454 QualType BaseType = BaseExpr->getType(); 5455 Qualifiers BaseQuals = BaseType.getQualifiers(); 5456 Qualifiers MemberQuals = ResultType.getQualifiers(); 5457 Qualifiers Combined = BaseQuals + MemberQuals; 5458 if (Combined != MemberQuals) 5459 ResultType = Context.getQualifiedType(ResultType, Combined); 5460 } else if (LHSTy->isArrayType()) { 5461 // If we see an array that wasn't promoted by 5462 // DefaultFunctionArrayLvalueConversion, it must be an array that 5463 // wasn't promoted because of the C90 rule that doesn't 5464 // allow promoting non-lvalue arrays. Warn, then 5465 // force the promotion here. 5466 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5467 << LHSExp->getSourceRange(); 5468 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5469 CK_ArrayToPointerDecay).get(); 5470 LHSTy = LHSExp->getType(); 5471 5472 BaseExpr = LHSExp; 5473 IndexExpr = RHSExp; 5474 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5475 } else if (RHSTy->isArrayType()) { 5476 // Same as previous, except for 123[f().a] case 5477 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5478 << RHSExp->getSourceRange(); 5479 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5480 CK_ArrayToPointerDecay).get(); 5481 RHSTy = RHSExp->getType(); 5482 5483 BaseExpr = RHSExp; 5484 IndexExpr = LHSExp; 5485 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5486 } else { 5487 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5488 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5489 } 5490 // C99 6.5.2.1p1 5491 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5492 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5493 << IndexExpr->getSourceRange()); 5494 5495 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5496 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5497 && !IndexExpr->isTypeDependent()) 5498 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5499 5500 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5501 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5502 // type. Note that Functions are not objects, and that (in C99 parlance) 5503 // incomplete types are not object types. 5504 if (ResultType->isFunctionType()) { 5505 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5506 << ResultType << BaseExpr->getSourceRange(); 5507 return ExprError(); 5508 } 5509 5510 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5511 // GNU extension: subscripting on pointer to void 5512 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5513 << BaseExpr->getSourceRange(); 5514 5515 // C forbids expressions of unqualified void type from being l-values. 5516 // See IsCForbiddenLValueType. 5517 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5518 } else if (!ResultType->isDependentType() && 5519 RequireCompleteSizedType( 5520 LLoc, ResultType, 5521 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5522 return ExprError(); 5523 5524 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5525 !ResultType.isCForbiddenLValueType()); 5526 5527 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5528 FunctionScopes.size() > 1) { 5529 if (auto *TT = 5530 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5531 for (auto I = FunctionScopes.rbegin(), 5532 E = std::prev(FunctionScopes.rend()); 5533 I != E; ++I) { 5534 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5535 if (CSI == nullptr) 5536 break; 5537 DeclContext *DC = nullptr; 5538 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5539 DC = LSI->CallOperator; 5540 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5541 DC = CRSI->TheCapturedDecl; 5542 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5543 DC = BSI->TheDecl; 5544 if (DC) { 5545 if (DC->containsDecl(TT->getDecl())) 5546 break; 5547 captureVariablyModifiedType( 5548 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5549 } 5550 } 5551 } 5552 } 5553 5554 return new (Context) 5555 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5556 } 5557 5558 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5559 ParmVarDecl *Param) { 5560 if (Param->hasUnparsedDefaultArg()) { 5561 // If we've already cleared out the location for the default argument, 5562 // that means we're parsing it right now. 5563 if (!UnparsedDefaultArgLocs.count(Param)) { 5564 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5565 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5566 Param->setInvalidDecl(); 5567 return true; 5568 } 5569 5570 Diag(CallLoc, 5571 diag::err_use_of_default_argument_to_function_declared_later) << 5572 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 5573 Diag(UnparsedDefaultArgLocs[Param], 5574 diag::note_default_argument_declared_here); 5575 return true; 5576 } 5577 5578 if (Param->hasUninstantiatedDefaultArg() && 5579 InstantiateDefaultArgument(CallLoc, FD, Param)) 5580 return true; 5581 5582 assert(Param->hasInit() && "default argument but no initializer?"); 5583 5584 // If the default expression creates temporaries, we need to 5585 // push them to the current stack of expression temporaries so they'll 5586 // be properly destroyed. 5587 // FIXME: We should really be rebuilding the default argument with new 5588 // bound temporaries; see the comment in PR5810. 5589 // We don't need to do that with block decls, though, because 5590 // blocks in default argument expression can never capture anything. 5591 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5592 // Set the "needs cleanups" bit regardless of whether there are 5593 // any explicit objects. 5594 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5595 5596 // Append all the objects to the cleanup list. Right now, this 5597 // should always be a no-op, because blocks in default argument 5598 // expressions should never be able to capture anything. 5599 assert(!Init->getNumObjects() && 5600 "default argument expression has capturing blocks?"); 5601 } 5602 5603 // We already type-checked the argument, so we know it works. 5604 // Just mark all of the declarations in this potentially-evaluated expression 5605 // as being "referenced". 5606 EnterExpressionEvaluationContext EvalContext( 5607 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5608 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5609 /*SkipLocalVariables=*/true); 5610 return false; 5611 } 5612 5613 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5614 FunctionDecl *FD, ParmVarDecl *Param) { 5615 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5616 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5617 return ExprError(); 5618 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5619 } 5620 5621 Sema::VariadicCallType 5622 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5623 Expr *Fn) { 5624 if (Proto && Proto->isVariadic()) { 5625 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5626 return VariadicConstructor; 5627 else if (Fn && Fn->getType()->isBlockPointerType()) 5628 return VariadicBlock; 5629 else if (FDecl) { 5630 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5631 if (Method->isInstance()) 5632 return VariadicMethod; 5633 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5634 return VariadicMethod; 5635 return VariadicFunction; 5636 } 5637 return VariadicDoesNotApply; 5638 } 5639 5640 namespace { 5641 class FunctionCallCCC final : public FunctionCallFilterCCC { 5642 public: 5643 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5644 unsigned NumArgs, MemberExpr *ME) 5645 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5646 FunctionName(FuncName) {} 5647 5648 bool ValidateCandidate(const TypoCorrection &candidate) override { 5649 if (!candidate.getCorrectionSpecifier() || 5650 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5651 return false; 5652 } 5653 5654 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5655 } 5656 5657 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5658 return std::make_unique<FunctionCallCCC>(*this); 5659 } 5660 5661 private: 5662 const IdentifierInfo *const FunctionName; 5663 }; 5664 } 5665 5666 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5667 FunctionDecl *FDecl, 5668 ArrayRef<Expr *> Args) { 5669 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5670 DeclarationName FuncName = FDecl->getDeclName(); 5671 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5672 5673 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5674 if (TypoCorrection Corrected = S.CorrectTypo( 5675 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5676 S.getScopeForContext(S.CurContext), nullptr, CCC, 5677 Sema::CTK_ErrorRecovery)) { 5678 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5679 if (Corrected.isOverloaded()) { 5680 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5681 OverloadCandidateSet::iterator Best; 5682 for (NamedDecl *CD : Corrected) { 5683 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5684 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5685 OCS); 5686 } 5687 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5688 case OR_Success: 5689 ND = Best->FoundDecl; 5690 Corrected.setCorrectionDecl(ND); 5691 break; 5692 default: 5693 break; 5694 } 5695 } 5696 ND = ND->getUnderlyingDecl(); 5697 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5698 return Corrected; 5699 } 5700 } 5701 return TypoCorrection(); 5702 } 5703 5704 /// ConvertArgumentsForCall - Converts the arguments specified in 5705 /// Args/NumArgs to the parameter types of the function FDecl with 5706 /// function prototype Proto. Call is the call expression itself, and 5707 /// Fn is the function expression. For a C++ member function, this 5708 /// routine does not attempt to convert the object argument. Returns 5709 /// true if the call is ill-formed. 5710 bool 5711 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5712 FunctionDecl *FDecl, 5713 const FunctionProtoType *Proto, 5714 ArrayRef<Expr *> Args, 5715 SourceLocation RParenLoc, 5716 bool IsExecConfig) { 5717 // Bail out early if calling a builtin with custom typechecking. 5718 if (FDecl) 5719 if (unsigned ID = FDecl->getBuiltinID()) 5720 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5721 return false; 5722 5723 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5724 // assignment, to the types of the corresponding parameter, ... 5725 unsigned NumParams = Proto->getNumParams(); 5726 bool Invalid = false; 5727 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5728 unsigned FnKind = Fn->getType()->isBlockPointerType() 5729 ? 1 /* block */ 5730 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5731 : 0 /* function */); 5732 5733 // If too few arguments are available (and we don't have default 5734 // arguments for the remaining parameters), don't make the call. 5735 if (Args.size() < NumParams) { 5736 if (Args.size() < MinArgs) { 5737 TypoCorrection TC; 5738 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5739 unsigned diag_id = 5740 MinArgs == NumParams && !Proto->isVariadic() 5741 ? diag::err_typecheck_call_too_few_args_suggest 5742 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5743 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5744 << static_cast<unsigned>(Args.size()) 5745 << TC.getCorrectionRange()); 5746 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5747 Diag(RParenLoc, 5748 MinArgs == NumParams && !Proto->isVariadic() 5749 ? diag::err_typecheck_call_too_few_args_one 5750 : diag::err_typecheck_call_too_few_args_at_least_one) 5751 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5752 else 5753 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5754 ? diag::err_typecheck_call_too_few_args 5755 : diag::err_typecheck_call_too_few_args_at_least) 5756 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5757 << Fn->getSourceRange(); 5758 5759 // Emit the location of the prototype. 5760 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5761 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5762 5763 return true; 5764 } 5765 // We reserve space for the default arguments when we create 5766 // the call expression, before calling ConvertArgumentsForCall. 5767 assert((Call->getNumArgs() == NumParams) && 5768 "We should have reserved space for the default arguments before!"); 5769 } 5770 5771 // If too many are passed and not variadic, error on the extras and drop 5772 // them. 5773 if (Args.size() > NumParams) { 5774 if (!Proto->isVariadic()) { 5775 TypoCorrection TC; 5776 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5777 unsigned diag_id = 5778 MinArgs == NumParams && !Proto->isVariadic() 5779 ? diag::err_typecheck_call_too_many_args_suggest 5780 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5781 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5782 << static_cast<unsigned>(Args.size()) 5783 << TC.getCorrectionRange()); 5784 } else if (NumParams == 1 && FDecl && 5785 FDecl->getParamDecl(0)->getDeclName()) 5786 Diag(Args[NumParams]->getBeginLoc(), 5787 MinArgs == NumParams 5788 ? diag::err_typecheck_call_too_many_args_one 5789 : diag::err_typecheck_call_too_many_args_at_most_one) 5790 << FnKind << FDecl->getParamDecl(0) 5791 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5792 << SourceRange(Args[NumParams]->getBeginLoc(), 5793 Args.back()->getEndLoc()); 5794 else 5795 Diag(Args[NumParams]->getBeginLoc(), 5796 MinArgs == NumParams 5797 ? diag::err_typecheck_call_too_many_args 5798 : diag::err_typecheck_call_too_many_args_at_most) 5799 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5800 << Fn->getSourceRange() 5801 << SourceRange(Args[NumParams]->getBeginLoc(), 5802 Args.back()->getEndLoc()); 5803 5804 // Emit the location of the prototype. 5805 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5806 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5807 5808 // This deletes the extra arguments. 5809 Call->shrinkNumArgs(NumParams); 5810 return true; 5811 } 5812 } 5813 SmallVector<Expr *, 8> AllArgs; 5814 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5815 5816 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5817 AllArgs, CallType); 5818 if (Invalid) 5819 return true; 5820 unsigned TotalNumArgs = AllArgs.size(); 5821 for (unsigned i = 0; i < TotalNumArgs; ++i) 5822 Call->setArg(i, AllArgs[i]); 5823 5824 return false; 5825 } 5826 5827 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5828 const FunctionProtoType *Proto, 5829 unsigned FirstParam, ArrayRef<Expr *> Args, 5830 SmallVectorImpl<Expr *> &AllArgs, 5831 VariadicCallType CallType, bool AllowExplicit, 5832 bool IsListInitialization) { 5833 unsigned NumParams = Proto->getNumParams(); 5834 bool Invalid = false; 5835 size_t ArgIx = 0; 5836 // Continue to check argument types (even if we have too few/many args). 5837 for (unsigned i = FirstParam; i < NumParams; i++) { 5838 QualType ProtoArgType = Proto->getParamType(i); 5839 5840 Expr *Arg; 5841 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5842 if (ArgIx < Args.size()) { 5843 Arg = Args[ArgIx++]; 5844 5845 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5846 diag::err_call_incomplete_argument, Arg)) 5847 return true; 5848 5849 // Strip the unbridged-cast placeholder expression off, if applicable. 5850 bool CFAudited = false; 5851 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5852 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5853 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5854 Arg = stripARCUnbridgedCast(Arg); 5855 else if (getLangOpts().ObjCAutoRefCount && 5856 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5857 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5858 CFAudited = true; 5859 5860 if (Proto->getExtParameterInfo(i).isNoEscape()) 5861 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5862 BE->getBlockDecl()->setDoesNotEscape(); 5863 5864 InitializedEntity Entity = 5865 Param ? InitializedEntity::InitializeParameter(Context, Param, 5866 ProtoArgType) 5867 : InitializedEntity::InitializeParameter( 5868 Context, ProtoArgType, Proto->isParamConsumed(i)); 5869 5870 // Remember that parameter belongs to a CF audited API. 5871 if (CFAudited) 5872 Entity.setParameterCFAudited(); 5873 5874 ExprResult ArgE = PerformCopyInitialization( 5875 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5876 if (ArgE.isInvalid()) 5877 return true; 5878 5879 Arg = ArgE.getAs<Expr>(); 5880 } else { 5881 assert(Param && "can't use default arguments without a known callee"); 5882 5883 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5884 if (ArgExpr.isInvalid()) 5885 return true; 5886 5887 Arg = ArgExpr.getAs<Expr>(); 5888 } 5889 5890 // Check for array bounds violations for each argument to the call. This 5891 // check only triggers warnings when the argument isn't a more complex Expr 5892 // with its own checking, such as a BinaryOperator. 5893 CheckArrayAccess(Arg); 5894 5895 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5896 CheckStaticArrayArgument(CallLoc, Param, Arg); 5897 5898 AllArgs.push_back(Arg); 5899 } 5900 5901 // If this is a variadic call, handle args passed through "...". 5902 if (CallType != VariadicDoesNotApply) { 5903 // Assume that extern "C" functions with variadic arguments that 5904 // return __unknown_anytype aren't *really* variadic. 5905 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5906 FDecl->isExternC()) { 5907 for (Expr *A : Args.slice(ArgIx)) { 5908 QualType paramType; // ignored 5909 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5910 Invalid |= arg.isInvalid(); 5911 AllArgs.push_back(arg.get()); 5912 } 5913 5914 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5915 } else { 5916 for (Expr *A : Args.slice(ArgIx)) { 5917 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5918 Invalid |= Arg.isInvalid(); 5919 AllArgs.push_back(Arg.get()); 5920 } 5921 } 5922 5923 // Check for array bounds violations. 5924 for (Expr *A : Args.slice(ArgIx)) 5925 CheckArrayAccess(A); 5926 } 5927 return Invalid; 5928 } 5929 5930 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5931 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5932 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5933 TL = DTL.getOriginalLoc(); 5934 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5935 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5936 << ATL.getLocalSourceRange(); 5937 } 5938 5939 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5940 /// array parameter, check that it is non-null, and that if it is formed by 5941 /// array-to-pointer decay, the underlying array is sufficiently large. 5942 /// 5943 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5944 /// array type derivation, then for each call to the function, the value of the 5945 /// corresponding actual argument shall provide access to the first element of 5946 /// an array with at least as many elements as specified by the size expression. 5947 void 5948 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5949 ParmVarDecl *Param, 5950 const Expr *ArgExpr) { 5951 // Static array parameters are not supported in C++. 5952 if (!Param || getLangOpts().CPlusPlus) 5953 return; 5954 5955 QualType OrigTy = Param->getOriginalType(); 5956 5957 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5958 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5959 return; 5960 5961 if (ArgExpr->isNullPointerConstant(Context, 5962 Expr::NPC_NeverValueDependent)) { 5963 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5964 DiagnoseCalleeStaticArrayParam(*this, Param); 5965 return; 5966 } 5967 5968 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5969 if (!CAT) 5970 return; 5971 5972 const ConstantArrayType *ArgCAT = 5973 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5974 if (!ArgCAT) 5975 return; 5976 5977 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5978 ArgCAT->getElementType())) { 5979 if (ArgCAT->getSize().ult(CAT->getSize())) { 5980 Diag(CallLoc, diag::warn_static_array_too_small) 5981 << ArgExpr->getSourceRange() 5982 << (unsigned)ArgCAT->getSize().getZExtValue() 5983 << (unsigned)CAT->getSize().getZExtValue() << 0; 5984 DiagnoseCalleeStaticArrayParam(*this, Param); 5985 } 5986 return; 5987 } 5988 5989 Optional<CharUnits> ArgSize = 5990 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5991 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5992 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5993 Diag(CallLoc, diag::warn_static_array_too_small) 5994 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5995 << (unsigned)ParmSize->getQuantity() << 1; 5996 DiagnoseCalleeStaticArrayParam(*this, Param); 5997 } 5998 } 5999 6000 /// Given a function expression of unknown-any type, try to rebuild it 6001 /// to have a function type. 6002 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6003 6004 /// Is the given type a placeholder that we need to lower out 6005 /// immediately during argument processing? 6006 static bool isPlaceholderToRemoveAsArg(QualType type) { 6007 // Placeholders are never sugared. 6008 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6009 if (!placeholder) return false; 6010 6011 switch (placeholder->getKind()) { 6012 // Ignore all the non-placeholder types. 6013 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6014 case BuiltinType::Id: 6015 #include "clang/Basic/OpenCLImageTypes.def" 6016 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6017 case BuiltinType::Id: 6018 #include "clang/Basic/OpenCLExtensionTypes.def" 6019 // In practice we'll never use this, since all SVE types are sugared 6020 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6021 #define SVE_TYPE(Name, Id, SingletonId) \ 6022 case BuiltinType::Id: 6023 #include "clang/Basic/AArch64SVEACLETypes.def" 6024 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6025 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6026 #include "clang/AST/BuiltinTypes.def" 6027 return false; 6028 6029 // We cannot lower out overload sets; they might validly be resolved 6030 // by the call machinery. 6031 case BuiltinType::Overload: 6032 return false; 6033 6034 // Unbridged casts in ARC can be handled in some call positions and 6035 // should be left in place. 6036 case BuiltinType::ARCUnbridgedCast: 6037 return false; 6038 6039 // Pseudo-objects should be converted as soon as possible. 6040 case BuiltinType::PseudoObject: 6041 return true; 6042 6043 // The debugger mode could theoretically but currently does not try 6044 // to resolve unknown-typed arguments based on known parameter types. 6045 case BuiltinType::UnknownAny: 6046 return true; 6047 6048 // These are always invalid as call arguments and should be reported. 6049 case BuiltinType::BoundMember: 6050 case BuiltinType::BuiltinFn: 6051 case BuiltinType::IncompleteMatrixIdx: 6052 case BuiltinType::OMPArraySection: 6053 case BuiltinType::OMPArrayShaping: 6054 case BuiltinType::OMPIterator: 6055 return true; 6056 6057 } 6058 llvm_unreachable("bad builtin type kind"); 6059 } 6060 6061 /// Check an argument list for placeholders that we won't try to 6062 /// handle later. 6063 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6064 // Apply this processing to all the arguments at once instead of 6065 // dying at the first failure. 6066 bool hasInvalid = false; 6067 for (size_t i = 0, e = args.size(); i != e; i++) { 6068 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6069 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6070 if (result.isInvalid()) hasInvalid = true; 6071 else args[i] = result.get(); 6072 } else if (hasInvalid) { 6073 (void)S.CorrectDelayedTyposInExpr(args[i]); 6074 } 6075 } 6076 return hasInvalid; 6077 } 6078 6079 /// If a builtin function has a pointer argument with no explicit address 6080 /// space, then it should be able to accept a pointer to any address 6081 /// space as input. In order to do this, we need to replace the 6082 /// standard builtin declaration with one that uses the same address space 6083 /// as the call. 6084 /// 6085 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6086 /// it does not contain any pointer arguments without 6087 /// an address space qualifer. Otherwise the rewritten 6088 /// FunctionDecl is returned. 6089 /// TODO: Handle pointer return types. 6090 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6091 FunctionDecl *FDecl, 6092 MultiExprArg ArgExprs) { 6093 6094 QualType DeclType = FDecl->getType(); 6095 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6096 6097 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6098 ArgExprs.size() < FT->getNumParams()) 6099 return nullptr; 6100 6101 bool NeedsNewDecl = false; 6102 unsigned i = 0; 6103 SmallVector<QualType, 8> OverloadParams; 6104 6105 for (QualType ParamType : FT->param_types()) { 6106 6107 // Convert array arguments to pointer to simplify type lookup. 6108 ExprResult ArgRes = 6109 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6110 if (ArgRes.isInvalid()) 6111 return nullptr; 6112 Expr *Arg = ArgRes.get(); 6113 QualType ArgType = Arg->getType(); 6114 if (!ParamType->isPointerType() || 6115 ParamType.hasAddressSpace() || 6116 !ArgType->isPointerType() || 6117 !ArgType->getPointeeType().hasAddressSpace()) { 6118 OverloadParams.push_back(ParamType); 6119 continue; 6120 } 6121 6122 QualType PointeeType = ParamType->getPointeeType(); 6123 if (PointeeType.hasAddressSpace()) 6124 continue; 6125 6126 NeedsNewDecl = true; 6127 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6128 6129 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6130 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6131 } 6132 6133 if (!NeedsNewDecl) 6134 return nullptr; 6135 6136 FunctionProtoType::ExtProtoInfo EPI; 6137 EPI.Variadic = FT->isVariadic(); 6138 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6139 OverloadParams, EPI); 6140 DeclContext *Parent = FDecl->getParent(); 6141 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6142 FDecl->getLocation(), 6143 FDecl->getLocation(), 6144 FDecl->getIdentifier(), 6145 OverloadTy, 6146 /*TInfo=*/nullptr, 6147 SC_Extern, false, 6148 /*hasPrototype=*/true); 6149 SmallVector<ParmVarDecl*, 16> Params; 6150 FT = cast<FunctionProtoType>(OverloadTy); 6151 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6152 QualType ParamType = FT->getParamType(i); 6153 ParmVarDecl *Parm = 6154 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6155 SourceLocation(), nullptr, ParamType, 6156 /*TInfo=*/nullptr, SC_None, nullptr); 6157 Parm->setScopeInfo(0, i); 6158 Params.push_back(Parm); 6159 } 6160 OverloadDecl->setParams(Params); 6161 return OverloadDecl; 6162 } 6163 6164 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6165 FunctionDecl *Callee, 6166 MultiExprArg ArgExprs) { 6167 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6168 // similar attributes) really don't like it when functions are called with an 6169 // invalid number of args. 6170 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6171 /*PartialOverloading=*/false) && 6172 !Callee->isVariadic()) 6173 return; 6174 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6175 return; 6176 6177 if (const EnableIfAttr *Attr = 6178 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6179 S.Diag(Fn->getBeginLoc(), 6180 isa<CXXMethodDecl>(Callee) 6181 ? diag::err_ovl_no_viable_member_function_in_call 6182 : diag::err_ovl_no_viable_function_in_call) 6183 << Callee << Callee->getSourceRange(); 6184 S.Diag(Callee->getLocation(), 6185 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6186 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6187 return; 6188 } 6189 } 6190 6191 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6192 const UnresolvedMemberExpr *const UME, Sema &S) { 6193 6194 const auto GetFunctionLevelDCIfCXXClass = 6195 [](Sema &S) -> const CXXRecordDecl * { 6196 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6197 if (!DC || !DC->getParent()) 6198 return nullptr; 6199 6200 // If the call to some member function was made from within a member 6201 // function body 'M' return return 'M's parent. 6202 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6203 return MD->getParent()->getCanonicalDecl(); 6204 // else the call was made from within a default member initializer of a 6205 // class, so return the class. 6206 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6207 return RD->getCanonicalDecl(); 6208 return nullptr; 6209 }; 6210 // If our DeclContext is neither a member function nor a class (in the 6211 // case of a lambda in a default member initializer), we can't have an 6212 // enclosing 'this'. 6213 6214 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6215 if (!CurParentClass) 6216 return false; 6217 6218 // The naming class for implicit member functions call is the class in which 6219 // name lookup starts. 6220 const CXXRecordDecl *const NamingClass = 6221 UME->getNamingClass()->getCanonicalDecl(); 6222 assert(NamingClass && "Must have naming class even for implicit access"); 6223 6224 // If the unresolved member functions were found in a 'naming class' that is 6225 // related (either the same or derived from) to the class that contains the 6226 // member function that itself contained the implicit member access. 6227 6228 return CurParentClass == NamingClass || 6229 CurParentClass->isDerivedFrom(NamingClass); 6230 } 6231 6232 static void 6233 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6234 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6235 6236 if (!UME) 6237 return; 6238 6239 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6240 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6241 // already been captured, or if this is an implicit member function call (if 6242 // it isn't, an attempt to capture 'this' should already have been made). 6243 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6244 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6245 return; 6246 6247 // Check if the naming class in which the unresolved members were found is 6248 // related (same as or is a base of) to the enclosing class. 6249 6250 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6251 return; 6252 6253 6254 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6255 // If the enclosing function is not dependent, then this lambda is 6256 // capture ready, so if we can capture this, do so. 6257 if (!EnclosingFunctionCtx->isDependentContext()) { 6258 // If the current lambda and all enclosing lambdas can capture 'this' - 6259 // then go ahead and capture 'this' (since our unresolved overload set 6260 // contains at least one non-static member function). 6261 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6262 S.CheckCXXThisCapture(CallLoc); 6263 } else if (S.CurContext->isDependentContext()) { 6264 // ... since this is an implicit member reference, that might potentially 6265 // involve a 'this' capture, mark 'this' for potential capture in 6266 // enclosing lambdas. 6267 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6268 CurLSI->addPotentialThisCapture(CallLoc); 6269 } 6270 } 6271 6272 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6273 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6274 Expr *ExecConfig) { 6275 ExprResult Call = 6276 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6277 if (Call.isInvalid()) 6278 return Call; 6279 6280 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6281 // language modes. 6282 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6283 if (ULE->hasExplicitTemplateArgs() && 6284 ULE->decls_begin() == ULE->decls_end()) { 6285 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6286 ? diag::warn_cxx17_compat_adl_only_template_id 6287 : diag::ext_adl_only_template_id) 6288 << ULE->getName(); 6289 } 6290 } 6291 6292 if (LangOpts.OpenMP) 6293 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6294 ExecConfig); 6295 6296 return Call; 6297 } 6298 6299 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6300 /// This provides the location of the left/right parens and a list of comma 6301 /// locations. 6302 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6303 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6304 Expr *ExecConfig, bool IsExecConfig) { 6305 // Since this might be a postfix expression, get rid of ParenListExprs. 6306 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6307 if (Result.isInvalid()) return ExprError(); 6308 Fn = Result.get(); 6309 6310 if (checkArgsForPlaceholders(*this, ArgExprs)) 6311 return ExprError(); 6312 6313 if (getLangOpts().CPlusPlus) { 6314 // If this is a pseudo-destructor expression, build the call immediately. 6315 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6316 if (!ArgExprs.empty()) { 6317 // Pseudo-destructor calls should not have any arguments. 6318 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6319 << FixItHint::CreateRemoval( 6320 SourceRange(ArgExprs.front()->getBeginLoc(), 6321 ArgExprs.back()->getEndLoc())); 6322 } 6323 6324 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6325 VK_RValue, RParenLoc); 6326 } 6327 if (Fn->getType() == Context.PseudoObjectTy) { 6328 ExprResult result = CheckPlaceholderExpr(Fn); 6329 if (result.isInvalid()) return ExprError(); 6330 Fn = result.get(); 6331 } 6332 6333 // Determine whether this is a dependent call inside a C++ template, 6334 // in which case we won't do any semantic analysis now. 6335 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6336 if (ExecConfig) { 6337 return CUDAKernelCallExpr::Create( 6338 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6339 Context.DependentTy, VK_RValue, RParenLoc); 6340 } else { 6341 6342 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6343 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6344 Fn->getBeginLoc()); 6345 6346 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6347 VK_RValue, RParenLoc); 6348 } 6349 } 6350 6351 // Determine whether this is a call to an object (C++ [over.call.object]). 6352 if (Fn->getType()->isRecordType()) 6353 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6354 RParenLoc); 6355 6356 if (Fn->getType() == Context.UnknownAnyTy) { 6357 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6358 if (result.isInvalid()) return ExprError(); 6359 Fn = result.get(); 6360 } 6361 6362 if (Fn->getType() == Context.BoundMemberTy) { 6363 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6364 RParenLoc); 6365 } 6366 } 6367 6368 // Check for overloaded calls. This can happen even in C due to extensions. 6369 if (Fn->getType() == Context.OverloadTy) { 6370 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6371 6372 // We aren't supposed to apply this logic if there's an '&' involved. 6373 if (!find.HasFormOfMemberPointer) { 6374 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6375 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6376 VK_RValue, RParenLoc); 6377 OverloadExpr *ovl = find.Expression; 6378 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6379 return BuildOverloadedCallExpr( 6380 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6381 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6382 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6383 RParenLoc); 6384 } 6385 } 6386 6387 // If we're directly calling a function, get the appropriate declaration. 6388 if (Fn->getType() == Context.UnknownAnyTy) { 6389 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6390 if (result.isInvalid()) return ExprError(); 6391 Fn = result.get(); 6392 } 6393 6394 Expr *NakedFn = Fn->IgnoreParens(); 6395 6396 bool CallingNDeclIndirectly = false; 6397 NamedDecl *NDecl = nullptr; 6398 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6399 if (UnOp->getOpcode() == UO_AddrOf) { 6400 CallingNDeclIndirectly = true; 6401 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6402 } 6403 } 6404 6405 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6406 NDecl = DRE->getDecl(); 6407 6408 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6409 if (FDecl && FDecl->getBuiltinID()) { 6410 // Rewrite the function decl for this builtin by replacing parameters 6411 // with no explicit address space with the address space of the arguments 6412 // in ArgExprs. 6413 if ((FDecl = 6414 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6415 NDecl = FDecl; 6416 Fn = DeclRefExpr::Create( 6417 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6418 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6419 nullptr, DRE->isNonOdrUse()); 6420 } 6421 } 6422 } else if (isa<MemberExpr>(NakedFn)) 6423 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6424 6425 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6426 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6427 FD, /*Complain=*/true, Fn->getBeginLoc())) 6428 return ExprError(); 6429 6430 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6431 return ExprError(); 6432 6433 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6434 } 6435 6436 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6437 ExecConfig, IsExecConfig); 6438 } 6439 6440 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6441 /// 6442 /// __builtin_astype( value, dst type ) 6443 /// 6444 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6445 SourceLocation BuiltinLoc, 6446 SourceLocation RParenLoc) { 6447 ExprValueKind VK = VK_RValue; 6448 ExprObjectKind OK = OK_Ordinary; 6449 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6450 QualType SrcTy = E->getType(); 6451 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6452 return ExprError(Diag(BuiltinLoc, 6453 diag::err_invalid_astype_of_different_size) 6454 << DstTy 6455 << SrcTy 6456 << E->getSourceRange()); 6457 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6458 } 6459 6460 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6461 /// provided arguments. 6462 /// 6463 /// __builtin_convertvector( value, dst type ) 6464 /// 6465 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6466 SourceLocation BuiltinLoc, 6467 SourceLocation RParenLoc) { 6468 TypeSourceInfo *TInfo; 6469 GetTypeFromParser(ParsedDestTy, &TInfo); 6470 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6471 } 6472 6473 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6474 /// i.e. an expression not of \p OverloadTy. The expression should 6475 /// unary-convert to an expression of function-pointer or 6476 /// block-pointer type. 6477 /// 6478 /// \param NDecl the declaration being called, if available 6479 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6480 SourceLocation LParenLoc, 6481 ArrayRef<Expr *> Args, 6482 SourceLocation RParenLoc, Expr *Config, 6483 bool IsExecConfig, ADLCallKind UsesADL) { 6484 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6485 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6486 6487 // Functions with 'interrupt' attribute cannot be called directly. 6488 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6489 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6490 return ExprError(); 6491 } 6492 6493 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6494 // so there's some risk when calling out to non-interrupt handler functions 6495 // that the callee might not preserve them. This is easy to diagnose here, 6496 // but can be very challenging to debug. 6497 if (auto *Caller = getCurFunctionDecl()) 6498 if (Caller->hasAttr<ARMInterruptAttr>()) { 6499 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6500 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6501 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6502 } 6503 6504 // Promote the function operand. 6505 // We special-case function promotion here because we only allow promoting 6506 // builtin functions to function pointers in the callee of a call. 6507 ExprResult Result; 6508 QualType ResultTy; 6509 if (BuiltinID && 6510 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6511 // Extract the return type from the (builtin) function pointer type. 6512 // FIXME Several builtins still have setType in 6513 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6514 // Builtins.def to ensure they are correct before removing setType calls. 6515 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6516 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6517 ResultTy = FDecl->getCallResultType(); 6518 } else { 6519 Result = CallExprUnaryConversions(Fn); 6520 ResultTy = Context.BoolTy; 6521 } 6522 if (Result.isInvalid()) 6523 return ExprError(); 6524 Fn = Result.get(); 6525 6526 // Check for a valid function type, but only if it is not a builtin which 6527 // requires custom type checking. These will be handled by 6528 // CheckBuiltinFunctionCall below just after creation of the call expression. 6529 const FunctionType *FuncT = nullptr; 6530 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6531 retry: 6532 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6533 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6534 // have type pointer to function". 6535 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6536 if (!FuncT) 6537 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6538 << Fn->getType() << Fn->getSourceRange()); 6539 } else if (const BlockPointerType *BPT = 6540 Fn->getType()->getAs<BlockPointerType>()) { 6541 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6542 } else { 6543 // Handle calls to expressions of unknown-any type. 6544 if (Fn->getType() == Context.UnknownAnyTy) { 6545 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6546 if (rewrite.isInvalid()) 6547 return ExprError(); 6548 Fn = rewrite.get(); 6549 goto retry; 6550 } 6551 6552 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6553 << Fn->getType() << Fn->getSourceRange()); 6554 } 6555 } 6556 6557 // Get the number of parameters in the function prototype, if any. 6558 // We will allocate space for max(Args.size(), NumParams) arguments 6559 // in the call expression. 6560 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6561 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6562 6563 CallExpr *TheCall; 6564 if (Config) { 6565 assert(UsesADL == ADLCallKind::NotADL && 6566 "CUDAKernelCallExpr should not use ADL"); 6567 TheCall = 6568 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6569 ResultTy, VK_RValue, RParenLoc, NumParams); 6570 } else { 6571 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6572 RParenLoc, NumParams, UsesADL); 6573 } 6574 6575 if (!getLangOpts().CPlusPlus) { 6576 // Forget about the nulled arguments since typo correction 6577 // do not handle them well. 6578 TheCall->shrinkNumArgs(Args.size()); 6579 // C cannot always handle TypoExpr nodes in builtin calls and direct 6580 // function calls as their argument checking don't necessarily handle 6581 // dependent types properly, so make sure any TypoExprs have been 6582 // dealt with. 6583 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6584 if (!Result.isUsable()) return ExprError(); 6585 CallExpr *TheOldCall = TheCall; 6586 TheCall = dyn_cast<CallExpr>(Result.get()); 6587 bool CorrectedTypos = TheCall != TheOldCall; 6588 if (!TheCall) return Result; 6589 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6590 6591 // A new call expression node was created if some typos were corrected. 6592 // However it may not have been constructed with enough storage. In this 6593 // case, rebuild the node with enough storage. The waste of space is 6594 // immaterial since this only happens when some typos were corrected. 6595 if (CorrectedTypos && Args.size() < NumParams) { 6596 if (Config) 6597 TheCall = CUDAKernelCallExpr::Create( 6598 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6599 RParenLoc, NumParams); 6600 else 6601 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6602 RParenLoc, NumParams, UsesADL); 6603 } 6604 // We can now handle the nulled arguments for the default arguments. 6605 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6606 } 6607 6608 // Bail out early if calling a builtin with custom type checking. 6609 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6610 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6611 6612 if (getLangOpts().CUDA) { 6613 if (Config) { 6614 // CUDA: Kernel calls must be to global functions 6615 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6616 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6617 << FDecl << Fn->getSourceRange()); 6618 6619 // CUDA: Kernel function must have 'void' return type 6620 if (!FuncT->getReturnType()->isVoidType() && 6621 !FuncT->getReturnType()->getAs<AutoType>() && 6622 !FuncT->getReturnType()->isInstantiationDependentType()) 6623 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6624 << Fn->getType() << Fn->getSourceRange()); 6625 } else { 6626 // CUDA: Calls to global functions must be configured 6627 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6628 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6629 << FDecl << Fn->getSourceRange()); 6630 } 6631 } 6632 6633 // Check for a valid return type 6634 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6635 FDecl)) 6636 return ExprError(); 6637 6638 // We know the result type of the call, set it. 6639 TheCall->setType(FuncT->getCallResultType(Context)); 6640 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6641 6642 if (Proto) { 6643 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6644 IsExecConfig)) 6645 return ExprError(); 6646 } else { 6647 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6648 6649 if (FDecl) { 6650 // Check if we have too few/too many template arguments, based 6651 // on our knowledge of the function definition. 6652 const FunctionDecl *Def = nullptr; 6653 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6654 Proto = Def->getType()->getAs<FunctionProtoType>(); 6655 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6656 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6657 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6658 } 6659 6660 // If the function we're calling isn't a function prototype, but we have 6661 // a function prototype from a prior declaratiom, use that prototype. 6662 if (!FDecl->hasPrototype()) 6663 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6664 } 6665 6666 // Promote the arguments (C99 6.5.2.2p6). 6667 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6668 Expr *Arg = Args[i]; 6669 6670 if (Proto && i < Proto->getNumParams()) { 6671 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6672 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6673 ExprResult ArgE = 6674 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6675 if (ArgE.isInvalid()) 6676 return true; 6677 6678 Arg = ArgE.getAs<Expr>(); 6679 6680 } else { 6681 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6682 6683 if (ArgE.isInvalid()) 6684 return true; 6685 6686 Arg = ArgE.getAs<Expr>(); 6687 } 6688 6689 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6690 diag::err_call_incomplete_argument, Arg)) 6691 return ExprError(); 6692 6693 TheCall->setArg(i, Arg); 6694 } 6695 } 6696 6697 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6698 if (!Method->isStatic()) 6699 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6700 << Fn->getSourceRange()); 6701 6702 // Check for sentinels 6703 if (NDecl) 6704 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6705 6706 // Warn for unions passing across security boundary (CMSE). 6707 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6708 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6709 if (const auto *RT = 6710 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6711 if (RT->getDecl()->isOrContainsUnion()) 6712 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6713 << 0 << i; 6714 } 6715 } 6716 } 6717 6718 // Do special checking on direct calls to functions. 6719 if (FDecl) { 6720 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6721 return ExprError(); 6722 6723 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6724 6725 if (BuiltinID) 6726 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6727 } else if (NDecl) { 6728 if (CheckPointerCall(NDecl, TheCall, Proto)) 6729 return ExprError(); 6730 } else { 6731 if (CheckOtherCall(TheCall, Proto)) 6732 return ExprError(); 6733 } 6734 6735 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6736 } 6737 6738 ExprResult 6739 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6740 SourceLocation RParenLoc, Expr *InitExpr) { 6741 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6742 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6743 6744 TypeSourceInfo *TInfo; 6745 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6746 if (!TInfo) 6747 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6748 6749 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6750 } 6751 6752 ExprResult 6753 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6754 SourceLocation RParenLoc, Expr *LiteralExpr) { 6755 QualType literalType = TInfo->getType(); 6756 6757 if (literalType->isArrayType()) { 6758 if (RequireCompleteSizedType( 6759 LParenLoc, Context.getBaseElementType(literalType), 6760 diag::err_array_incomplete_or_sizeless_type, 6761 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6762 return ExprError(); 6763 if (literalType->isVariableArrayType()) 6764 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6765 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6766 } else if (!literalType->isDependentType() && 6767 RequireCompleteType(LParenLoc, literalType, 6768 diag::err_typecheck_decl_incomplete_type, 6769 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6770 return ExprError(); 6771 6772 InitializedEntity Entity 6773 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6774 InitializationKind Kind 6775 = InitializationKind::CreateCStyleCast(LParenLoc, 6776 SourceRange(LParenLoc, RParenLoc), 6777 /*InitList=*/true); 6778 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6779 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6780 &literalType); 6781 if (Result.isInvalid()) 6782 return ExprError(); 6783 LiteralExpr = Result.get(); 6784 6785 bool isFileScope = !CurContext->isFunctionOrMethod(); 6786 6787 // In C, compound literals are l-values for some reason. 6788 // For GCC compatibility, in C++, file-scope array compound literals with 6789 // constant initializers are also l-values, and compound literals are 6790 // otherwise prvalues. 6791 // 6792 // (GCC also treats C++ list-initialized file-scope array prvalues with 6793 // constant initializers as l-values, but that's non-conforming, so we don't 6794 // follow it there.) 6795 // 6796 // FIXME: It would be better to handle the lvalue cases as materializing and 6797 // lifetime-extending a temporary object, but our materialized temporaries 6798 // representation only supports lifetime extension from a variable, not "out 6799 // of thin air". 6800 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6801 // is bound to the result of applying array-to-pointer decay to the compound 6802 // literal. 6803 // FIXME: GCC supports compound literals of reference type, which should 6804 // obviously have a value kind derived from the kind of reference involved. 6805 ExprValueKind VK = 6806 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6807 ? VK_RValue 6808 : VK_LValue; 6809 6810 if (isFileScope) 6811 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6812 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6813 Expr *Init = ILE->getInit(i); 6814 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6815 } 6816 6817 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6818 VK, LiteralExpr, isFileScope); 6819 if (isFileScope) { 6820 if (!LiteralExpr->isTypeDependent() && 6821 !LiteralExpr->isValueDependent() && 6822 !literalType->isDependentType()) // C99 6.5.2.5p3 6823 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6824 return ExprError(); 6825 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6826 literalType.getAddressSpace() != LangAS::Default) { 6827 // Embedded-C extensions to C99 6.5.2.5: 6828 // "If the compound literal occurs inside the body of a function, the 6829 // type name shall not be qualified by an address-space qualifier." 6830 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6831 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6832 return ExprError(); 6833 } 6834 6835 if (!isFileScope && !getLangOpts().CPlusPlus) { 6836 // Compound literals that have automatic storage duration are destroyed at 6837 // the end of the scope in C; in C++, they're just temporaries. 6838 6839 // Emit diagnostics if it is or contains a C union type that is non-trivial 6840 // to destruct. 6841 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6842 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6843 NTCUC_CompoundLiteral, NTCUK_Destruct); 6844 6845 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6846 if (literalType.isDestructedType()) { 6847 Cleanup.setExprNeedsCleanups(true); 6848 ExprCleanupObjects.push_back(E); 6849 getCurFunction()->setHasBranchProtectedScope(); 6850 } 6851 } 6852 6853 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6854 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6855 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6856 E->getInitializer()->getExprLoc()); 6857 6858 return MaybeBindToTemporary(E); 6859 } 6860 6861 ExprResult 6862 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6863 SourceLocation RBraceLoc) { 6864 // Only produce each kind of designated initialization diagnostic once. 6865 SourceLocation FirstDesignator; 6866 bool DiagnosedArrayDesignator = false; 6867 bool DiagnosedNestedDesignator = false; 6868 bool DiagnosedMixedDesignator = false; 6869 6870 // Check that any designated initializers are syntactically valid in the 6871 // current language mode. 6872 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6873 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6874 if (FirstDesignator.isInvalid()) 6875 FirstDesignator = DIE->getBeginLoc(); 6876 6877 if (!getLangOpts().CPlusPlus) 6878 break; 6879 6880 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6881 DiagnosedNestedDesignator = true; 6882 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6883 << DIE->getDesignatorsSourceRange(); 6884 } 6885 6886 for (auto &Desig : DIE->designators()) { 6887 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6888 DiagnosedArrayDesignator = true; 6889 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6890 << Desig.getSourceRange(); 6891 } 6892 } 6893 6894 if (!DiagnosedMixedDesignator && 6895 !isa<DesignatedInitExpr>(InitArgList[0])) { 6896 DiagnosedMixedDesignator = true; 6897 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6898 << DIE->getSourceRange(); 6899 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6900 << InitArgList[0]->getSourceRange(); 6901 } 6902 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6903 isa<DesignatedInitExpr>(InitArgList[0])) { 6904 DiagnosedMixedDesignator = true; 6905 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6906 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6907 << DIE->getSourceRange(); 6908 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6909 << InitArgList[I]->getSourceRange(); 6910 } 6911 } 6912 6913 if (FirstDesignator.isValid()) { 6914 // Only diagnose designated initiaization as a C++20 extension if we didn't 6915 // already diagnose use of (non-C++20) C99 designator syntax. 6916 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6917 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6918 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6919 ? diag::warn_cxx17_compat_designated_init 6920 : diag::ext_cxx_designated_init); 6921 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6922 Diag(FirstDesignator, diag::ext_designated_init); 6923 } 6924 } 6925 6926 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6927 } 6928 6929 ExprResult 6930 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6931 SourceLocation RBraceLoc) { 6932 // Semantic analysis for initializers is done by ActOnDeclarator() and 6933 // CheckInitializer() - it requires knowledge of the object being initialized. 6934 6935 // Immediately handle non-overload placeholders. Overloads can be 6936 // resolved contextually, but everything else here can't. 6937 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6938 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6939 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6940 6941 // Ignore failures; dropping the entire initializer list because 6942 // of one failure would be terrible for indexing/etc. 6943 if (result.isInvalid()) continue; 6944 6945 InitArgList[I] = result.get(); 6946 } 6947 } 6948 6949 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6950 RBraceLoc); 6951 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6952 return E; 6953 } 6954 6955 /// Do an explicit extend of the given block pointer if we're in ARC. 6956 void Sema::maybeExtendBlockObject(ExprResult &E) { 6957 assert(E.get()->getType()->isBlockPointerType()); 6958 assert(E.get()->isRValue()); 6959 6960 // Only do this in an r-value context. 6961 if (!getLangOpts().ObjCAutoRefCount) return; 6962 6963 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6964 CK_ARCExtendBlockObject, E.get(), 6965 /*base path*/ nullptr, VK_RValue); 6966 Cleanup.setExprNeedsCleanups(true); 6967 } 6968 6969 /// Prepare a conversion of the given expression to an ObjC object 6970 /// pointer type. 6971 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6972 QualType type = E.get()->getType(); 6973 if (type->isObjCObjectPointerType()) { 6974 return CK_BitCast; 6975 } else if (type->isBlockPointerType()) { 6976 maybeExtendBlockObject(E); 6977 return CK_BlockPointerToObjCPointerCast; 6978 } else { 6979 assert(type->isPointerType()); 6980 return CK_CPointerToObjCPointerCast; 6981 } 6982 } 6983 6984 /// Prepares for a scalar cast, performing all the necessary stages 6985 /// except the final cast and returning the kind required. 6986 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6987 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6988 // Also, callers should have filtered out the invalid cases with 6989 // pointers. Everything else should be possible. 6990 6991 QualType SrcTy = Src.get()->getType(); 6992 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6993 return CK_NoOp; 6994 6995 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6996 case Type::STK_MemberPointer: 6997 llvm_unreachable("member pointer type in C"); 6998 6999 case Type::STK_CPointer: 7000 case Type::STK_BlockPointer: 7001 case Type::STK_ObjCObjectPointer: 7002 switch (DestTy->getScalarTypeKind()) { 7003 case Type::STK_CPointer: { 7004 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7005 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7006 if (SrcAS != DestAS) 7007 return CK_AddressSpaceConversion; 7008 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7009 return CK_NoOp; 7010 return CK_BitCast; 7011 } 7012 case Type::STK_BlockPointer: 7013 return (SrcKind == Type::STK_BlockPointer 7014 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7015 case Type::STK_ObjCObjectPointer: 7016 if (SrcKind == Type::STK_ObjCObjectPointer) 7017 return CK_BitCast; 7018 if (SrcKind == Type::STK_CPointer) 7019 return CK_CPointerToObjCPointerCast; 7020 maybeExtendBlockObject(Src); 7021 return CK_BlockPointerToObjCPointerCast; 7022 case Type::STK_Bool: 7023 return CK_PointerToBoolean; 7024 case Type::STK_Integral: 7025 return CK_PointerToIntegral; 7026 case Type::STK_Floating: 7027 case Type::STK_FloatingComplex: 7028 case Type::STK_IntegralComplex: 7029 case Type::STK_MemberPointer: 7030 case Type::STK_FixedPoint: 7031 llvm_unreachable("illegal cast from pointer"); 7032 } 7033 llvm_unreachable("Should have returned before this"); 7034 7035 case Type::STK_FixedPoint: 7036 switch (DestTy->getScalarTypeKind()) { 7037 case Type::STK_FixedPoint: 7038 return CK_FixedPointCast; 7039 case Type::STK_Bool: 7040 return CK_FixedPointToBoolean; 7041 case Type::STK_Integral: 7042 return CK_FixedPointToIntegral; 7043 case Type::STK_Floating: 7044 case Type::STK_IntegralComplex: 7045 case Type::STK_FloatingComplex: 7046 Diag(Src.get()->getExprLoc(), 7047 diag::err_unimplemented_conversion_with_fixed_point_type) 7048 << DestTy; 7049 return CK_IntegralCast; 7050 case Type::STK_CPointer: 7051 case Type::STK_ObjCObjectPointer: 7052 case Type::STK_BlockPointer: 7053 case Type::STK_MemberPointer: 7054 llvm_unreachable("illegal cast to pointer type"); 7055 } 7056 llvm_unreachable("Should have returned before this"); 7057 7058 case Type::STK_Bool: // casting from bool is like casting from an integer 7059 case Type::STK_Integral: 7060 switch (DestTy->getScalarTypeKind()) { 7061 case Type::STK_CPointer: 7062 case Type::STK_ObjCObjectPointer: 7063 case Type::STK_BlockPointer: 7064 if (Src.get()->isNullPointerConstant(Context, 7065 Expr::NPC_ValueDependentIsNull)) 7066 return CK_NullToPointer; 7067 return CK_IntegralToPointer; 7068 case Type::STK_Bool: 7069 return CK_IntegralToBoolean; 7070 case Type::STK_Integral: 7071 return CK_IntegralCast; 7072 case Type::STK_Floating: 7073 return CK_IntegralToFloating; 7074 case Type::STK_IntegralComplex: 7075 Src = ImpCastExprToType(Src.get(), 7076 DestTy->castAs<ComplexType>()->getElementType(), 7077 CK_IntegralCast); 7078 return CK_IntegralRealToComplex; 7079 case Type::STK_FloatingComplex: 7080 Src = ImpCastExprToType(Src.get(), 7081 DestTy->castAs<ComplexType>()->getElementType(), 7082 CK_IntegralToFloating); 7083 return CK_FloatingRealToComplex; 7084 case Type::STK_MemberPointer: 7085 llvm_unreachable("member pointer type in C"); 7086 case Type::STK_FixedPoint: 7087 return CK_IntegralToFixedPoint; 7088 } 7089 llvm_unreachable("Should have returned before this"); 7090 7091 case Type::STK_Floating: 7092 switch (DestTy->getScalarTypeKind()) { 7093 case Type::STK_Floating: 7094 return CK_FloatingCast; 7095 case Type::STK_Bool: 7096 return CK_FloatingToBoolean; 7097 case Type::STK_Integral: 7098 return CK_FloatingToIntegral; 7099 case Type::STK_FloatingComplex: 7100 Src = ImpCastExprToType(Src.get(), 7101 DestTy->castAs<ComplexType>()->getElementType(), 7102 CK_FloatingCast); 7103 return CK_FloatingRealToComplex; 7104 case Type::STK_IntegralComplex: 7105 Src = ImpCastExprToType(Src.get(), 7106 DestTy->castAs<ComplexType>()->getElementType(), 7107 CK_FloatingToIntegral); 7108 return CK_IntegralRealToComplex; 7109 case Type::STK_CPointer: 7110 case Type::STK_ObjCObjectPointer: 7111 case Type::STK_BlockPointer: 7112 llvm_unreachable("valid float->pointer cast?"); 7113 case Type::STK_MemberPointer: 7114 llvm_unreachable("member pointer type in C"); 7115 case Type::STK_FixedPoint: 7116 Diag(Src.get()->getExprLoc(), 7117 diag::err_unimplemented_conversion_with_fixed_point_type) 7118 << SrcTy; 7119 return CK_IntegralCast; 7120 } 7121 llvm_unreachable("Should have returned before this"); 7122 7123 case Type::STK_FloatingComplex: 7124 switch (DestTy->getScalarTypeKind()) { 7125 case Type::STK_FloatingComplex: 7126 return CK_FloatingComplexCast; 7127 case Type::STK_IntegralComplex: 7128 return CK_FloatingComplexToIntegralComplex; 7129 case Type::STK_Floating: { 7130 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7131 if (Context.hasSameType(ET, DestTy)) 7132 return CK_FloatingComplexToReal; 7133 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7134 return CK_FloatingCast; 7135 } 7136 case Type::STK_Bool: 7137 return CK_FloatingComplexToBoolean; 7138 case Type::STK_Integral: 7139 Src = ImpCastExprToType(Src.get(), 7140 SrcTy->castAs<ComplexType>()->getElementType(), 7141 CK_FloatingComplexToReal); 7142 return CK_FloatingToIntegral; 7143 case Type::STK_CPointer: 7144 case Type::STK_ObjCObjectPointer: 7145 case Type::STK_BlockPointer: 7146 llvm_unreachable("valid complex float->pointer cast?"); 7147 case Type::STK_MemberPointer: 7148 llvm_unreachable("member pointer type in C"); 7149 case Type::STK_FixedPoint: 7150 Diag(Src.get()->getExprLoc(), 7151 diag::err_unimplemented_conversion_with_fixed_point_type) 7152 << SrcTy; 7153 return CK_IntegralCast; 7154 } 7155 llvm_unreachable("Should have returned before this"); 7156 7157 case Type::STK_IntegralComplex: 7158 switch (DestTy->getScalarTypeKind()) { 7159 case Type::STK_FloatingComplex: 7160 return CK_IntegralComplexToFloatingComplex; 7161 case Type::STK_IntegralComplex: 7162 return CK_IntegralComplexCast; 7163 case Type::STK_Integral: { 7164 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7165 if (Context.hasSameType(ET, DestTy)) 7166 return CK_IntegralComplexToReal; 7167 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7168 return CK_IntegralCast; 7169 } 7170 case Type::STK_Bool: 7171 return CK_IntegralComplexToBoolean; 7172 case Type::STK_Floating: 7173 Src = ImpCastExprToType(Src.get(), 7174 SrcTy->castAs<ComplexType>()->getElementType(), 7175 CK_IntegralComplexToReal); 7176 return CK_IntegralToFloating; 7177 case Type::STK_CPointer: 7178 case Type::STK_ObjCObjectPointer: 7179 case Type::STK_BlockPointer: 7180 llvm_unreachable("valid complex int->pointer cast?"); 7181 case Type::STK_MemberPointer: 7182 llvm_unreachable("member pointer type in C"); 7183 case Type::STK_FixedPoint: 7184 Diag(Src.get()->getExprLoc(), 7185 diag::err_unimplemented_conversion_with_fixed_point_type) 7186 << SrcTy; 7187 return CK_IntegralCast; 7188 } 7189 llvm_unreachable("Should have returned before this"); 7190 } 7191 7192 llvm_unreachable("Unhandled scalar cast"); 7193 } 7194 7195 static bool breakDownVectorType(QualType type, uint64_t &len, 7196 QualType &eltType) { 7197 // Vectors are simple. 7198 if (const VectorType *vecType = type->getAs<VectorType>()) { 7199 len = vecType->getNumElements(); 7200 eltType = vecType->getElementType(); 7201 assert(eltType->isScalarType()); 7202 return true; 7203 } 7204 7205 // We allow lax conversion to and from non-vector types, but only if 7206 // they're real types (i.e. non-complex, non-pointer scalar types). 7207 if (!type->isRealType()) return false; 7208 7209 len = 1; 7210 eltType = type; 7211 return true; 7212 } 7213 7214 /// Are the two types lax-compatible vector types? That is, given 7215 /// that one of them is a vector, do they have equal storage sizes, 7216 /// where the storage size is the number of elements times the element 7217 /// size? 7218 /// 7219 /// This will also return false if either of the types is neither a 7220 /// vector nor a real type. 7221 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7222 assert(destTy->isVectorType() || srcTy->isVectorType()); 7223 7224 // Disallow lax conversions between scalars and ExtVectors (these 7225 // conversions are allowed for other vector types because common headers 7226 // depend on them). Most scalar OP ExtVector cases are handled by the 7227 // splat path anyway, which does what we want (convert, not bitcast). 7228 // What this rules out for ExtVectors is crazy things like char4*float. 7229 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7230 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7231 7232 uint64_t srcLen, destLen; 7233 QualType srcEltTy, destEltTy; 7234 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7235 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7236 7237 // ASTContext::getTypeSize will return the size rounded up to a 7238 // power of 2, so instead of using that, we need to use the raw 7239 // element size multiplied by the element count. 7240 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7241 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7242 7243 return (srcLen * srcEltSize == destLen * destEltSize); 7244 } 7245 7246 /// Is this a legal conversion between two types, one of which is 7247 /// known to be a vector type? 7248 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7249 assert(destTy->isVectorType() || srcTy->isVectorType()); 7250 7251 switch (Context.getLangOpts().getLaxVectorConversions()) { 7252 case LangOptions::LaxVectorConversionKind::None: 7253 return false; 7254 7255 case LangOptions::LaxVectorConversionKind::Integer: 7256 if (!srcTy->isIntegralOrEnumerationType()) { 7257 auto *Vec = srcTy->getAs<VectorType>(); 7258 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7259 return false; 7260 } 7261 if (!destTy->isIntegralOrEnumerationType()) { 7262 auto *Vec = destTy->getAs<VectorType>(); 7263 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7264 return false; 7265 } 7266 // OK, integer (vector) -> integer (vector) bitcast. 7267 break; 7268 7269 case LangOptions::LaxVectorConversionKind::All: 7270 break; 7271 } 7272 7273 return areLaxCompatibleVectorTypes(srcTy, destTy); 7274 } 7275 7276 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7277 CastKind &Kind) { 7278 assert(VectorTy->isVectorType() && "Not a vector type!"); 7279 7280 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7281 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7282 return Diag(R.getBegin(), 7283 Ty->isVectorType() ? 7284 diag::err_invalid_conversion_between_vectors : 7285 diag::err_invalid_conversion_between_vector_and_integer) 7286 << VectorTy << Ty << R; 7287 } else 7288 return Diag(R.getBegin(), 7289 diag::err_invalid_conversion_between_vector_and_scalar) 7290 << VectorTy << Ty << R; 7291 7292 Kind = CK_BitCast; 7293 return false; 7294 } 7295 7296 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7297 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7298 7299 if (DestElemTy == SplattedExpr->getType()) 7300 return SplattedExpr; 7301 7302 assert(DestElemTy->isFloatingType() || 7303 DestElemTy->isIntegralOrEnumerationType()); 7304 7305 CastKind CK; 7306 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7307 // OpenCL requires that we convert `true` boolean expressions to -1, but 7308 // only when splatting vectors. 7309 if (DestElemTy->isFloatingType()) { 7310 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7311 // in two steps: boolean to signed integral, then to floating. 7312 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7313 CK_BooleanToSignedIntegral); 7314 SplattedExpr = CastExprRes.get(); 7315 CK = CK_IntegralToFloating; 7316 } else { 7317 CK = CK_BooleanToSignedIntegral; 7318 } 7319 } else { 7320 ExprResult CastExprRes = SplattedExpr; 7321 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7322 if (CastExprRes.isInvalid()) 7323 return ExprError(); 7324 SplattedExpr = CastExprRes.get(); 7325 } 7326 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7327 } 7328 7329 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7330 Expr *CastExpr, CastKind &Kind) { 7331 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7332 7333 QualType SrcTy = CastExpr->getType(); 7334 7335 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7336 // an ExtVectorType. 7337 // In OpenCL, casts between vectors of different types are not allowed. 7338 // (See OpenCL 6.2). 7339 if (SrcTy->isVectorType()) { 7340 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7341 (getLangOpts().OpenCL && 7342 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7343 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7344 << DestTy << SrcTy << R; 7345 return ExprError(); 7346 } 7347 Kind = CK_BitCast; 7348 return CastExpr; 7349 } 7350 7351 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7352 // conversion will take place first from scalar to elt type, and then 7353 // splat from elt type to vector. 7354 if (SrcTy->isPointerType()) 7355 return Diag(R.getBegin(), 7356 diag::err_invalid_conversion_between_vector_and_scalar) 7357 << DestTy << SrcTy << R; 7358 7359 Kind = CK_VectorSplat; 7360 return prepareVectorSplat(DestTy, CastExpr); 7361 } 7362 7363 ExprResult 7364 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7365 Declarator &D, ParsedType &Ty, 7366 SourceLocation RParenLoc, Expr *CastExpr) { 7367 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7368 "ActOnCastExpr(): missing type or expr"); 7369 7370 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7371 if (D.isInvalidType()) 7372 return ExprError(); 7373 7374 if (getLangOpts().CPlusPlus) { 7375 // Check that there are no default arguments (C++ only). 7376 CheckExtraCXXDefaultArguments(D); 7377 } else { 7378 // Make sure any TypoExprs have been dealt with. 7379 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7380 if (!Res.isUsable()) 7381 return ExprError(); 7382 CastExpr = Res.get(); 7383 } 7384 7385 checkUnusedDeclAttributes(D); 7386 7387 QualType castType = castTInfo->getType(); 7388 Ty = CreateParsedType(castType, castTInfo); 7389 7390 bool isVectorLiteral = false; 7391 7392 // Check for an altivec or OpenCL literal, 7393 // i.e. all the elements are integer constants. 7394 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7395 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7396 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7397 && castType->isVectorType() && (PE || PLE)) { 7398 if (PLE && PLE->getNumExprs() == 0) { 7399 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7400 return ExprError(); 7401 } 7402 if (PE || PLE->getNumExprs() == 1) { 7403 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7404 if (!E->getType()->isVectorType()) 7405 isVectorLiteral = true; 7406 } 7407 else 7408 isVectorLiteral = true; 7409 } 7410 7411 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7412 // then handle it as such. 7413 if (isVectorLiteral) 7414 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7415 7416 // If the Expr being casted is a ParenListExpr, handle it specially. 7417 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7418 // sequence of BinOp comma operators. 7419 if (isa<ParenListExpr>(CastExpr)) { 7420 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7421 if (Result.isInvalid()) return ExprError(); 7422 CastExpr = Result.get(); 7423 } 7424 7425 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7426 !getSourceManager().isInSystemMacro(LParenLoc)) 7427 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7428 7429 CheckTollFreeBridgeCast(castType, CastExpr); 7430 7431 CheckObjCBridgeRelatedCast(castType, CastExpr); 7432 7433 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7434 7435 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7436 } 7437 7438 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7439 SourceLocation RParenLoc, Expr *E, 7440 TypeSourceInfo *TInfo) { 7441 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7442 "Expected paren or paren list expression"); 7443 7444 Expr **exprs; 7445 unsigned numExprs; 7446 Expr *subExpr; 7447 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7448 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7449 LiteralLParenLoc = PE->getLParenLoc(); 7450 LiteralRParenLoc = PE->getRParenLoc(); 7451 exprs = PE->getExprs(); 7452 numExprs = PE->getNumExprs(); 7453 } else { // isa<ParenExpr> by assertion at function entrance 7454 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7455 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7456 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7457 exprs = &subExpr; 7458 numExprs = 1; 7459 } 7460 7461 QualType Ty = TInfo->getType(); 7462 assert(Ty->isVectorType() && "Expected vector type"); 7463 7464 SmallVector<Expr *, 8> initExprs; 7465 const VectorType *VTy = Ty->castAs<VectorType>(); 7466 unsigned numElems = VTy->getNumElements(); 7467 7468 // '(...)' form of vector initialization in AltiVec: the number of 7469 // initializers must be one or must match the size of the vector. 7470 // If a single value is specified in the initializer then it will be 7471 // replicated to all the components of the vector 7472 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7473 // The number of initializers must be one or must match the size of the 7474 // vector. If a single value is specified in the initializer then it will 7475 // be replicated to all the components of the vector 7476 if (numExprs == 1) { 7477 QualType ElemTy = VTy->getElementType(); 7478 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7479 if (Literal.isInvalid()) 7480 return ExprError(); 7481 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7482 PrepareScalarCast(Literal, ElemTy)); 7483 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7484 } 7485 else if (numExprs < numElems) { 7486 Diag(E->getExprLoc(), 7487 diag::err_incorrect_number_of_vector_initializers); 7488 return ExprError(); 7489 } 7490 else 7491 initExprs.append(exprs, exprs + numExprs); 7492 } 7493 else { 7494 // For OpenCL, when the number of initializers is a single value, 7495 // it will be replicated to all components of the vector. 7496 if (getLangOpts().OpenCL && 7497 VTy->getVectorKind() == VectorType::GenericVector && 7498 numExprs == 1) { 7499 QualType ElemTy = VTy->getElementType(); 7500 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7501 if (Literal.isInvalid()) 7502 return ExprError(); 7503 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7504 PrepareScalarCast(Literal, ElemTy)); 7505 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7506 } 7507 7508 initExprs.append(exprs, exprs + numExprs); 7509 } 7510 // FIXME: This means that pretty-printing the final AST will produce curly 7511 // braces instead of the original commas. 7512 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7513 initExprs, LiteralRParenLoc); 7514 initE->setType(Ty); 7515 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7516 } 7517 7518 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7519 /// the ParenListExpr into a sequence of comma binary operators. 7520 ExprResult 7521 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7522 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7523 if (!E) 7524 return OrigExpr; 7525 7526 ExprResult Result(E->getExpr(0)); 7527 7528 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7529 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7530 E->getExpr(i)); 7531 7532 if (Result.isInvalid()) return ExprError(); 7533 7534 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7535 } 7536 7537 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7538 SourceLocation R, 7539 MultiExprArg Val) { 7540 return ParenListExpr::Create(Context, L, Val, R); 7541 } 7542 7543 /// Emit a specialized diagnostic when one expression is a null pointer 7544 /// constant and the other is not a pointer. Returns true if a diagnostic is 7545 /// emitted. 7546 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7547 SourceLocation QuestionLoc) { 7548 Expr *NullExpr = LHSExpr; 7549 Expr *NonPointerExpr = RHSExpr; 7550 Expr::NullPointerConstantKind NullKind = 7551 NullExpr->isNullPointerConstant(Context, 7552 Expr::NPC_ValueDependentIsNotNull); 7553 7554 if (NullKind == Expr::NPCK_NotNull) { 7555 NullExpr = RHSExpr; 7556 NonPointerExpr = LHSExpr; 7557 NullKind = 7558 NullExpr->isNullPointerConstant(Context, 7559 Expr::NPC_ValueDependentIsNotNull); 7560 } 7561 7562 if (NullKind == Expr::NPCK_NotNull) 7563 return false; 7564 7565 if (NullKind == Expr::NPCK_ZeroExpression) 7566 return false; 7567 7568 if (NullKind == Expr::NPCK_ZeroLiteral) { 7569 // In this case, check to make sure that we got here from a "NULL" 7570 // string in the source code. 7571 NullExpr = NullExpr->IgnoreParenImpCasts(); 7572 SourceLocation loc = NullExpr->getExprLoc(); 7573 if (!findMacroSpelling(loc, "NULL")) 7574 return false; 7575 } 7576 7577 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7578 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7579 << NonPointerExpr->getType() << DiagType 7580 << NonPointerExpr->getSourceRange(); 7581 return true; 7582 } 7583 7584 /// Return false if the condition expression is valid, true otherwise. 7585 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7586 QualType CondTy = Cond->getType(); 7587 7588 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7589 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7590 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7591 << CondTy << Cond->getSourceRange(); 7592 return true; 7593 } 7594 7595 // C99 6.5.15p2 7596 if (CondTy->isScalarType()) return false; 7597 7598 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7599 << CondTy << Cond->getSourceRange(); 7600 return true; 7601 } 7602 7603 /// Handle when one or both operands are void type. 7604 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7605 ExprResult &RHS) { 7606 Expr *LHSExpr = LHS.get(); 7607 Expr *RHSExpr = RHS.get(); 7608 7609 if (!LHSExpr->getType()->isVoidType()) 7610 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7611 << RHSExpr->getSourceRange(); 7612 if (!RHSExpr->getType()->isVoidType()) 7613 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7614 << LHSExpr->getSourceRange(); 7615 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7616 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7617 return S.Context.VoidTy; 7618 } 7619 7620 /// Return false if the NullExpr can be promoted to PointerTy, 7621 /// true otherwise. 7622 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7623 QualType PointerTy) { 7624 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7625 !NullExpr.get()->isNullPointerConstant(S.Context, 7626 Expr::NPC_ValueDependentIsNull)) 7627 return true; 7628 7629 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7630 return false; 7631 } 7632 7633 /// Checks compatibility between two pointers and return the resulting 7634 /// type. 7635 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7636 ExprResult &RHS, 7637 SourceLocation Loc) { 7638 QualType LHSTy = LHS.get()->getType(); 7639 QualType RHSTy = RHS.get()->getType(); 7640 7641 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7642 // Two identical pointers types are always compatible. 7643 return LHSTy; 7644 } 7645 7646 QualType lhptee, rhptee; 7647 7648 // Get the pointee types. 7649 bool IsBlockPointer = false; 7650 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7651 lhptee = LHSBTy->getPointeeType(); 7652 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7653 IsBlockPointer = true; 7654 } else { 7655 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7656 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7657 } 7658 7659 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7660 // differently qualified versions of compatible types, the result type is 7661 // a pointer to an appropriately qualified version of the composite 7662 // type. 7663 7664 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7665 // clause doesn't make sense for our extensions. E.g. address space 2 should 7666 // be incompatible with address space 3: they may live on different devices or 7667 // anything. 7668 Qualifiers lhQual = lhptee.getQualifiers(); 7669 Qualifiers rhQual = rhptee.getQualifiers(); 7670 7671 LangAS ResultAddrSpace = LangAS::Default; 7672 LangAS LAddrSpace = lhQual.getAddressSpace(); 7673 LangAS RAddrSpace = rhQual.getAddressSpace(); 7674 7675 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7676 // spaces is disallowed. 7677 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7678 ResultAddrSpace = LAddrSpace; 7679 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7680 ResultAddrSpace = RAddrSpace; 7681 else { 7682 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7683 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7684 << RHS.get()->getSourceRange(); 7685 return QualType(); 7686 } 7687 7688 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7689 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7690 lhQual.removeCVRQualifiers(); 7691 rhQual.removeCVRQualifiers(); 7692 7693 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7694 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7695 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7696 // qual types are compatible iff 7697 // * corresponded types are compatible 7698 // * CVR qualifiers are equal 7699 // * address spaces are equal 7700 // Thus for conditional operator we merge CVR and address space unqualified 7701 // pointees and if there is a composite type we return a pointer to it with 7702 // merged qualifiers. 7703 LHSCastKind = 7704 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7705 RHSCastKind = 7706 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7707 lhQual.removeAddressSpace(); 7708 rhQual.removeAddressSpace(); 7709 7710 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7711 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7712 7713 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7714 7715 if (CompositeTy.isNull()) { 7716 // In this situation, we assume void* type. No especially good 7717 // reason, but this is what gcc does, and we do have to pick 7718 // to get a consistent AST. 7719 QualType incompatTy; 7720 incompatTy = S.Context.getPointerType( 7721 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7722 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7723 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7724 7725 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7726 // for casts between types with incompatible address space qualifiers. 7727 // For the following code the compiler produces casts between global and 7728 // local address spaces of the corresponded innermost pointees: 7729 // local int *global *a; 7730 // global int *global *b; 7731 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7732 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7733 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7734 << RHS.get()->getSourceRange(); 7735 7736 return incompatTy; 7737 } 7738 7739 // The pointer types are compatible. 7740 // In case of OpenCL ResultTy should have the address space qualifier 7741 // which is a superset of address spaces of both the 2nd and the 3rd 7742 // operands of the conditional operator. 7743 QualType ResultTy = [&, ResultAddrSpace]() { 7744 if (S.getLangOpts().OpenCL) { 7745 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7746 CompositeQuals.setAddressSpace(ResultAddrSpace); 7747 return S.Context 7748 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7749 .withCVRQualifiers(MergedCVRQual); 7750 } 7751 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7752 }(); 7753 if (IsBlockPointer) 7754 ResultTy = S.Context.getBlockPointerType(ResultTy); 7755 else 7756 ResultTy = S.Context.getPointerType(ResultTy); 7757 7758 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7759 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7760 return ResultTy; 7761 } 7762 7763 /// Return the resulting type when the operands are both block pointers. 7764 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7765 ExprResult &LHS, 7766 ExprResult &RHS, 7767 SourceLocation Loc) { 7768 QualType LHSTy = LHS.get()->getType(); 7769 QualType RHSTy = RHS.get()->getType(); 7770 7771 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7772 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7773 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7774 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7775 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7776 return destType; 7777 } 7778 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7779 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7780 << RHS.get()->getSourceRange(); 7781 return QualType(); 7782 } 7783 7784 // We have 2 block pointer types. 7785 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7786 } 7787 7788 /// Return the resulting type when the operands are both pointers. 7789 static QualType 7790 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7791 ExprResult &RHS, 7792 SourceLocation Loc) { 7793 // get the pointer types 7794 QualType LHSTy = LHS.get()->getType(); 7795 QualType RHSTy = RHS.get()->getType(); 7796 7797 // get the "pointed to" types 7798 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7799 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7800 7801 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7802 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7803 // Figure out necessary qualifiers (C99 6.5.15p6) 7804 QualType destPointee 7805 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7806 QualType destType = S.Context.getPointerType(destPointee); 7807 // Add qualifiers if necessary. 7808 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7809 // Promote to void*. 7810 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7811 return destType; 7812 } 7813 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7814 QualType destPointee 7815 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7816 QualType destType = S.Context.getPointerType(destPointee); 7817 // Add qualifiers if necessary. 7818 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7819 // Promote to void*. 7820 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7821 return destType; 7822 } 7823 7824 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7825 } 7826 7827 /// Return false if the first expression is not an integer and the second 7828 /// expression is not a pointer, true otherwise. 7829 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7830 Expr* PointerExpr, SourceLocation Loc, 7831 bool IsIntFirstExpr) { 7832 if (!PointerExpr->getType()->isPointerType() || 7833 !Int.get()->getType()->isIntegerType()) 7834 return false; 7835 7836 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7837 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7838 7839 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7840 << Expr1->getType() << Expr2->getType() 7841 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7842 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7843 CK_IntegralToPointer); 7844 return true; 7845 } 7846 7847 /// Simple conversion between integer and floating point types. 7848 /// 7849 /// Used when handling the OpenCL conditional operator where the 7850 /// condition is a vector while the other operands are scalar. 7851 /// 7852 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7853 /// types are either integer or floating type. Between the two 7854 /// operands, the type with the higher rank is defined as the "result 7855 /// type". The other operand needs to be promoted to the same type. No 7856 /// other type promotion is allowed. We cannot use 7857 /// UsualArithmeticConversions() for this purpose, since it always 7858 /// promotes promotable types. 7859 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7860 ExprResult &RHS, 7861 SourceLocation QuestionLoc) { 7862 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7863 if (LHS.isInvalid()) 7864 return QualType(); 7865 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7866 if (RHS.isInvalid()) 7867 return QualType(); 7868 7869 // For conversion purposes, we ignore any qualifiers. 7870 // For example, "const float" and "float" are equivalent. 7871 QualType LHSType = 7872 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7873 QualType RHSType = 7874 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7875 7876 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7877 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7878 << LHSType << LHS.get()->getSourceRange(); 7879 return QualType(); 7880 } 7881 7882 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7883 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7884 << RHSType << RHS.get()->getSourceRange(); 7885 return QualType(); 7886 } 7887 7888 // If both types are identical, no conversion is needed. 7889 if (LHSType == RHSType) 7890 return LHSType; 7891 7892 // Now handle "real" floating types (i.e. float, double, long double). 7893 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7894 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7895 /*IsCompAssign = */ false); 7896 7897 // Finally, we have two differing integer types. 7898 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7899 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7900 } 7901 7902 /// Convert scalar operands to a vector that matches the 7903 /// condition in length. 7904 /// 7905 /// Used when handling the OpenCL conditional operator where the 7906 /// condition is a vector while the other operands are scalar. 7907 /// 7908 /// We first compute the "result type" for the scalar operands 7909 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7910 /// into a vector of that type where the length matches the condition 7911 /// vector type. s6.11.6 requires that the element types of the result 7912 /// and the condition must have the same number of bits. 7913 static QualType 7914 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7915 QualType CondTy, SourceLocation QuestionLoc) { 7916 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7917 if (ResTy.isNull()) return QualType(); 7918 7919 const VectorType *CV = CondTy->getAs<VectorType>(); 7920 assert(CV); 7921 7922 // Determine the vector result type 7923 unsigned NumElements = CV->getNumElements(); 7924 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7925 7926 // Ensure that all types have the same number of bits 7927 if (S.Context.getTypeSize(CV->getElementType()) 7928 != S.Context.getTypeSize(ResTy)) { 7929 // Since VectorTy is created internally, it does not pretty print 7930 // with an OpenCL name. Instead, we just print a description. 7931 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7932 SmallString<64> Str; 7933 llvm::raw_svector_ostream OS(Str); 7934 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7935 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7936 << CondTy << OS.str(); 7937 return QualType(); 7938 } 7939 7940 // Convert operands to the vector result type 7941 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7942 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7943 7944 return VectorTy; 7945 } 7946 7947 /// Return false if this is a valid OpenCL condition vector 7948 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7949 SourceLocation QuestionLoc) { 7950 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7951 // integral type. 7952 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7953 assert(CondTy); 7954 QualType EleTy = CondTy->getElementType(); 7955 if (EleTy->isIntegerType()) return false; 7956 7957 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7958 << Cond->getType() << Cond->getSourceRange(); 7959 return true; 7960 } 7961 7962 /// Return false if the vector condition type and the vector 7963 /// result type are compatible. 7964 /// 7965 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7966 /// number of elements, and their element types have the same number 7967 /// of bits. 7968 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7969 SourceLocation QuestionLoc) { 7970 const VectorType *CV = CondTy->getAs<VectorType>(); 7971 const VectorType *RV = VecResTy->getAs<VectorType>(); 7972 assert(CV && RV); 7973 7974 if (CV->getNumElements() != RV->getNumElements()) { 7975 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7976 << CondTy << VecResTy; 7977 return true; 7978 } 7979 7980 QualType CVE = CV->getElementType(); 7981 QualType RVE = RV->getElementType(); 7982 7983 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7984 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7985 << CondTy << VecResTy; 7986 return true; 7987 } 7988 7989 return false; 7990 } 7991 7992 /// Return the resulting type for the conditional operator in 7993 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7994 /// s6.3.i) when the condition is a vector type. 7995 static QualType 7996 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7997 ExprResult &LHS, ExprResult &RHS, 7998 SourceLocation QuestionLoc) { 7999 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8000 if (Cond.isInvalid()) 8001 return QualType(); 8002 QualType CondTy = Cond.get()->getType(); 8003 8004 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8005 return QualType(); 8006 8007 // If either operand is a vector then find the vector type of the 8008 // result as specified in OpenCL v1.1 s6.3.i. 8009 if (LHS.get()->getType()->isVectorType() || 8010 RHS.get()->getType()->isVectorType()) { 8011 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8012 /*isCompAssign*/false, 8013 /*AllowBothBool*/true, 8014 /*AllowBoolConversions*/false); 8015 if (VecResTy.isNull()) return QualType(); 8016 // The result type must match the condition type as specified in 8017 // OpenCL v1.1 s6.11.6. 8018 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8019 return QualType(); 8020 return VecResTy; 8021 } 8022 8023 // Both operands are scalar. 8024 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8025 } 8026 8027 /// Return true if the Expr is block type 8028 static bool checkBlockType(Sema &S, const Expr *E) { 8029 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8030 QualType Ty = CE->getCallee()->getType(); 8031 if (Ty->isBlockPointerType()) { 8032 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8033 return true; 8034 } 8035 } 8036 return false; 8037 } 8038 8039 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8040 /// In that case, LHS = cond. 8041 /// C99 6.5.15 8042 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8043 ExprResult &RHS, ExprValueKind &VK, 8044 ExprObjectKind &OK, 8045 SourceLocation QuestionLoc) { 8046 8047 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8048 if (!LHSResult.isUsable()) return QualType(); 8049 LHS = LHSResult; 8050 8051 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8052 if (!RHSResult.isUsable()) return QualType(); 8053 RHS = RHSResult; 8054 8055 // C++ is sufficiently different to merit its own checker. 8056 if (getLangOpts().CPlusPlus) 8057 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8058 8059 VK = VK_RValue; 8060 OK = OK_Ordinary; 8061 8062 // The OpenCL operator with a vector condition is sufficiently 8063 // different to merit its own checker. 8064 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8065 Cond.get()->getType()->isExtVectorType()) 8066 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8067 8068 // First, check the condition. 8069 Cond = UsualUnaryConversions(Cond.get()); 8070 if (Cond.isInvalid()) 8071 return QualType(); 8072 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8073 return QualType(); 8074 8075 // Now check the two expressions. 8076 if (LHS.get()->getType()->isVectorType() || 8077 RHS.get()->getType()->isVectorType()) 8078 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8079 /*AllowBothBool*/true, 8080 /*AllowBoolConversions*/false); 8081 8082 QualType ResTy = 8083 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8084 if (LHS.isInvalid() || RHS.isInvalid()) 8085 return QualType(); 8086 8087 QualType LHSTy = LHS.get()->getType(); 8088 QualType RHSTy = RHS.get()->getType(); 8089 8090 // Diagnose attempts to convert between __float128 and long double where 8091 // such conversions currently can't be handled. 8092 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8093 Diag(QuestionLoc, 8094 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8095 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8096 return QualType(); 8097 } 8098 8099 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8100 // selection operator (?:). 8101 if (getLangOpts().OpenCL && 8102 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8103 return QualType(); 8104 } 8105 8106 // If both operands have arithmetic type, do the usual arithmetic conversions 8107 // to find a common type: C99 6.5.15p3,5. 8108 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8109 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8110 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8111 8112 return ResTy; 8113 } 8114 8115 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8116 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8117 return LHSTy; 8118 } 8119 8120 // If both operands are the same structure or union type, the result is that 8121 // type. 8122 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8123 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8124 if (LHSRT->getDecl() == RHSRT->getDecl()) 8125 // "If both the operands have structure or union type, the result has 8126 // that type." This implies that CV qualifiers are dropped. 8127 return LHSTy.getUnqualifiedType(); 8128 // FIXME: Type of conditional expression must be complete in C mode. 8129 } 8130 8131 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8132 // The following || allows only one side to be void (a GCC-ism). 8133 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8134 return checkConditionalVoidType(*this, LHS, RHS); 8135 } 8136 8137 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8138 // the type of the other operand." 8139 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8140 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8141 8142 // All objective-c pointer type analysis is done here. 8143 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8144 QuestionLoc); 8145 if (LHS.isInvalid() || RHS.isInvalid()) 8146 return QualType(); 8147 if (!compositeType.isNull()) 8148 return compositeType; 8149 8150 8151 // Handle block pointer types. 8152 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8153 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8154 QuestionLoc); 8155 8156 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8157 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8158 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8159 QuestionLoc); 8160 8161 // GCC compatibility: soften pointer/integer mismatch. Note that 8162 // null pointers have been filtered out by this point. 8163 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8164 /*IsIntFirstExpr=*/true)) 8165 return RHSTy; 8166 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8167 /*IsIntFirstExpr=*/false)) 8168 return LHSTy; 8169 8170 // Allow ?: operations in which both operands have the same 8171 // built-in sizeless type. 8172 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8173 return LHSTy; 8174 8175 // Emit a better diagnostic if one of the expressions is a null pointer 8176 // constant and the other is not a pointer type. In this case, the user most 8177 // likely forgot to take the address of the other expression. 8178 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8179 return QualType(); 8180 8181 // Otherwise, the operands are not compatible. 8182 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8183 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8184 << RHS.get()->getSourceRange(); 8185 return QualType(); 8186 } 8187 8188 /// FindCompositeObjCPointerType - Helper method to find composite type of 8189 /// two objective-c pointer types of the two input expressions. 8190 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8191 SourceLocation QuestionLoc) { 8192 QualType LHSTy = LHS.get()->getType(); 8193 QualType RHSTy = RHS.get()->getType(); 8194 8195 // Handle things like Class and struct objc_class*. Here we case the result 8196 // to the pseudo-builtin, because that will be implicitly cast back to the 8197 // redefinition type if an attempt is made to access its fields. 8198 if (LHSTy->isObjCClassType() && 8199 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8200 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8201 return LHSTy; 8202 } 8203 if (RHSTy->isObjCClassType() && 8204 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8205 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8206 return RHSTy; 8207 } 8208 // And the same for struct objc_object* / id 8209 if (LHSTy->isObjCIdType() && 8210 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8211 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8212 return LHSTy; 8213 } 8214 if (RHSTy->isObjCIdType() && 8215 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8216 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8217 return RHSTy; 8218 } 8219 // And the same for struct objc_selector* / SEL 8220 if (Context.isObjCSelType(LHSTy) && 8221 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8222 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8223 return LHSTy; 8224 } 8225 if (Context.isObjCSelType(RHSTy) && 8226 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8227 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8228 return RHSTy; 8229 } 8230 // Check constraints for Objective-C object pointers types. 8231 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8232 8233 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8234 // Two identical object pointer types are always compatible. 8235 return LHSTy; 8236 } 8237 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8238 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8239 QualType compositeType = LHSTy; 8240 8241 // If both operands are interfaces and either operand can be 8242 // assigned to the other, use that type as the composite 8243 // type. This allows 8244 // xxx ? (A*) a : (B*) b 8245 // where B is a subclass of A. 8246 // 8247 // Additionally, as for assignment, if either type is 'id' 8248 // allow silent coercion. Finally, if the types are 8249 // incompatible then make sure to use 'id' as the composite 8250 // type so the result is acceptable for sending messages to. 8251 8252 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8253 // It could return the composite type. 8254 if (!(compositeType = 8255 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8256 // Nothing more to do. 8257 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8258 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8259 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8260 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8261 } else if ((LHSOPT->isObjCQualifiedIdType() || 8262 RHSOPT->isObjCQualifiedIdType()) && 8263 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8264 true)) { 8265 // Need to handle "id<xx>" explicitly. 8266 // GCC allows qualified id and any Objective-C type to devolve to 8267 // id. Currently localizing to here until clear this should be 8268 // part of ObjCQualifiedIdTypesAreCompatible. 8269 compositeType = Context.getObjCIdType(); 8270 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8271 compositeType = Context.getObjCIdType(); 8272 } else { 8273 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8274 << LHSTy << RHSTy 8275 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8276 QualType incompatTy = Context.getObjCIdType(); 8277 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8278 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8279 return incompatTy; 8280 } 8281 // The object pointer types are compatible. 8282 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8283 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8284 return compositeType; 8285 } 8286 // Check Objective-C object pointer types and 'void *' 8287 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8288 if (getLangOpts().ObjCAutoRefCount) { 8289 // ARC forbids the implicit conversion of object pointers to 'void *', 8290 // so these types are not compatible. 8291 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8292 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8293 LHS = RHS = true; 8294 return QualType(); 8295 } 8296 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8297 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8298 QualType destPointee 8299 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8300 QualType destType = Context.getPointerType(destPointee); 8301 // Add qualifiers if necessary. 8302 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8303 // Promote to void*. 8304 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8305 return destType; 8306 } 8307 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8308 if (getLangOpts().ObjCAutoRefCount) { 8309 // ARC forbids the implicit conversion of object pointers to 'void *', 8310 // so these types are not compatible. 8311 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8312 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8313 LHS = RHS = true; 8314 return QualType(); 8315 } 8316 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8317 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8318 QualType destPointee 8319 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8320 QualType destType = Context.getPointerType(destPointee); 8321 // Add qualifiers if necessary. 8322 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8323 // Promote to void*. 8324 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8325 return destType; 8326 } 8327 return QualType(); 8328 } 8329 8330 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8331 /// ParenRange in parentheses. 8332 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8333 const PartialDiagnostic &Note, 8334 SourceRange ParenRange) { 8335 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8336 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8337 EndLoc.isValid()) { 8338 Self.Diag(Loc, Note) 8339 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8340 << FixItHint::CreateInsertion(EndLoc, ")"); 8341 } else { 8342 // We can't display the parentheses, so just show the bare note. 8343 Self.Diag(Loc, Note) << ParenRange; 8344 } 8345 } 8346 8347 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8348 return BinaryOperator::isAdditiveOp(Opc) || 8349 BinaryOperator::isMultiplicativeOp(Opc) || 8350 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8351 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8352 // not any of the logical operators. Bitwise-xor is commonly used as a 8353 // logical-xor because there is no logical-xor operator. The logical 8354 // operators, including uses of xor, have a high false positive rate for 8355 // precedence warnings. 8356 } 8357 8358 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8359 /// expression, either using a built-in or overloaded operator, 8360 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8361 /// expression. 8362 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8363 Expr **RHSExprs) { 8364 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8365 E = E->IgnoreImpCasts(); 8366 E = E->IgnoreConversionOperator(); 8367 E = E->IgnoreImpCasts(); 8368 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8369 E = MTE->getSubExpr(); 8370 E = E->IgnoreImpCasts(); 8371 } 8372 8373 // Built-in binary operator. 8374 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8375 if (IsArithmeticOp(OP->getOpcode())) { 8376 *Opcode = OP->getOpcode(); 8377 *RHSExprs = OP->getRHS(); 8378 return true; 8379 } 8380 } 8381 8382 // Overloaded operator. 8383 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8384 if (Call->getNumArgs() != 2) 8385 return false; 8386 8387 // Make sure this is really a binary operator that is safe to pass into 8388 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8389 OverloadedOperatorKind OO = Call->getOperator(); 8390 if (OO < OO_Plus || OO > OO_Arrow || 8391 OO == OO_PlusPlus || OO == OO_MinusMinus) 8392 return false; 8393 8394 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8395 if (IsArithmeticOp(OpKind)) { 8396 *Opcode = OpKind; 8397 *RHSExprs = Call->getArg(1); 8398 return true; 8399 } 8400 } 8401 8402 return false; 8403 } 8404 8405 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8406 /// or is a logical expression such as (x==y) which has int type, but is 8407 /// commonly interpreted as boolean. 8408 static bool ExprLooksBoolean(Expr *E) { 8409 E = E->IgnoreParenImpCasts(); 8410 8411 if (E->getType()->isBooleanType()) 8412 return true; 8413 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8414 return OP->isComparisonOp() || OP->isLogicalOp(); 8415 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8416 return OP->getOpcode() == UO_LNot; 8417 if (E->getType()->isPointerType()) 8418 return true; 8419 // FIXME: What about overloaded operator calls returning "unspecified boolean 8420 // type"s (commonly pointer-to-members)? 8421 8422 return false; 8423 } 8424 8425 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8426 /// and binary operator are mixed in a way that suggests the programmer assumed 8427 /// the conditional operator has higher precedence, for example: 8428 /// "int x = a + someBinaryCondition ? 1 : 2". 8429 static void DiagnoseConditionalPrecedence(Sema &Self, 8430 SourceLocation OpLoc, 8431 Expr *Condition, 8432 Expr *LHSExpr, 8433 Expr *RHSExpr) { 8434 BinaryOperatorKind CondOpcode; 8435 Expr *CondRHS; 8436 8437 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8438 return; 8439 if (!ExprLooksBoolean(CondRHS)) 8440 return; 8441 8442 // The condition is an arithmetic binary expression, with a right- 8443 // hand side that looks boolean, so warn. 8444 8445 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8446 ? diag::warn_precedence_bitwise_conditional 8447 : diag::warn_precedence_conditional; 8448 8449 Self.Diag(OpLoc, DiagID) 8450 << Condition->getSourceRange() 8451 << BinaryOperator::getOpcodeStr(CondOpcode); 8452 8453 SuggestParentheses( 8454 Self, OpLoc, 8455 Self.PDiag(diag::note_precedence_silence) 8456 << BinaryOperator::getOpcodeStr(CondOpcode), 8457 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8458 8459 SuggestParentheses(Self, OpLoc, 8460 Self.PDiag(diag::note_precedence_conditional_first), 8461 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8462 } 8463 8464 /// Compute the nullability of a conditional expression. 8465 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8466 QualType LHSTy, QualType RHSTy, 8467 ASTContext &Ctx) { 8468 if (!ResTy->isAnyPointerType()) 8469 return ResTy; 8470 8471 auto GetNullability = [&Ctx](QualType Ty) { 8472 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8473 if (Kind) 8474 return *Kind; 8475 return NullabilityKind::Unspecified; 8476 }; 8477 8478 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8479 NullabilityKind MergedKind; 8480 8481 // Compute nullability of a binary conditional expression. 8482 if (IsBin) { 8483 if (LHSKind == NullabilityKind::NonNull) 8484 MergedKind = NullabilityKind::NonNull; 8485 else 8486 MergedKind = RHSKind; 8487 // Compute nullability of a normal conditional expression. 8488 } else { 8489 if (LHSKind == NullabilityKind::Nullable || 8490 RHSKind == NullabilityKind::Nullable) 8491 MergedKind = NullabilityKind::Nullable; 8492 else if (LHSKind == NullabilityKind::NonNull) 8493 MergedKind = RHSKind; 8494 else if (RHSKind == NullabilityKind::NonNull) 8495 MergedKind = LHSKind; 8496 else 8497 MergedKind = NullabilityKind::Unspecified; 8498 } 8499 8500 // Return if ResTy already has the correct nullability. 8501 if (GetNullability(ResTy) == MergedKind) 8502 return ResTy; 8503 8504 // Strip all nullability from ResTy. 8505 while (ResTy->getNullability(Ctx)) 8506 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8507 8508 // Create a new AttributedType with the new nullability kind. 8509 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8510 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8511 } 8512 8513 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8514 /// in the case of a the GNU conditional expr extension. 8515 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8516 SourceLocation ColonLoc, 8517 Expr *CondExpr, Expr *LHSExpr, 8518 Expr *RHSExpr) { 8519 if (!getLangOpts().CPlusPlus) { 8520 // C cannot handle TypoExpr nodes in the condition because it 8521 // doesn't handle dependent types properly, so make sure any TypoExprs have 8522 // been dealt with before checking the operands. 8523 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8524 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8525 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8526 8527 if (!CondResult.isUsable()) 8528 return ExprError(); 8529 8530 if (LHSExpr) { 8531 if (!LHSResult.isUsable()) 8532 return ExprError(); 8533 } 8534 8535 if (!RHSResult.isUsable()) 8536 return ExprError(); 8537 8538 CondExpr = CondResult.get(); 8539 LHSExpr = LHSResult.get(); 8540 RHSExpr = RHSResult.get(); 8541 } 8542 8543 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8544 // was the condition. 8545 OpaqueValueExpr *opaqueValue = nullptr; 8546 Expr *commonExpr = nullptr; 8547 if (!LHSExpr) { 8548 commonExpr = CondExpr; 8549 // Lower out placeholder types first. This is important so that we don't 8550 // try to capture a placeholder. This happens in few cases in C++; such 8551 // as Objective-C++'s dictionary subscripting syntax. 8552 if (commonExpr->hasPlaceholderType()) { 8553 ExprResult result = CheckPlaceholderExpr(commonExpr); 8554 if (!result.isUsable()) return ExprError(); 8555 commonExpr = result.get(); 8556 } 8557 // We usually want to apply unary conversions *before* saving, except 8558 // in the special case of a C++ l-value conditional. 8559 if (!(getLangOpts().CPlusPlus 8560 && !commonExpr->isTypeDependent() 8561 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8562 && commonExpr->isGLValue() 8563 && commonExpr->isOrdinaryOrBitFieldObject() 8564 && RHSExpr->isOrdinaryOrBitFieldObject() 8565 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8566 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8567 if (commonRes.isInvalid()) 8568 return ExprError(); 8569 commonExpr = commonRes.get(); 8570 } 8571 8572 // If the common expression is a class or array prvalue, materialize it 8573 // so that we can safely refer to it multiple times. 8574 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8575 commonExpr->getType()->isArrayType())) { 8576 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8577 if (MatExpr.isInvalid()) 8578 return ExprError(); 8579 commonExpr = MatExpr.get(); 8580 } 8581 8582 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8583 commonExpr->getType(), 8584 commonExpr->getValueKind(), 8585 commonExpr->getObjectKind(), 8586 commonExpr); 8587 LHSExpr = CondExpr = opaqueValue; 8588 } 8589 8590 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8591 ExprValueKind VK = VK_RValue; 8592 ExprObjectKind OK = OK_Ordinary; 8593 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8594 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8595 VK, OK, QuestionLoc); 8596 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8597 RHS.isInvalid()) 8598 return ExprError(); 8599 8600 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8601 RHS.get()); 8602 8603 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8604 8605 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8606 Context); 8607 8608 if (!commonExpr) 8609 return new (Context) 8610 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8611 RHS.get(), result, VK, OK); 8612 8613 return new (Context) BinaryConditionalOperator( 8614 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8615 ColonLoc, result, VK, OK); 8616 } 8617 8618 // Check if we have a conversion between incompatible cmse function pointer 8619 // types, that is, a conversion between a function pointer with the 8620 // cmse_nonsecure_call attribute and one without. 8621 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8622 QualType ToType) { 8623 if (const auto *ToFn = 8624 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8625 if (const auto *FromFn = 8626 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8627 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8628 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8629 8630 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8631 } 8632 } 8633 return false; 8634 } 8635 8636 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8637 // being closely modeled after the C99 spec:-). The odd characteristic of this 8638 // routine is it effectively iqnores the qualifiers on the top level pointee. 8639 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8640 // FIXME: add a couple examples in this comment. 8641 static Sema::AssignConvertType 8642 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8643 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8644 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8645 8646 // get the "pointed to" type (ignoring qualifiers at the top level) 8647 const Type *lhptee, *rhptee; 8648 Qualifiers lhq, rhq; 8649 std::tie(lhptee, lhq) = 8650 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8651 std::tie(rhptee, rhq) = 8652 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8653 8654 Sema::AssignConvertType ConvTy = Sema::Compatible; 8655 8656 // C99 6.5.16.1p1: This following citation is common to constraints 8657 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8658 // qualifiers of the type *pointed to* by the right; 8659 8660 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8661 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8662 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8663 // Ignore lifetime for further calculation. 8664 lhq.removeObjCLifetime(); 8665 rhq.removeObjCLifetime(); 8666 } 8667 8668 if (!lhq.compatiblyIncludes(rhq)) { 8669 // Treat address-space mismatches as fatal. 8670 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8671 return Sema::IncompatiblePointerDiscardsQualifiers; 8672 8673 // It's okay to add or remove GC or lifetime qualifiers when converting to 8674 // and from void*. 8675 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8676 .compatiblyIncludes( 8677 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8678 && (lhptee->isVoidType() || rhptee->isVoidType())) 8679 ; // keep old 8680 8681 // Treat lifetime mismatches as fatal. 8682 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8683 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8684 8685 // For GCC/MS compatibility, other qualifier mismatches are treated 8686 // as still compatible in C. 8687 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8688 } 8689 8690 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8691 // incomplete type and the other is a pointer to a qualified or unqualified 8692 // version of void... 8693 if (lhptee->isVoidType()) { 8694 if (rhptee->isIncompleteOrObjectType()) 8695 return ConvTy; 8696 8697 // As an extension, we allow cast to/from void* to function pointer. 8698 assert(rhptee->isFunctionType()); 8699 return Sema::FunctionVoidPointer; 8700 } 8701 8702 if (rhptee->isVoidType()) { 8703 if (lhptee->isIncompleteOrObjectType()) 8704 return ConvTy; 8705 8706 // As an extension, we allow cast to/from void* to function pointer. 8707 assert(lhptee->isFunctionType()); 8708 return Sema::FunctionVoidPointer; 8709 } 8710 8711 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8712 // unqualified versions of compatible types, ... 8713 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8714 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8715 // Check if the pointee types are compatible ignoring the sign. 8716 // We explicitly check for char so that we catch "char" vs 8717 // "unsigned char" on systems where "char" is unsigned. 8718 if (lhptee->isCharType()) 8719 ltrans = S.Context.UnsignedCharTy; 8720 else if (lhptee->hasSignedIntegerRepresentation()) 8721 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8722 8723 if (rhptee->isCharType()) 8724 rtrans = S.Context.UnsignedCharTy; 8725 else if (rhptee->hasSignedIntegerRepresentation()) 8726 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8727 8728 if (ltrans == rtrans) { 8729 // Types are compatible ignoring the sign. Qualifier incompatibility 8730 // takes priority over sign incompatibility because the sign 8731 // warning can be disabled. 8732 if (ConvTy != Sema::Compatible) 8733 return ConvTy; 8734 8735 return Sema::IncompatiblePointerSign; 8736 } 8737 8738 // If we are a multi-level pointer, it's possible that our issue is simply 8739 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8740 // the eventual target type is the same and the pointers have the same 8741 // level of indirection, this must be the issue. 8742 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8743 do { 8744 std::tie(lhptee, lhq) = 8745 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8746 std::tie(rhptee, rhq) = 8747 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8748 8749 // Inconsistent address spaces at this point is invalid, even if the 8750 // address spaces would be compatible. 8751 // FIXME: This doesn't catch address space mismatches for pointers of 8752 // different nesting levels, like: 8753 // __local int *** a; 8754 // int ** b = a; 8755 // It's not clear how to actually determine when such pointers are 8756 // invalidly incompatible. 8757 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8758 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8759 8760 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8761 8762 if (lhptee == rhptee) 8763 return Sema::IncompatibleNestedPointerQualifiers; 8764 } 8765 8766 // General pointer incompatibility takes priority over qualifiers. 8767 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8768 return Sema::IncompatibleFunctionPointer; 8769 return Sema::IncompatiblePointer; 8770 } 8771 if (!S.getLangOpts().CPlusPlus && 8772 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8773 return Sema::IncompatibleFunctionPointer; 8774 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8775 return Sema::IncompatibleFunctionPointer; 8776 return ConvTy; 8777 } 8778 8779 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8780 /// block pointer types are compatible or whether a block and normal pointer 8781 /// are compatible. It is more restrict than comparing two function pointer 8782 // types. 8783 static Sema::AssignConvertType 8784 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8785 QualType RHSType) { 8786 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8787 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8788 8789 QualType lhptee, rhptee; 8790 8791 // get the "pointed to" type (ignoring qualifiers at the top level) 8792 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8793 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8794 8795 // In C++, the types have to match exactly. 8796 if (S.getLangOpts().CPlusPlus) 8797 return Sema::IncompatibleBlockPointer; 8798 8799 Sema::AssignConvertType ConvTy = Sema::Compatible; 8800 8801 // For blocks we enforce that qualifiers are identical. 8802 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8803 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8804 if (S.getLangOpts().OpenCL) { 8805 LQuals.removeAddressSpace(); 8806 RQuals.removeAddressSpace(); 8807 } 8808 if (LQuals != RQuals) 8809 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8810 8811 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8812 // assignment. 8813 // The current behavior is similar to C++ lambdas. A block might be 8814 // assigned to a variable iff its return type and parameters are compatible 8815 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8816 // an assignment. Presumably it should behave in way that a function pointer 8817 // assignment does in C, so for each parameter and return type: 8818 // * CVR and address space of LHS should be a superset of CVR and address 8819 // space of RHS. 8820 // * unqualified types should be compatible. 8821 if (S.getLangOpts().OpenCL) { 8822 if (!S.Context.typesAreBlockPointerCompatible( 8823 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8824 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8825 return Sema::IncompatibleBlockPointer; 8826 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8827 return Sema::IncompatibleBlockPointer; 8828 8829 return ConvTy; 8830 } 8831 8832 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8833 /// for assignment compatibility. 8834 static Sema::AssignConvertType 8835 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8836 QualType RHSType) { 8837 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8838 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8839 8840 if (LHSType->isObjCBuiltinType()) { 8841 // Class is not compatible with ObjC object pointers. 8842 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8843 !RHSType->isObjCQualifiedClassType()) 8844 return Sema::IncompatiblePointer; 8845 return Sema::Compatible; 8846 } 8847 if (RHSType->isObjCBuiltinType()) { 8848 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8849 !LHSType->isObjCQualifiedClassType()) 8850 return Sema::IncompatiblePointer; 8851 return Sema::Compatible; 8852 } 8853 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8854 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8855 8856 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8857 // make an exception for id<P> 8858 !LHSType->isObjCQualifiedIdType()) 8859 return Sema::CompatiblePointerDiscardsQualifiers; 8860 8861 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8862 return Sema::Compatible; 8863 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8864 return Sema::IncompatibleObjCQualifiedId; 8865 return Sema::IncompatiblePointer; 8866 } 8867 8868 Sema::AssignConvertType 8869 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8870 QualType LHSType, QualType RHSType) { 8871 // Fake up an opaque expression. We don't actually care about what 8872 // cast operations are required, so if CheckAssignmentConstraints 8873 // adds casts to this they'll be wasted, but fortunately that doesn't 8874 // usually happen on valid code. 8875 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8876 ExprResult RHSPtr = &RHSExpr; 8877 CastKind K; 8878 8879 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8880 } 8881 8882 /// This helper function returns true if QT is a vector type that has element 8883 /// type ElementType. 8884 static bool isVector(QualType QT, QualType ElementType) { 8885 if (const VectorType *VT = QT->getAs<VectorType>()) 8886 return VT->getElementType().getCanonicalType() == ElementType; 8887 return false; 8888 } 8889 8890 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8891 /// has code to accommodate several GCC extensions when type checking 8892 /// pointers. Here are some objectionable examples that GCC considers warnings: 8893 /// 8894 /// int a, *pint; 8895 /// short *pshort; 8896 /// struct foo *pfoo; 8897 /// 8898 /// pint = pshort; // warning: assignment from incompatible pointer type 8899 /// a = pint; // warning: assignment makes integer from pointer without a cast 8900 /// pint = a; // warning: assignment makes pointer from integer without a cast 8901 /// pint = pfoo; // warning: assignment from incompatible pointer type 8902 /// 8903 /// As a result, the code for dealing with pointers is more complex than the 8904 /// C99 spec dictates. 8905 /// 8906 /// Sets 'Kind' for any result kind except Incompatible. 8907 Sema::AssignConvertType 8908 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8909 CastKind &Kind, bool ConvertRHS) { 8910 QualType RHSType = RHS.get()->getType(); 8911 QualType OrigLHSType = LHSType; 8912 8913 // Get canonical types. We're not formatting these types, just comparing 8914 // them. 8915 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8916 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8917 8918 // Common case: no conversion required. 8919 if (LHSType == RHSType) { 8920 Kind = CK_NoOp; 8921 return Compatible; 8922 } 8923 8924 // If we have an atomic type, try a non-atomic assignment, then just add an 8925 // atomic qualification step. 8926 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8927 Sema::AssignConvertType result = 8928 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8929 if (result != Compatible) 8930 return result; 8931 if (Kind != CK_NoOp && ConvertRHS) 8932 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8933 Kind = CK_NonAtomicToAtomic; 8934 return Compatible; 8935 } 8936 8937 // If the left-hand side is a reference type, then we are in a 8938 // (rare!) case where we've allowed the use of references in C, 8939 // e.g., as a parameter type in a built-in function. In this case, 8940 // just make sure that the type referenced is compatible with the 8941 // right-hand side type. The caller is responsible for adjusting 8942 // LHSType so that the resulting expression does not have reference 8943 // type. 8944 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8945 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8946 Kind = CK_LValueBitCast; 8947 return Compatible; 8948 } 8949 return Incompatible; 8950 } 8951 8952 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8953 // to the same ExtVector type. 8954 if (LHSType->isExtVectorType()) { 8955 if (RHSType->isExtVectorType()) 8956 return Incompatible; 8957 if (RHSType->isArithmeticType()) { 8958 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8959 if (ConvertRHS) 8960 RHS = prepareVectorSplat(LHSType, RHS.get()); 8961 Kind = CK_VectorSplat; 8962 return Compatible; 8963 } 8964 } 8965 8966 // Conversions to or from vector type. 8967 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8968 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8969 // Allow assignments of an AltiVec vector type to an equivalent GCC 8970 // vector type and vice versa 8971 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8972 Kind = CK_BitCast; 8973 return Compatible; 8974 } 8975 8976 // If we are allowing lax vector conversions, and LHS and RHS are both 8977 // vectors, the total size only needs to be the same. This is a bitcast; 8978 // no bits are changed but the result type is different. 8979 if (isLaxVectorConversion(RHSType, LHSType)) { 8980 Kind = CK_BitCast; 8981 return IncompatibleVectors; 8982 } 8983 } 8984 8985 // When the RHS comes from another lax conversion (e.g. binops between 8986 // scalars and vectors) the result is canonicalized as a vector. When the 8987 // LHS is also a vector, the lax is allowed by the condition above. Handle 8988 // the case where LHS is a scalar. 8989 if (LHSType->isScalarType()) { 8990 const VectorType *VecType = RHSType->getAs<VectorType>(); 8991 if (VecType && VecType->getNumElements() == 1 && 8992 isLaxVectorConversion(RHSType, LHSType)) { 8993 ExprResult *VecExpr = &RHS; 8994 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8995 Kind = CK_BitCast; 8996 return Compatible; 8997 } 8998 } 8999 9000 return Incompatible; 9001 } 9002 9003 // Diagnose attempts to convert between __float128 and long double where 9004 // such conversions currently can't be handled. 9005 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9006 return Incompatible; 9007 9008 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9009 // discards the imaginary part. 9010 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9011 !LHSType->getAs<ComplexType>()) 9012 return Incompatible; 9013 9014 // Arithmetic conversions. 9015 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9016 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9017 if (ConvertRHS) 9018 Kind = PrepareScalarCast(RHS, LHSType); 9019 return Compatible; 9020 } 9021 9022 // Conversions to normal pointers. 9023 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9024 // U* -> T* 9025 if (isa<PointerType>(RHSType)) { 9026 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9027 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9028 if (AddrSpaceL != AddrSpaceR) 9029 Kind = CK_AddressSpaceConversion; 9030 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9031 Kind = CK_NoOp; 9032 else 9033 Kind = CK_BitCast; 9034 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9035 } 9036 9037 // int -> T* 9038 if (RHSType->isIntegerType()) { 9039 Kind = CK_IntegralToPointer; // FIXME: null? 9040 return IntToPointer; 9041 } 9042 9043 // C pointers are not compatible with ObjC object pointers, 9044 // with two exceptions: 9045 if (isa<ObjCObjectPointerType>(RHSType)) { 9046 // - conversions to void* 9047 if (LHSPointer->getPointeeType()->isVoidType()) { 9048 Kind = CK_BitCast; 9049 return Compatible; 9050 } 9051 9052 // - conversions from 'Class' to the redefinition type 9053 if (RHSType->isObjCClassType() && 9054 Context.hasSameType(LHSType, 9055 Context.getObjCClassRedefinitionType())) { 9056 Kind = CK_BitCast; 9057 return Compatible; 9058 } 9059 9060 Kind = CK_BitCast; 9061 return IncompatiblePointer; 9062 } 9063 9064 // U^ -> void* 9065 if (RHSType->getAs<BlockPointerType>()) { 9066 if (LHSPointer->getPointeeType()->isVoidType()) { 9067 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9068 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9069 ->getPointeeType() 9070 .getAddressSpace(); 9071 Kind = 9072 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9073 return Compatible; 9074 } 9075 } 9076 9077 return Incompatible; 9078 } 9079 9080 // Conversions to block pointers. 9081 if (isa<BlockPointerType>(LHSType)) { 9082 // U^ -> T^ 9083 if (RHSType->isBlockPointerType()) { 9084 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9085 ->getPointeeType() 9086 .getAddressSpace(); 9087 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9088 ->getPointeeType() 9089 .getAddressSpace(); 9090 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9091 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9092 } 9093 9094 // int or null -> T^ 9095 if (RHSType->isIntegerType()) { 9096 Kind = CK_IntegralToPointer; // FIXME: null 9097 return IntToBlockPointer; 9098 } 9099 9100 // id -> T^ 9101 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9102 Kind = CK_AnyPointerToBlockPointerCast; 9103 return Compatible; 9104 } 9105 9106 // void* -> T^ 9107 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9108 if (RHSPT->getPointeeType()->isVoidType()) { 9109 Kind = CK_AnyPointerToBlockPointerCast; 9110 return Compatible; 9111 } 9112 9113 return Incompatible; 9114 } 9115 9116 // Conversions to Objective-C pointers. 9117 if (isa<ObjCObjectPointerType>(LHSType)) { 9118 // A* -> B* 9119 if (RHSType->isObjCObjectPointerType()) { 9120 Kind = CK_BitCast; 9121 Sema::AssignConvertType result = 9122 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9123 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9124 result == Compatible && 9125 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9126 result = IncompatibleObjCWeakRef; 9127 return result; 9128 } 9129 9130 // int or null -> A* 9131 if (RHSType->isIntegerType()) { 9132 Kind = CK_IntegralToPointer; // FIXME: null 9133 return IntToPointer; 9134 } 9135 9136 // In general, C pointers are not compatible with ObjC object pointers, 9137 // with two exceptions: 9138 if (isa<PointerType>(RHSType)) { 9139 Kind = CK_CPointerToObjCPointerCast; 9140 9141 // - conversions from 'void*' 9142 if (RHSType->isVoidPointerType()) { 9143 return Compatible; 9144 } 9145 9146 // - conversions to 'Class' from its redefinition type 9147 if (LHSType->isObjCClassType() && 9148 Context.hasSameType(RHSType, 9149 Context.getObjCClassRedefinitionType())) { 9150 return Compatible; 9151 } 9152 9153 return IncompatiblePointer; 9154 } 9155 9156 // Only under strict condition T^ is compatible with an Objective-C pointer. 9157 if (RHSType->isBlockPointerType() && 9158 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9159 if (ConvertRHS) 9160 maybeExtendBlockObject(RHS); 9161 Kind = CK_BlockPointerToObjCPointerCast; 9162 return Compatible; 9163 } 9164 9165 return Incompatible; 9166 } 9167 9168 // Conversions from pointers that are not covered by the above. 9169 if (isa<PointerType>(RHSType)) { 9170 // T* -> _Bool 9171 if (LHSType == Context.BoolTy) { 9172 Kind = CK_PointerToBoolean; 9173 return Compatible; 9174 } 9175 9176 // T* -> int 9177 if (LHSType->isIntegerType()) { 9178 Kind = CK_PointerToIntegral; 9179 return PointerToInt; 9180 } 9181 9182 return Incompatible; 9183 } 9184 9185 // Conversions from Objective-C pointers that are not covered by the above. 9186 if (isa<ObjCObjectPointerType>(RHSType)) { 9187 // T* -> _Bool 9188 if (LHSType == Context.BoolTy) { 9189 Kind = CK_PointerToBoolean; 9190 return Compatible; 9191 } 9192 9193 // T* -> int 9194 if (LHSType->isIntegerType()) { 9195 Kind = CK_PointerToIntegral; 9196 return PointerToInt; 9197 } 9198 9199 return Incompatible; 9200 } 9201 9202 // struct A -> struct B 9203 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9204 if (Context.typesAreCompatible(LHSType, RHSType)) { 9205 Kind = CK_NoOp; 9206 return Compatible; 9207 } 9208 } 9209 9210 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9211 Kind = CK_IntToOCLSampler; 9212 return Compatible; 9213 } 9214 9215 return Incompatible; 9216 } 9217 9218 /// Constructs a transparent union from an expression that is 9219 /// used to initialize the transparent union. 9220 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9221 ExprResult &EResult, QualType UnionType, 9222 FieldDecl *Field) { 9223 // Build an initializer list that designates the appropriate member 9224 // of the transparent union. 9225 Expr *E = EResult.get(); 9226 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9227 E, SourceLocation()); 9228 Initializer->setType(UnionType); 9229 Initializer->setInitializedFieldInUnion(Field); 9230 9231 // Build a compound literal constructing a value of the transparent 9232 // union type from this initializer list. 9233 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9234 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9235 VK_RValue, Initializer, false); 9236 } 9237 9238 Sema::AssignConvertType 9239 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9240 ExprResult &RHS) { 9241 QualType RHSType = RHS.get()->getType(); 9242 9243 // If the ArgType is a Union type, we want to handle a potential 9244 // transparent_union GCC extension. 9245 const RecordType *UT = ArgType->getAsUnionType(); 9246 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9247 return Incompatible; 9248 9249 // The field to initialize within the transparent union. 9250 RecordDecl *UD = UT->getDecl(); 9251 FieldDecl *InitField = nullptr; 9252 // It's compatible if the expression matches any of the fields. 9253 for (auto *it : UD->fields()) { 9254 if (it->getType()->isPointerType()) { 9255 // If the transparent union contains a pointer type, we allow: 9256 // 1) void pointer 9257 // 2) null pointer constant 9258 if (RHSType->isPointerType()) 9259 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9260 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9261 InitField = it; 9262 break; 9263 } 9264 9265 if (RHS.get()->isNullPointerConstant(Context, 9266 Expr::NPC_ValueDependentIsNull)) { 9267 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9268 CK_NullToPointer); 9269 InitField = it; 9270 break; 9271 } 9272 } 9273 9274 CastKind Kind; 9275 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9276 == Compatible) { 9277 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9278 InitField = it; 9279 break; 9280 } 9281 } 9282 9283 if (!InitField) 9284 return Incompatible; 9285 9286 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9287 return Compatible; 9288 } 9289 9290 Sema::AssignConvertType 9291 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9292 bool Diagnose, 9293 bool DiagnoseCFAudited, 9294 bool ConvertRHS) { 9295 // We need to be able to tell the caller whether we diagnosed a problem, if 9296 // they ask us to issue diagnostics. 9297 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9298 9299 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9300 // we can't avoid *all* modifications at the moment, so we need some somewhere 9301 // to put the updated value. 9302 ExprResult LocalRHS = CallerRHS; 9303 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9304 9305 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9306 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9307 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9308 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9309 Diag(RHS.get()->getExprLoc(), 9310 diag::warn_noderef_to_dereferenceable_pointer) 9311 << RHS.get()->getSourceRange(); 9312 } 9313 } 9314 } 9315 9316 if (getLangOpts().CPlusPlus) { 9317 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9318 // C++ 5.17p3: If the left operand is not of class type, the 9319 // expression is implicitly converted (C++ 4) to the 9320 // cv-unqualified type of the left operand. 9321 QualType RHSType = RHS.get()->getType(); 9322 if (Diagnose) { 9323 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9324 AA_Assigning); 9325 } else { 9326 ImplicitConversionSequence ICS = 9327 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9328 /*SuppressUserConversions=*/false, 9329 AllowedExplicit::None, 9330 /*InOverloadResolution=*/false, 9331 /*CStyle=*/false, 9332 /*AllowObjCWritebackConversion=*/false); 9333 if (ICS.isFailure()) 9334 return Incompatible; 9335 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9336 ICS, AA_Assigning); 9337 } 9338 if (RHS.isInvalid()) 9339 return Incompatible; 9340 Sema::AssignConvertType result = Compatible; 9341 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9342 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9343 result = IncompatibleObjCWeakRef; 9344 return result; 9345 } 9346 9347 // FIXME: Currently, we fall through and treat C++ classes like C 9348 // structures. 9349 // FIXME: We also fall through for atomics; not sure what should 9350 // happen there, though. 9351 } else if (RHS.get()->getType() == Context.OverloadTy) { 9352 // As a set of extensions to C, we support overloading on functions. These 9353 // functions need to be resolved here. 9354 DeclAccessPair DAP; 9355 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9356 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9357 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9358 else 9359 return Incompatible; 9360 } 9361 9362 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9363 // a null pointer constant. 9364 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9365 LHSType->isBlockPointerType()) && 9366 RHS.get()->isNullPointerConstant(Context, 9367 Expr::NPC_ValueDependentIsNull)) { 9368 if (Diagnose || ConvertRHS) { 9369 CastKind Kind; 9370 CXXCastPath Path; 9371 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9372 /*IgnoreBaseAccess=*/false, Diagnose); 9373 if (ConvertRHS) 9374 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9375 } 9376 return Compatible; 9377 } 9378 9379 // OpenCL queue_t type assignment. 9380 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9381 Context, Expr::NPC_ValueDependentIsNull)) { 9382 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9383 return Compatible; 9384 } 9385 9386 // This check seems unnatural, however it is necessary to ensure the proper 9387 // conversion of functions/arrays. If the conversion were done for all 9388 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9389 // expressions that suppress this implicit conversion (&, sizeof). 9390 // 9391 // Suppress this for references: C++ 8.5.3p5. 9392 if (!LHSType->isReferenceType()) { 9393 // FIXME: We potentially allocate here even if ConvertRHS is false. 9394 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9395 if (RHS.isInvalid()) 9396 return Incompatible; 9397 } 9398 CastKind Kind; 9399 Sema::AssignConvertType result = 9400 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9401 9402 // C99 6.5.16.1p2: The value of the right operand is converted to the 9403 // type of the assignment expression. 9404 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9405 // so that we can use references in built-in functions even in C. 9406 // The getNonReferenceType() call makes sure that the resulting expression 9407 // does not have reference type. 9408 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9409 QualType Ty = LHSType.getNonLValueExprType(Context); 9410 Expr *E = RHS.get(); 9411 9412 // Check for various Objective-C errors. If we are not reporting 9413 // diagnostics and just checking for errors, e.g., during overload 9414 // resolution, return Incompatible to indicate the failure. 9415 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9416 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9417 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9418 if (!Diagnose) 9419 return Incompatible; 9420 } 9421 if (getLangOpts().ObjC && 9422 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9423 E->getType(), E, Diagnose) || 9424 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9425 if (!Diagnose) 9426 return Incompatible; 9427 // Replace the expression with a corrected version and continue so we 9428 // can find further errors. 9429 RHS = E; 9430 return Compatible; 9431 } 9432 9433 if (ConvertRHS) 9434 RHS = ImpCastExprToType(E, Ty, Kind); 9435 } 9436 9437 return result; 9438 } 9439 9440 namespace { 9441 /// The original operand to an operator, prior to the application of the usual 9442 /// arithmetic conversions and converting the arguments of a builtin operator 9443 /// candidate. 9444 struct OriginalOperand { 9445 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9446 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9447 Op = MTE->getSubExpr(); 9448 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9449 Op = BTE->getSubExpr(); 9450 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9451 Orig = ICE->getSubExprAsWritten(); 9452 Conversion = ICE->getConversionFunction(); 9453 } 9454 } 9455 9456 QualType getType() const { return Orig->getType(); } 9457 9458 Expr *Orig; 9459 NamedDecl *Conversion; 9460 }; 9461 } 9462 9463 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9464 ExprResult &RHS) { 9465 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9466 9467 Diag(Loc, diag::err_typecheck_invalid_operands) 9468 << OrigLHS.getType() << OrigRHS.getType() 9469 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9470 9471 // If a user-defined conversion was applied to either of the operands prior 9472 // to applying the built-in operator rules, tell the user about it. 9473 if (OrigLHS.Conversion) { 9474 Diag(OrigLHS.Conversion->getLocation(), 9475 diag::note_typecheck_invalid_operands_converted) 9476 << 0 << LHS.get()->getType(); 9477 } 9478 if (OrigRHS.Conversion) { 9479 Diag(OrigRHS.Conversion->getLocation(), 9480 diag::note_typecheck_invalid_operands_converted) 9481 << 1 << RHS.get()->getType(); 9482 } 9483 9484 return QualType(); 9485 } 9486 9487 // Diagnose cases where a scalar was implicitly converted to a vector and 9488 // diagnose the underlying types. Otherwise, diagnose the error 9489 // as invalid vector logical operands for non-C++ cases. 9490 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9491 ExprResult &RHS) { 9492 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9493 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9494 9495 bool LHSNatVec = LHSType->isVectorType(); 9496 bool RHSNatVec = RHSType->isVectorType(); 9497 9498 if (!(LHSNatVec && RHSNatVec)) { 9499 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9500 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9501 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9502 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9503 << Vector->getSourceRange(); 9504 return QualType(); 9505 } 9506 9507 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9508 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9509 << RHS.get()->getSourceRange(); 9510 9511 return QualType(); 9512 } 9513 9514 /// Try to convert a value of non-vector type to a vector type by converting 9515 /// the type to the element type of the vector and then performing a splat. 9516 /// If the language is OpenCL, we only use conversions that promote scalar 9517 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9518 /// for float->int. 9519 /// 9520 /// OpenCL V2.0 6.2.6.p2: 9521 /// An error shall occur if any scalar operand type has greater rank 9522 /// than the type of the vector element. 9523 /// 9524 /// \param scalar - if non-null, actually perform the conversions 9525 /// \return true if the operation fails (but without diagnosing the failure) 9526 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9527 QualType scalarTy, 9528 QualType vectorEltTy, 9529 QualType vectorTy, 9530 unsigned &DiagID) { 9531 // The conversion to apply to the scalar before splatting it, 9532 // if necessary. 9533 CastKind scalarCast = CK_NoOp; 9534 9535 if (vectorEltTy->isIntegralType(S.Context)) { 9536 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9537 (scalarTy->isIntegerType() && 9538 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9539 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9540 return true; 9541 } 9542 if (!scalarTy->isIntegralType(S.Context)) 9543 return true; 9544 scalarCast = CK_IntegralCast; 9545 } else if (vectorEltTy->isRealFloatingType()) { 9546 if (scalarTy->isRealFloatingType()) { 9547 if (S.getLangOpts().OpenCL && 9548 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9549 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9550 return true; 9551 } 9552 scalarCast = CK_FloatingCast; 9553 } 9554 else if (scalarTy->isIntegralType(S.Context)) 9555 scalarCast = CK_IntegralToFloating; 9556 else 9557 return true; 9558 } else { 9559 return true; 9560 } 9561 9562 // Adjust scalar if desired. 9563 if (scalar) { 9564 if (scalarCast != CK_NoOp) 9565 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9566 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9567 } 9568 return false; 9569 } 9570 9571 /// Convert vector E to a vector with the same number of elements but different 9572 /// element type. 9573 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9574 const auto *VecTy = E->getType()->getAs<VectorType>(); 9575 assert(VecTy && "Expression E must be a vector"); 9576 QualType NewVecTy = S.Context.getVectorType(ElementType, 9577 VecTy->getNumElements(), 9578 VecTy->getVectorKind()); 9579 9580 // Look through the implicit cast. Return the subexpression if its type is 9581 // NewVecTy. 9582 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9583 if (ICE->getSubExpr()->getType() == NewVecTy) 9584 return ICE->getSubExpr(); 9585 9586 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9587 return S.ImpCastExprToType(E, NewVecTy, Cast); 9588 } 9589 9590 /// Test if a (constant) integer Int can be casted to another integer type 9591 /// IntTy without losing precision. 9592 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9593 QualType OtherIntTy) { 9594 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9595 9596 // Reject cases where the value of the Int is unknown as that would 9597 // possibly cause truncation, but accept cases where the scalar can be 9598 // demoted without loss of precision. 9599 Expr::EvalResult EVResult; 9600 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9601 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9602 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9603 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9604 9605 if (CstInt) { 9606 // If the scalar is constant and is of a higher order and has more active 9607 // bits that the vector element type, reject it. 9608 llvm::APSInt Result = EVResult.Val.getInt(); 9609 unsigned NumBits = IntSigned 9610 ? (Result.isNegative() ? Result.getMinSignedBits() 9611 : Result.getActiveBits()) 9612 : Result.getActiveBits(); 9613 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9614 return true; 9615 9616 // If the signedness of the scalar type and the vector element type 9617 // differs and the number of bits is greater than that of the vector 9618 // element reject it. 9619 return (IntSigned != OtherIntSigned && 9620 NumBits > S.Context.getIntWidth(OtherIntTy)); 9621 } 9622 9623 // Reject cases where the value of the scalar is not constant and it's 9624 // order is greater than that of the vector element type. 9625 return (Order < 0); 9626 } 9627 9628 /// Test if a (constant) integer Int can be casted to floating point type 9629 /// FloatTy without losing precision. 9630 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9631 QualType FloatTy) { 9632 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9633 9634 // Determine if the integer constant can be expressed as a floating point 9635 // number of the appropriate type. 9636 Expr::EvalResult EVResult; 9637 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9638 9639 uint64_t Bits = 0; 9640 if (CstInt) { 9641 // Reject constants that would be truncated if they were converted to 9642 // the floating point type. Test by simple to/from conversion. 9643 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9644 // could be avoided if there was a convertFromAPInt method 9645 // which could signal back if implicit truncation occurred. 9646 llvm::APSInt Result = EVResult.Val.getInt(); 9647 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9648 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9649 llvm::APFloat::rmTowardZero); 9650 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9651 !IntTy->hasSignedIntegerRepresentation()); 9652 bool Ignored = false; 9653 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9654 &Ignored); 9655 if (Result != ConvertBack) 9656 return true; 9657 } else { 9658 // Reject types that cannot be fully encoded into the mantissa of 9659 // the float. 9660 Bits = S.Context.getTypeSize(IntTy); 9661 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9662 S.Context.getFloatTypeSemantics(FloatTy)); 9663 if (Bits > FloatPrec) 9664 return true; 9665 } 9666 9667 return false; 9668 } 9669 9670 /// Attempt to convert and splat Scalar into a vector whose types matches 9671 /// Vector following GCC conversion rules. The rule is that implicit 9672 /// conversion can occur when Scalar can be casted to match Vector's element 9673 /// type without causing truncation of Scalar. 9674 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9675 ExprResult *Vector) { 9676 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9677 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9678 const VectorType *VT = VectorTy->getAs<VectorType>(); 9679 9680 assert(!isa<ExtVectorType>(VT) && 9681 "ExtVectorTypes should not be handled here!"); 9682 9683 QualType VectorEltTy = VT->getElementType(); 9684 9685 // Reject cases where the vector element type or the scalar element type are 9686 // not integral or floating point types. 9687 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9688 return true; 9689 9690 // The conversion to apply to the scalar before splatting it, 9691 // if necessary. 9692 CastKind ScalarCast = CK_NoOp; 9693 9694 // Accept cases where the vector elements are integers and the scalar is 9695 // an integer. 9696 // FIXME: Notionally if the scalar was a floating point value with a precise 9697 // integral representation, we could cast it to an appropriate integer 9698 // type and then perform the rest of the checks here. GCC will perform 9699 // this conversion in some cases as determined by the input language. 9700 // We should accept it on a language independent basis. 9701 if (VectorEltTy->isIntegralType(S.Context) && 9702 ScalarTy->isIntegralType(S.Context) && 9703 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9704 9705 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9706 return true; 9707 9708 ScalarCast = CK_IntegralCast; 9709 } else if (VectorEltTy->isIntegralType(S.Context) && 9710 ScalarTy->isRealFloatingType()) { 9711 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9712 ScalarCast = CK_FloatingToIntegral; 9713 else 9714 return true; 9715 } else if (VectorEltTy->isRealFloatingType()) { 9716 if (ScalarTy->isRealFloatingType()) { 9717 9718 // Reject cases where the scalar type is not a constant and has a higher 9719 // Order than the vector element type. 9720 llvm::APFloat Result(0.0); 9721 9722 // Determine whether this is a constant scalar. In the event that the 9723 // value is dependent (and thus cannot be evaluated by the constant 9724 // evaluator), skip the evaluation. This will then diagnose once the 9725 // expression is instantiated. 9726 bool CstScalar = Scalar->get()->isValueDependent() || 9727 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9728 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9729 if (!CstScalar && Order < 0) 9730 return true; 9731 9732 // If the scalar cannot be safely casted to the vector element type, 9733 // reject it. 9734 if (CstScalar) { 9735 bool Truncated = false; 9736 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9737 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9738 if (Truncated) 9739 return true; 9740 } 9741 9742 ScalarCast = CK_FloatingCast; 9743 } else if (ScalarTy->isIntegralType(S.Context)) { 9744 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9745 return true; 9746 9747 ScalarCast = CK_IntegralToFloating; 9748 } else 9749 return true; 9750 } else if (ScalarTy->isEnumeralType()) 9751 return true; 9752 9753 // Adjust scalar if desired. 9754 if (Scalar) { 9755 if (ScalarCast != CK_NoOp) 9756 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9757 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9758 } 9759 return false; 9760 } 9761 9762 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9763 SourceLocation Loc, bool IsCompAssign, 9764 bool AllowBothBool, 9765 bool AllowBoolConversions) { 9766 if (!IsCompAssign) { 9767 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9768 if (LHS.isInvalid()) 9769 return QualType(); 9770 } 9771 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9772 if (RHS.isInvalid()) 9773 return QualType(); 9774 9775 // For conversion purposes, we ignore any qualifiers. 9776 // For example, "const float" and "float" are equivalent. 9777 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9778 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9779 9780 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9781 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9782 assert(LHSVecType || RHSVecType); 9783 9784 // AltiVec-style "vector bool op vector bool" combinations are allowed 9785 // for some operators but not others. 9786 if (!AllowBothBool && 9787 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9788 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9789 return InvalidOperands(Loc, LHS, RHS); 9790 9791 // If the vector types are identical, return. 9792 if (Context.hasSameType(LHSType, RHSType)) 9793 return LHSType; 9794 9795 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9796 if (LHSVecType && RHSVecType && 9797 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9798 if (isa<ExtVectorType>(LHSVecType)) { 9799 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9800 return LHSType; 9801 } 9802 9803 if (!IsCompAssign) 9804 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9805 return RHSType; 9806 } 9807 9808 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9809 // can be mixed, with the result being the non-bool type. The non-bool 9810 // operand must have integer element type. 9811 if (AllowBoolConversions && LHSVecType && RHSVecType && 9812 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9813 (Context.getTypeSize(LHSVecType->getElementType()) == 9814 Context.getTypeSize(RHSVecType->getElementType()))) { 9815 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9816 LHSVecType->getElementType()->isIntegerType() && 9817 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9818 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9819 return LHSType; 9820 } 9821 if (!IsCompAssign && 9822 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9823 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9824 RHSVecType->getElementType()->isIntegerType()) { 9825 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9826 return RHSType; 9827 } 9828 } 9829 9830 // If there's a vector type and a scalar, try to convert the scalar to 9831 // the vector element type and splat. 9832 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9833 if (!RHSVecType) { 9834 if (isa<ExtVectorType>(LHSVecType)) { 9835 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9836 LHSVecType->getElementType(), LHSType, 9837 DiagID)) 9838 return LHSType; 9839 } else { 9840 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9841 return LHSType; 9842 } 9843 } 9844 if (!LHSVecType) { 9845 if (isa<ExtVectorType>(RHSVecType)) { 9846 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9847 LHSType, RHSVecType->getElementType(), 9848 RHSType, DiagID)) 9849 return RHSType; 9850 } else { 9851 if (LHS.get()->getValueKind() == VK_LValue || 9852 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9853 return RHSType; 9854 } 9855 } 9856 9857 // FIXME: The code below also handles conversion between vectors and 9858 // non-scalars, we should break this down into fine grained specific checks 9859 // and emit proper diagnostics. 9860 QualType VecType = LHSVecType ? LHSType : RHSType; 9861 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9862 QualType OtherType = LHSVecType ? RHSType : LHSType; 9863 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9864 if (isLaxVectorConversion(OtherType, VecType)) { 9865 // If we're allowing lax vector conversions, only the total (data) size 9866 // needs to be the same. For non compound assignment, if one of the types is 9867 // scalar, the result is always the vector type. 9868 if (!IsCompAssign) { 9869 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9870 return VecType; 9871 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9872 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9873 // type. Note that this is already done by non-compound assignments in 9874 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9875 // <1 x T> -> T. The result is also a vector type. 9876 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9877 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9878 ExprResult *RHSExpr = &RHS; 9879 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9880 return VecType; 9881 } 9882 } 9883 9884 // Okay, the expression is invalid. 9885 9886 // If there's a non-vector, non-real operand, diagnose that. 9887 if ((!RHSVecType && !RHSType->isRealType()) || 9888 (!LHSVecType && !LHSType->isRealType())) { 9889 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9890 << LHSType << RHSType 9891 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9892 return QualType(); 9893 } 9894 9895 // OpenCL V1.1 6.2.6.p1: 9896 // If the operands are of more than one vector type, then an error shall 9897 // occur. Implicit conversions between vector types are not permitted, per 9898 // section 6.2.1. 9899 if (getLangOpts().OpenCL && 9900 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9901 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9902 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9903 << RHSType; 9904 return QualType(); 9905 } 9906 9907 9908 // If there is a vector type that is not a ExtVector and a scalar, we reach 9909 // this point if scalar could not be converted to the vector's element type 9910 // without truncation. 9911 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9912 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9913 QualType Scalar = LHSVecType ? RHSType : LHSType; 9914 QualType Vector = LHSVecType ? LHSType : RHSType; 9915 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9916 Diag(Loc, 9917 diag::err_typecheck_vector_not_convertable_implict_truncation) 9918 << ScalarOrVector << Scalar << Vector; 9919 9920 return QualType(); 9921 } 9922 9923 // Otherwise, use the generic diagnostic. 9924 Diag(Loc, DiagID) 9925 << LHSType << RHSType 9926 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9927 return QualType(); 9928 } 9929 9930 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9931 // expression. These are mainly cases where the null pointer is used as an 9932 // integer instead of a pointer. 9933 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9934 SourceLocation Loc, bool IsCompare) { 9935 // The canonical way to check for a GNU null is with isNullPointerConstant, 9936 // but we use a bit of a hack here for speed; this is a relatively 9937 // hot path, and isNullPointerConstant is slow. 9938 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9939 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9940 9941 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9942 9943 // Avoid analyzing cases where the result will either be invalid (and 9944 // diagnosed as such) or entirely valid and not something to warn about. 9945 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9946 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9947 return; 9948 9949 // Comparison operations would not make sense with a null pointer no matter 9950 // what the other expression is. 9951 if (!IsCompare) { 9952 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9953 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9954 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9955 return; 9956 } 9957 9958 // The rest of the operations only make sense with a null pointer 9959 // if the other expression is a pointer. 9960 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9961 NonNullType->canDecayToPointerType()) 9962 return; 9963 9964 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9965 << LHSNull /* LHS is NULL */ << NonNullType 9966 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9967 } 9968 9969 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9970 SourceLocation Loc) { 9971 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9972 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9973 if (!LUE || !RUE) 9974 return; 9975 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9976 RUE->getKind() != UETT_SizeOf) 9977 return; 9978 9979 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9980 QualType LHSTy = LHSArg->getType(); 9981 QualType RHSTy; 9982 9983 if (RUE->isArgumentType()) 9984 RHSTy = RUE->getArgumentType(); 9985 else 9986 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9987 9988 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9989 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9990 return; 9991 9992 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9993 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9994 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9995 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9996 << LHSArgDecl; 9997 } 9998 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9999 QualType ArrayElemTy = ArrayTy->getElementType(); 10000 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10001 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10002 ArrayElemTy->isCharType() || 10003 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10004 return; 10005 S.Diag(Loc, diag::warn_division_sizeof_array) 10006 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10007 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10008 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10009 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10010 << LHSArgDecl; 10011 } 10012 10013 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10014 } 10015 } 10016 10017 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10018 ExprResult &RHS, 10019 SourceLocation Loc, bool IsDiv) { 10020 // Check for division/remainder by zero. 10021 Expr::EvalResult RHSValue; 10022 if (!RHS.get()->isValueDependent() && 10023 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10024 RHSValue.Val.getInt() == 0) 10025 S.DiagRuntimeBehavior(Loc, RHS.get(), 10026 S.PDiag(diag::warn_remainder_division_by_zero) 10027 << IsDiv << RHS.get()->getSourceRange()); 10028 } 10029 10030 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10031 SourceLocation Loc, 10032 bool IsCompAssign, bool IsDiv) { 10033 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10034 10035 if (LHS.get()->getType()->isVectorType() || 10036 RHS.get()->getType()->isVectorType()) 10037 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10038 /*AllowBothBool*/getLangOpts().AltiVec, 10039 /*AllowBoolConversions*/false); 10040 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10041 RHS.get()->getType()->isConstantMatrixType())) 10042 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10043 10044 QualType compType = UsualArithmeticConversions( 10045 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10046 if (LHS.isInvalid() || RHS.isInvalid()) 10047 return QualType(); 10048 10049 10050 if (compType.isNull() || !compType->isArithmeticType()) 10051 return InvalidOperands(Loc, LHS, RHS); 10052 if (IsDiv) { 10053 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10054 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10055 } 10056 return compType; 10057 } 10058 10059 QualType Sema::CheckRemainderOperands( 10060 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10061 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10062 10063 if (LHS.get()->getType()->isVectorType() || 10064 RHS.get()->getType()->isVectorType()) { 10065 if (LHS.get()->getType()->hasIntegerRepresentation() && 10066 RHS.get()->getType()->hasIntegerRepresentation()) 10067 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10068 /*AllowBothBool*/getLangOpts().AltiVec, 10069 /*AllowBoolConversions*/false); 10070 return InvalidOperands(Loc, LHS, RHS); 10071 } 10072 10073 QualType compType = UsualArithmeticConversions( 10074 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10075 if (LHS.isInvalid() || RHS.isInvalid()) 10076 return QualType(); 10077 10078 if (compType.isNull() || !compType->isIntegerType()) 10079 return InvalidOperands(Loc, LHS, RHS); 10080 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10081 return compType; 10082 } 10083 10084 /// Diagnose invalid arithmetic on two void pointers. 10085 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10086 Expr *LHSExpr, Expr *RHSExpr) { 10087 S.Diag(Loc, S.getLangOpts().CPlusPlus 10088 ? diag::err_typecheck_pointer_arith_void_type 10089 : diag::ext_gnu_void_ptr) 10090 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10091 << RHSExpr->getSourceRange(); 10092 } 10093 10094 /// Diagnose invalid arithmetic on a void pointer. 10095 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10096 Expr *Pointer) { 10097 S.Diag(Loc, S.getLangOpts().CPlusPlus 10098 ? diag::err_typecheck_pointer_arith_void_type 10099 : diag::ext_gnu_void_ptr) 10100 << 0 /* one pointer */ << Pointer->getSourceRange(); 10101 } 10102 10103 /// Diagnose invalid arithmetic on a null pointer. 10104 /// 10105 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10106 /// idiom, which we recognize as a GNU extension. 10107 /// 10108 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10109 Expr *Pointer, bool IsGNUIdiom) { 10110 if (IsGNUIdiom) 10111 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10112 << Pointer->getSourceRange(); 10113 else 10114 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10115 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10116 } 10117 10118 /// Diagnose invalid arithmetic on two function pointers. 10119 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10120 Expr *LHS, Expr *RHS) { 10121 assert(LHS->getType()->isAnyPointerType()); 10122 assert(RHS->getType()->isAnyPointerType()); 10123 S.Diag(Loc, S.getLangOpts().CPlusPlus 10124 ? diag::err_typecheck_pointer_arith_function_type 10125 : diag::ext_gnu_ptr_func_arith) 10126 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10127 // We only show the second type if it differs from the first. 10128 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10129 RHS->getType()) 10130 << RHS->getType()->getPointeeType() 10131 << LHS->getSourceRange() << RHS->getSourceRange(); 10132 } 10133 10134 /// Diagnose invalid arithmetic on a function pointer. 10135 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10136 Expr *Pointer) { 10137 assert(Pointer->getType()->isAnyPointerType()); 10138 S.Diag(Loc, S.getLangOpts().CPlusPlus 10139 ? diag::err_typecheck_pointer_arith_function_type 10140 : diag::ext_gnu_ptr_func_arith) 10141 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10142 << 0 /* one pointer, so only one type */ 10143 << Pointer->getSourceRange(); 10144 } 10145 10146 /// Emit error if Operand is incomplete pointer type 10147 /// 10148 /// \returns True if pointer has incomplete type 10149 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10150 Expr *Operand) { 10151 QualType ResType = Operand->getType(); 10152 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10153 ResType = ResAtomicType->getValueType(); 10154 10155 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10156 QualType PointeeTy = ResType->getPointeeType(); 10157 return S.RequireCompleteSizedType( 10158 Loc, PointeeTy, 10159 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10160 Operand->getSourceRange()); 10161 } 10162 10163 /// Check the validity of an arithmetic pointer operand. 10164 /// 10165 /// If the operand has pointer type, this code will check for pointer types 10166 /// which are invalid in arithmetic operations. These will be diagnosed 10167 /// appropriately, including whether or not the use is supported as an 10168 /// extension. 10169 /// 10170 /// \returns True when the operand is valid to use (even if as an extension). 10171 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10172 Expr *Operand) { 10173 QualType ResType = Operand->getType(); 10174 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10175 ResType = ResAtomicType->getValueType(); 10176 10177 if (!ResType->isAnyPointerType()) return true; 10178 10179 QualType PointeeTy = ResType->getPointeeType(); 10180 if (PointeeTy->isVoidType()) { 10181 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10182 return !S.getLangOpts().CPlusPlus; 10183 } 10184 if (PointeeTy->isFunctionType()) { 10185 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10186 return !S.getLangOpts().CPlusPlus; 10187 } 10188 10189 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10190 10191 return true; 10192 } 10193 10194 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10195 /// operands. 10196 /// 10197 /// This routine will diagnose any invalid arithmetic on pointer operands much 10198 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10199 /// for emitting a single diagnostic even for operations where both LHS and RHS 10200 /// are (potentially problematic) pointers. 10201 /// 10202 /// \returns True when the operand is valid to use (even if as an extension). 10203 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10204 Expr *LHSExpr, Expr *RHSExpr) { 10205 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10206 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10207 if (!isLHSPointer && !isRHSPointer) return true; 10208 10209 QualType LHSPointeeTy, RHSPointeeTy; 10210 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10211 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10212 10213 // if both are pointers check if operation is valid wrt address spaces 10214 if (isLHSPointer && isRHSPointer) { 10215 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10216 S.Diag(Loc, 10217 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10218 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10219 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10220 return false; 10221 } 10222 } 10223 10224 // Check for arithmetic on pointers to incomplete types. 10225 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10226 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10227 if (isLHSVoidPtr || isRHSVoidPtr) { 10228 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10229 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10230 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10231 10232 return !S.getLangOpts().CPlusPlus; 10233 } 10234 10235 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10236 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10237 if (isLHSFuncPtr || isRHSFuncPtr) { 10238 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10239 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10240 RHSExpr); 10241 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10242 10243 return !S.getLangOpts().CPlusPlus; 10244 } 10245 10246 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10247 return false; 10248 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10249 return false; 10250 10251 return true; 10252 } 10253 10254 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10255 /// literal. 10256 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10257 Expr *LHSExpr, Expr *RHSExpr) { 10258 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10259 Expr* IndexExpr = RHSExpr; 10260 if (!StrExpr) { 10261 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10262 IndexExpr = LHSExpr; 10263 } 10264 10265 bool IsStringPlusInt = StrExpr && 10266 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10267 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10268 return; 10269 10270 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10271 Self.Diag(OpLoc, diag::warn_string_plus_int) 10272 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10273 10274 // Only print a fixit for "str" + int, not for int + "str". 10275 if (IndexExpr == RHSExpr) { 10276 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10277 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10278 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10279 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10280 << FixItHint::CreateInsertion(EndLoc, "]"); 10281 } else 10282 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10283 } 10284 10285 /// Emit a warning when adding a char literal to a string. 10286 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10287 Expr *LHSExpr, Expr *RHSExpr) { 10288 const Expr *StringRefExpr = LHSExpr; 10289 const CharacterLiteral *CharExpr = 10290 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10291 10292 if (!CharExpr) { 10293 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10294 StringRefExpr = RHSExpr; 10295 } 10296 10297 if (!CharExpr || !StringRefExpr) 10298 return; 10299 10300 const QualType StringType = StringRefExpr->getType(); 10301 10302 // Return if not a PointerType. 10303 if (!StringType->isAnyPointerType()) 10304 return; 10305 10306 // Return if not a CharacterType. 10307 if (!StringType->getPointeeType()->isAnyCharacterType()) 10308 return; 10309 10310 ASTContext &Ctx = Self.getASTContext(); 10311 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10312 10313 const QualType CharType = CharExpr->getType(); 10314 if (!CharType->isAnyCharacterType() && 10315 CharType->isIntegerType() && 10316 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10317 Self.Diag(OpLoc, diag::warn_string_plus_char) 10318 << DiagRange << Ctx.CharTy; 10319 } else { 10320 Self.Diag(OpLoc, diag::warn_string_plus_char) 10321 << DiagRange << CharExpr->getType(); 10322 } 10323 10324 // Only print a fixit for str + char, not for char + str. 10325 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10326 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10327 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10328 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10329 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10330 << FixItHint::CreateInsertion(EndLoc, "]"); 10331 } else { 10332 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10333 } 10334 } 10335 10336 /// Emit error when two pointers are incompatible. 10337 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10338 Expr *LHSExpr, Expr *RHSExpr) { 10339 assert(LHSExpr->getType()->isAnyPointerType()); 10340 assert(RHSExpr->getType()->isAnyPointerType()); 10341 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10342 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10343 << RHSExpr->getSourceRange(); 10344 } 10345 10346 // C99 6.5.6 10347 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10348 SourceLocation Loc, BinaryOperatorKind Opc, 10349 QualType* CompLHSTy) { 10350 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10351 10352 if (LHS.get()->getType()->isVectorType() || 10353 RHS.get()->getType()->isVectorType()) { 10354 QualType compType = CheckVectorOperands( 10355 LHS, RHS, Loc, CompLHSTy, 10356 /*AllowBothBool*/getLangOpts().AltiVec, 10357 /*AllowBoolConversions*/getLangOpts().ZVector); 10358 if (CompLHSTy) *CompLHSTy = compType; 10359 return compType; 10360 } 10361 10362 if (LHS.get()->getType()->isConstantMatrixType() || 10363 RHS.get()->getType()->isConstantMatrixType()) { 10364 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10365 } 10366 10367 QualType compType = UsualArithmeticConversions( 10368 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10369 if (LHS.isInvalid() || RHS.isInvalid()) 10370 return QualType(); 10371 10372 // Diagnose "string literal" '+' int and string '+' "char literal". 10373 if (Opc == BO_Add) { 10374 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10375 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10376 } 10377 10378 // handle the common case first (both operands are arithmetic). 10379 if (!compType.isNull() && compType->isArithmeticType()) { 10380 if (CompLHSTy) *CompLHSTy = compType; 10381 return compType; 10382 } 10383 10384 // Type-checking. Ultimately the pointer's going to be in PExp; 10385 // note that we bias towards the LHS being the pointer. 10386 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10387 10388 bool isObjCPointer; 10389 if (PExp->getType()->isPointerType()) { 10390 isObjCPointer = false; 10391 } else if (PExp->getType()->isObjCObjectPointerType()) { 10392 isObjCPointer = true; 10393 } else { 10394 std::swap(PExp, IExp); 10395 if (PExp->getType()->isPointerType()) { 10396 isObjCPointer = false; 10397 } else if (PExp->getType()->isObjCObjectPointerType()) { 10398 isObjCPointer = true; 10399 } else { 10400 return InvalidOperands(Loc, LHS, RHS); 10401 } 10402 } 10403 assert(PExp->getType()->isAnyPointerType()); 10404 10405 if (!IExp->getType()->isIntegerType()) 10406 return InvalidOperands(Loc, LHS, RHS); 10407 10408 // Adding to a null pointer results in undefined behavior. 10409 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10410 Context, Expr::NPC_ValueDependentIsNotNull)) { 10411 // In C++ adding zero to a null pointer is defined. 10412 Expr::EvalResult KnownVal; 10413 if (!getLangOpts().CPlusPlus || 10414 (!IExp->isValueDependent() && 10415 (!IExp->EvaluateAsInt(KnownVal, Context) || 10416 KnownVal.Val.getInt() != 0))) { 10417 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10418 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10419 Context, BO_Add, PExp, IExp); 10420 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10421 } 10422 } 10423 10424 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10425 return QualType(); 10426 10427 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10428 return QualType(); 10429 10430 // Check array bounds for pointer arithemtic 10431 CheckArrayAccess(PExp, IExp); 10432 10433 if (CompLHSTy) { 10434 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10435 if (LHSTy.isNull()) { 10436 LHSTy = LHS.get()->getType(); 10437 if (LHSTy->isPromotableIntegerType()) 10438 LHSTy = Context.getPromotedIntegerType(LHSTy); 10439 } 10440 *CompLHSTy = LHSTy; 10441 } 10442 10443 return PExp->getType(); 10444 } 10445 10446 // C99 6.5.6 10447 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10448 SourceLocation Loc, 10449 QualType* CompLHSTy) { 10450 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10451 10452 if (LHS.get()->getType()->isVectorType() || 10453 RHS.get()->getType()->isVectorType()) { 10454 QualType compType = CheckVectorOperands( 10455 LHS, RHS, Loc, CompLHSTy, 10456 /*AllowBothBool*/getLangOpts().AltiVec, 10457 /*AllowBoolConversions*/getLangOpts().ZVector); 10458 if (CompLHSTy) *CompLHSTy = compType; 10459 return compType; 10460 } 10461 10462 if (LHS.get()->getType()->isConstantMatrixType() || 10463 RHS.get()->getType()->isConstantMatrixType()) { 10464 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10465 } 10466 10467 QualType compType = UsualArithmeticConversions( 10468 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10469 if (LHS.isInvalid() || RHS.isInvalid()) 10470 return QualType(); 10471 10472 // Enforce type constraints: C99 6.5.6p3. 10473 10474 // Handle the common case first (both operands are arithmetic). 10475 if (!compType.isNull() && compType->isArithmeticType()) { 10476 if (CompLHSTy) *CompLHSTy = compType; 10477 return compType; 10478 } 10479 10480 // Either ptr - int or ptr - ptr. 10481 if (LHS.get()->getType()->isAnyPointerType()) { 10482 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10483 10484 // Diagnose bad cases where we step over interface counts. 10485 if (LHS.get()->getType()->isObjCObjectPointerType() && 10486 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10487 return QualType(); 10488 10489 // The result type of a pointer-int computation is the pointer type. 10490 if (RHS.get()->getType()->isIntegerType()) { 10491 // Subtracting from a null pointer should produce a warning. 10492 // The last argument to the diagnose call says this doesn't match the 10493 // GNU int-to-pointer idiom. 10494 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10495 Expr::NPC_ValueDependentIsNotNull)) { 10496 // In C++ adding zero to a null pointer is defined. 10497 Expr::EvalResult KnownVal; 10498 if (!getLangOpts().CPlusPlus || 10499 (!RHS.get()->isValueDependent() && 10500 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10501 KnownVal.Val.getInt() != 0))) { 10502 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10503 } 10504 } 10505 10506 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10507 return QualType(); 10508 10509 // Check array bounds for pointer arithemtic 10510 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10511 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10512 10513 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10514 return LHS.get()->getType(); 10515 } 10516 10517 // Handle pointer-pointer subtractions. 10518 if (const PointerType *RHSPTy 10519 = RHS.get()->getType()->getAs<PointerType>()) { 10520 QualType rpointee = RHSPTy->getPointeeType(); 10521 10522 if (getLangOpts().CPlusPlus) { 10523 // Pointee types must be the same: C++ [expr.add] 10524 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10525 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10526 } 10527 } else { 10528 // Pointee types must be compatible C99 6.5.6p3 10529 if (!Context.typesAreCompatible( 10530 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10531 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10532 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10533 return QualType(); 10534 } 10535 } 10536 10537 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10538 LHS.get(), RHS.get())) 10539 return QualType(); 10540 10541 // FIXME: Add warnings for nullptr - ptr. 10542 10543 // The pointee type may have zero size. As an extension, a structure or 10544 // union may have zero size or an array may have zero length. In this 10545 // case subtraction does not make sense. 10546 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10547 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10548 if (ElementSize.isZero()) { 10549 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10550 << rpointee.getUnqualifiedType() 10551 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10552 } 10553 } 10554 10555 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10556 return Context.getPointerDiffType(); 10557 } 10558 } 10559 10560 return InvalidOperands(Loc, LHS, RHS); 10561 } 10562 10563 static bool isScopedEnumerationType(QualType T) { 10564 if (const EnumType *ET = T->getAs<EnumType>()) 10565 return ET->getDecl()->isScoped(); 10566 return false; 10567 } 10568 10569 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10570 SourceLocation Loc, BinaryOperatorKind Opc, 10571 QualType LHSType) { 10572 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10573 // so skip remaining warnings as we don't want to modify values within Sema. 10574 if (S.getLangOpts().OpenCL) 10575 return; 10576 10577 // Check right/shifter operand 10578 Expr::EvalResult RHSResult; 10579 if (RHS.get()->isValueDependent() || 10580 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10581 return; 10582 llvm::APSInt Right = RHSResult.Val.getInt(); 10583 10584 if (Right.isNegative()) { 10585 S.DiagRuntimeBehavior(Loc, RHS.get(), 10586 S.PDiag(diag::warn_shift_negative) 10587 << RHS.get()->getSourceRange()); 10588 return; 10589 } 10590 10591 QualType LHSExprType = LHS.get()->getType(); 10592 uint64_t LeftSize = LHSExprType->isExtIntType() 10593 ? S.Context.getIntWidth(LHSExprType) 10594 : S.Context.getTypeSize(LHSExprType); 10595 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10596 if (Right.uge(LeftBits)) { 10597 S.DiagRuntimeBehavior(Loc, RHS.get(), 10598 S.PDiag(diag::warn_shift_gt_typewidth) 10599 << RHS.get()->getSourceRange()); 10600 return; 10601 } 10602 10603 if (Opc != BO_Shl) 10604 return; 10605 10606 // When left shifting an ICE which is signed, we can check for overflow which 10607 // according to C++ standards prior to C++2a has undefined behavior 10608 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10609 // more than the maximum value representable in the result type, so never 10610 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10611 // expression is still probably a bug.) 10612 Expr::EvalResult LHSResult; 10613 if (LHS.get()->isValueDependent() || 10614 LHSType->hasUnsignedIntegerRepresentation() || 10615 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10616 return; 10617 llvm::APSInt Left = LHSResult.Val.getInt(); 10618 10619 // If LHS does not have a signed type and non-negative value 10620 // then, the behavior is undefined before C++2a. Warn about it. 10621 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10622 !S.getLangOpts().CPlusPlus20) { 10623 S.DiagRuntimeBehavior(Loc, LHS.get(), 10624 S.PDiag(diag::warn_shift_lhs_negative) 10625 << LHS.get()->getSourceRange()); 10626 return; 10627 } 10628 10629 llvm::APInt ResultBits = 10630 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10631 if (LeftBits.uge(ResultBits)) 10632 return; 10633 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10634 Result = Result.shl(Right); 10635 10636 // Print the bit representation of the signed integer as an unsigned 10637 // hexadecimal number. 10638 SmallString<40> HexResult; 10639 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10640 10641 // If we are only missing a sign bit, this is less likely to result in actual 10642 // bugs -- if the result is cast back to an unsigned type, it will have the 10643 // expected value. Thus we place this behind a different warning that can be 10644 // turned off separately if needed. 10645 if (LeftBits == ResultBits - 1) { 10646 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10647 << HexResult << LHSType 10648 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10649 return; 10650 } 10651 10652 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10653 << HexResult.str() << Result.getMinSignedBits() << LHSType 10654 << Left.getBitWidth() << LHS.get()->getSourceRange() 10655 << RHS.get()->getSourceRange(); 10656 } 10657 10658 /// Return the resulting type when a vector is shifted 10659 /// by a scalar or vector shift amount. 10660 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10661 SourceLocation Loc, bool IsCompAssign) { 10662 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10663 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10664 !LHS.get()->getType()->isVectorType()) { 10665 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10666 << RHS.get()->getType() << LHS.get()->getType() 10667 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10668 return QualType(); 10669 } 10670 10671 if (!IsCompAssign) { 10672 LHS = S.UsualUnaryConversions(LHS.get()); 10673 if (LHS.isInvalid()) return QualType(); 10674 } 10675 10676 RHS = S.UsualUnaryConversions(RHS.get()); 10677 if (RHS.isInvalid()) return QualType(); 10678 10679 QualType LHSType = LHS.get()->getType(); 10680 // Note that LHS might be a scalar because the routine calls not only in 10681 // OpenCL case. 10682 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10683 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10684 10685 // Note that RHS might not be a vector. 10686 QualType RHSType = RHS.get()->getType(); 10687 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10688 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10689 10690 // The operands need to be integers. 10691 if (!LHSEleType->isIntegerType()) { 10692 S.Diag(Loc, diag::err_typecheck_expect_int) 10693 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10694 return QualType(); 10695 } 10696 10697 if (!RHSEleType->isIntegerType()) { 10698 S.Diag(Loc, diag::err_typecheck_expect_int) 10699 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10700 return QualType(); 10701 } 10702 10703 if (!LHSVecTy) { 10704 assert(RHSVecTy); 10705 if (IsCompAssign) 10706 return RHSType; 10707 if (LHSEleType != RHSEleType) { 10708 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10709 LHSEleType = RHSEleType; 10710 } 10711 QualType VecTy = 10712 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10713 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10714 LHSType = VecTy; 10715 } else if (RHSVecTy) { 10716 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10717 // are applied component-wise. So if RHS is a vector, then ensure 10718 // that the number of elements is the same as LHS... 10719 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10720 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10721 << LHS.get()->getType() << RHS.get()->getType() 10722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10723 return QualType(); 10724 } 10725 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10726 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10727 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10728 if (LHSBT != RHSBT && 10729 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10730 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10731 << LHS.get()->getType() << RHS.get()->getType() 10732 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10733 } 10734 } 10735 } else { 10736 // ...else expand RHS to match the number of elements in LHS. 10737 QualType VecTy = 10738 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10739 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10740 } 10741 10742 return LHSType; 10743 } 10744 10745 // C99 6.5.7 10746 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10747 SourceLocation Loc, BinaryOperatorKind Opc, 10748 bool IsCompAssign) { 10749 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10750 10751 // Vector shifts promote their scalar inputs to vector type. 10752 if (LHS.get()->getType()->isVectorType() || 10753 RHS.get()->getType()->isVectorType()) { 10754 if (LangOpts.ZVector) { 10755 // The shift operators for the z vector extensions work basically 10756 // like general shifts, except that neither the LHS nor the RHS is 10757 // allowed to be a "vector bool". 10758 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10759 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10760 return InvalidOperands(Loc, LHS, RHS); 10761 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10762 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10763 return InvalidOperands(Loc, LHS, RHS); 10764 } 10765 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10766 } 10767 10768 // Shifts don't perform usual arithmetic conversions, they just do integer 10769 // promotions on each operand. C99 6.5.7p3 10770 10771 // For the LHS, do usual unary conversions, but then reset them away 10772 // if this is a compound assignment. 10773 ExprResult OldLHS = LHS; 10774 LHS = UsualUnaryConversions(LHS.get()); 10775 if (LHS.isInvalid()) 10776 return QualType(); 10777 QualType LHSType = LHS.get()->getType(); 10778 if (IsCompAssign) LHS = OldLHS; 10779 10780 // The RHS is simpler. 10781 RHS = UsualUnaryConversions(RHS.get()); 10782 if (RHS.isInvalid()) 10783 return QualType(); 10784 QualType RHSType = RHS.get()->getType(); 10785 10786 // C99 6.5.7p2: Each of the operands shall have integer type. 10787 if (!LHSType->hasIntegerRepresentation() || 10788 !RHSType->hasIntegerRepresentation()) 10789 return InvalidOperands(Loc, LHS, RHS); 10790 10791 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10792 // hasIntegerRepresentation() above instead of this. 10793 if (isScopedEnumerationType(LHSType) || 10794 isScopedEnumerationType(RHSType)) { 10795 return InvalidOperands(Loc, LHS, RHS); 10796 } 10797 // Sanity-check shift operands 10798 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10799 10800 // "The type of the result is that of the promoted left operand." 10801 return LHSType; 10802 } 10803 10804 /// Diagnose bad pointer comparisons. 10805 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10806 ExprResult &LHS, ExprResult &RHS, 10807 bool IsError) { 10808 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10809 : diag::ext_typecheck_comparison_of_distinct_pointers) 10810 << LHS.get()->getType() << RHS.get()->getType() 10811 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10812 } 10813 10814 /// Returns false if the pointers are converted to a composite type, 10815 /// true otherwise. 10816 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10817 ExprResult &LHS, ExprResult &RHS) { 10818 // C++ [expr.rel]p2: 10819 // [...] Pointer conversions (4.10) and qualification 10820 // conversions (4.4) are performed on pointer operands (or on 10821 // a pointer operand and a null pointer constant) to bring 10822 // them to their composite pointer type. [...] 10823 // 10824 // C++ [expr.eq]p1 uses the same notion for (in)equality 10825 // comparisons of pointers. 10826 10827 QualType LHSType = LHS.get()->getType(); 10828 QualType RHSType = RHS.get()->getType(); 10829 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10830 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10831 10832 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10833 if (T.isNull()) { 10834 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10835 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10836 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10837 else 10838 S.InvalidOperands(Loc, LHS, RHS); 10839 return true; 10840 } 10841 10842 return false; 10843 } 10844 10845 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10846 ExprResult &LHS, 10847 ExprResult &RHS, 10848 bool IsError) { 10849 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10850 : diag::ext_typecheck_comparison_of_fptr_to_void) 10851 << LHS.get()->getType() << RHS.get()->getType() 10852 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10853 } 10854 10855 static bool isObjCObjectLiteral(ExprResult &E) { 10856 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10857 case Stmt::ObjCArrayLiteralClass: 10858 case Stmt::ObjCDictionaryLiteralClass: 10859 case Stmt::ObjCStringLiteralClass: 10860 case Stmt::ObjCBoxedExprClass: 10861 return true; 10862 default: 10863 // Note that ObjCBoolLiteral is NOT an object literal! 10864 return false; 10865 } 10866 } 10867 10868 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10869 const ObjCObjectPointerType *Type = 10870 LHS->getType()->getAs<ObjCObjectPointerType>(); 10871 10872 // If this is not actually an Objective-C object, bail out. 10873 if (!Type) 10874 return false; 10875 10876 // Get the LHS object's interface type. 10877 QualType InterfaceType = Type->getPointeeType(); 10878 10879 // If the RHS isn't an Objective-C object, bail out. 10880 if (!RHS->getType()->isObjCObjectPointerType()) 10881 return false; 10882 10883 // Try to find the -isEqual: method. 10884 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10885 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10886 InterfaceType, 10887 /*IsInstance=*/true); 10888 if (!Method) { 10889 if (Type->isObjCIdType()) { 10890 // For 'id', just check the global pool. 10891 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10892 /*receiverId=*/true); 10893 } else { 10894 // Check protocols. 10895 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10896 /*IsInstance=*/true); 10897 } 10898 } 10899 10900 if (!Method) 10901 return false; 10902 10903 QualType T = Method->parameters()[0]->getType(); 10904 if (!T->isObjCObjectPointerType()) 10905 return false; 10906 10907 QualType R = Method->getReturnType(); 10908 if (!R->isScalarType()) 10909 return false; 10910 10911 return true; 10912 } 10913 10914 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10915 FromE = FromE->IgnoreParenImpCasts(); 10916 switch (FromE->getStmtClass()) { 10917 default: 10918 break; 10919 case Stmt::ObjCStringLiteralClass: 10920 // "string literal" 10921 return LK_String; 10922 case Stmt::ObjCArrayLiteralClass: 10923 // "array literal" 10924 return LK_Array; 10925 case Stmt::ObjCDictionaryLiteralClass: 10926 // "dictionary literal" 10927 return LK_Dictionary; 10928 case Stmt::BlockExprClass: 10929 return LK_Block; 10930 case Stmt::ObjCBoxedExprClass: { 10931 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10932 switch (Inner->getStmtClass()) { 10933 case Stmt::IntegerLiteralClass: 10934 case Stmt::FloatingLiteralClass: 10935 case Stmt::CharacterLiteralClass: 10936 case Stmt::ObjCBoolLiteralExprClass: 10937 case Stmt::CXXBoolLiteralExprClass: 10938 // "numeric literal" 10939 return LK_Numeric; 10940 case Stmt::ImplicitCastExprClass: { 10941 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10942 // Boolean literals can be represented by implicit casts. 10943 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10944 return LK_Numeric; 10945 break; 10946 } 10947 default: 10948 break; 10949 } 10950 return LK_Boxed; 10951 } 10952 } 10953 return LK_None; 10954 } 10955 10956 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10957 ExprResult &LHS, ExprResult &RHS, 10958 BinaryOperator::Opcode Opc){ 10959 Expr *Literal; 10960 Expr *Other; 10961 if (isObjCObjectLiteral(LHS)) { 10962 Literal = LHS.get(); 10963 Other = RHS.get(); 10964 } else { 10965 Literal = RHS.get(); 10966 Other = LHS.get(); 10967 } 10968 10969 // Don't warn on comparisons against nil. 10970 Other = Other->IgnoreParenCasts(); 10971 if (Other->isNullPointerConstant(S.getASTContext(), 10972 Expr::NPC_ValueDependentIsNotNull)) 10973 return; 10974 10975 // This should be kept in sync with warn_objc_literal_comparison. 10976 // LK_String should always be after the other literals, since it has its own 10977 // warning flag. 10978 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10979 assert(LiteralKind != Sema::LK_Block); 10980 if (LiteralKind == Sema::LK_None) { 10981 llvm_unreachable("Unknown Objective-C object literal kind"); 10982 } 10983 10984 if (LiteralKind == Sema::LK_String) 10985 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10986 << Literal->getSourceRange(); 10987 else 10988 S.Diag(Loc, diag::warn_objc_literal_comparison) 10989 << LiteralKind << Literal->getSourceRange(); 10990 10991 if (BinaryOperator::isEqualityOp(Opc) && 10992 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10993 SourceLocation Start = LHS.get()->getBeginLoc(); 10994 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10995 CharSourceRange OpRange = 10996 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10997 10998 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10999 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11000 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11001 << FixItHint::CreateInsertion(End, "]"); 11002 } 11003 } 11004 11005 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11006 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11007 ExprResult &RHS, SourceLocation Loc, 11008 BinaryOperatorKind Opc) { 11009 // Check that left hand side is !something. 11010 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11011 if (!UO || UO->getOpcode() != UO_LNot) return; 11012 11013 // Only check if the right hand side is non-bool arithmetic type. 11014 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11015 11016 // Make sure that the something in !something is not bool. 11017 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11018 if (SubExpr->isKnownToHaveBooleanValue()) return; 11019 11020 // Emit warning. 11021 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11022 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11023 << Loc << IsBitwiseOp; 11024 11025 // First note suggest !(x < y) 11026 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11027 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11028 FirstClose = S.getLocForEndOfToken(FirstClose); 11029 if (FirstClose.isInvalid()) 11030 FirstOpen = SourceLocation(); 11031 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11032 << IsBitwiseOp 11033 << FixItHint::CreateInsertion(FirstOpen, "(") 11034 << FixItHint::CreateInsertion(FirstClose, ")"); 11035 11036 // Second note suggests (!x) < y 11037 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11038 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11039 SecondClose = S.getLocForEndOfToken(SecondClose); 11040 if (SecondClose.isInvalid()) 11041 SecondOpen = SourceLocation(); 11042 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11043 << FixItHint::CreateInsertion(SecondOpen, "(") 11044 << FixItHint::CreateInsertion(SecondClose, ")"); 11045 } 11046 11047 // Returns true if E refers to a non-weak array. 11048 static bool checkForArray(const Expr *E) { 11049 const ValueDecl *D = nullptr; 11050 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11051 D = DR->getDecl(); 11052 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11053 if (Mem->isImplicitAccess()) 11054 D = Mem->getMemberDecl(); 11055 } 11056 if (!D) 11057 return false; 11058 return D->getType()->isArrayType() && !D->isWeak(); 11059 } 11060 11061 /// Diagnose some forms of syntactically-obvious tautological comparison. 11062 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11063 Expr *LHS, Expr *RHS, 11064 BinaryOperatorKind Opc) { 11065 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11066 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11067 11068 QualType LHSType = LHS->getType(); 11069 QualType RHSType = RHS->getType(); 11070 if (LHSType->hasFloatingRepresentation() || 11071 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11072 S.inTemplateInstantiation()) 11073 return; 11074 11075 // Comparisons between two array types are ill-formed for operator<=>, so 11076 // we shouldn't emit any additional warnings about it. 11077 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11078 return; 11079 11080 // For non-floating point types, check for self-comparisons of the form 11081 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11082 // often indicate logic errors in the program. 11083 // 11084 // NOTE: Don't warn about comparison expressions resulting from macro 11085 // expansion. Also don't warn about comparisons which are only self 11086 // comparisons within a template instantiation. The warnings should catch 11087 // obvious cases in the definition of the template anyways. The idea is to 11088 // warn when the typed comparison operator will always evaluate to the same 11089 // result. 11090 11091 // Used for indexing into %select in warn_comparison_always 11092 enum { 11093 AlwaysConstant, 11094 AlwaysTrue, 11095 AlwaysFalse, 11096 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11097 }; 11098 11099 // C++2a [depr.array.comp]: 11100 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11101 // operands of array type are deprecated. 11102 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11103 RHSStripped->getType()->isArrayType()) { 11104 S.Diag(Loc, diag::warn_depr_array_comparison) 11105 << LHS->getSourceRange() << RHS->getSourceRange() 11106 << LHSStripped->getType() << RHSStripped->getType(); 11107 // Carry on to produce the tautological comparison warning, if this 11108 // expression is potentially-evaluated, we can resolve the array to a 11109 // non-weak declaration, and so on. 11110 } 11111 11112 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11113 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11114 unsigned Result; 11115 switch (Opc) { 11116 case BO_EQ: 11117 case BO_LE: 11118 case BO_GE: 11119 Result = AlwaysTrue; 11120 break; 11121 case BO_NE: 11122 case BO_LT: 11123 case BO_GT: 11124 Result = AlwaysFalse; 11125 break; 11126 case BO_Cmp: 11127 Result = AlwaysEqual; 11128 break; 11129 default: 11130 Result = AlwaysConstant; 11131 break; 11132 } 11133 S.DiagRuntimeBehavior(Loc, nullptr, 11134 S.PDiag(diag::warn_comparison_always) 11135 << 0 /*self-comparison*/ 11136 << Result); 11137 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11138 // What is it always going to evaluate to? 11139 unsigned Result; 11140 switch (Opc) { 11141 case BO_EQ: // e.g. array1 == array2 11142 Result = AlwaysFalse; 11143 break; 11144 case BO_NE: // e.g. array1 != array2 11145 Result = AlwaysTrue; 11146 break; 11147 default: // e.g. array1 <= array2 11148 // The best we can say is 'a constant' 11149 Result = AlwaysConstant; 11150 break; 11151 } 11152 S.DiagRuntimeBehavior(Loc, nullptr, 11153 S.PDiag(diag::warn_comparison_always) 11154 << 1 /*array comparison*/ 11155 << Result); 11156 } 11157 } 11158 11159 if (isa<CastExpr>(LHSStripped)) 11160 LHSStripped = LHSStripped->IgnoreParenCasts(); 11161 if (isa<CastExpr>(RHSStripped)) 11162 RHSStripped = RHSStripped->IgnoreParenCasts(); 11163 11164 // Warn about comparisons against a string constant (unless the other 11165 // operand is null); the user probably wants string comparison function. 11166 Expr *LiteralString = nullptr; 11167 Expr *LiteralStringStripped = nullptr; 11168 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11169 !RHSStripped->isNullPointerConstant(S.Context, 11170 Expr::NPC_ValueDependentIsNull)) { 11171 LiteralString = LHS; 11172 LiteralStringStripped = LHSStripped; 11173 } else if ((isa<StringLiteral>(RHSStripped) || 11174 isa<ObjCEncodeExpr>(RHSStripped)) && 11175 !LHSStripped->isNullPointerConstant(S.Context, 11176 Expr::NPC_ValueDependentIsNull)) { 11177 LiteralString = RHS; 11178 LiteralStringStripped = RHSStripped; 11179 } 11180 11181 if (LiteralString) { 11182 S.DiagRuntimeBehavior(Loc, nullptr, 11183 S.PDiag(diag::warn_stringcompare) 11184 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11185 << LiteralString->getSourceRange()); 11186 } 11187 } 11188 11189 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11190 switch (CK) { 11191 default: { 11192 #ifndef NDEBUG 11193 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11194 << "\n"; 11195 #endif 11196 llvm_unreachable("unhandled cast kind"); 11197 } 11198 case CK_UserDefinedConversion: 11199 return ICK_Identity; 11200 case CK_LValueToRValue: 11201 return ICK_Lvalue_To_Rvalue; 11202 case CK_ArrayToPointerDecay: 11203 return ICK_Array_To_Pointer; 11204 case CK_FunctionToPointerDecay: 11205 return ICK_Function_To_Pointer; 11206 case CK_IntegralCast: 11207 return ICK_Integral_Conversion; 11208 case CK_FloatingCast: 11209 return ICK_Floating_Conversion; 11210 case CK_IntegralToFloating: 11211 case CK_FloatingToIntegral: 11212 return ICK_Floating_Integral; 11213 case CK_IntegralComplexCast: 11214 case CK_FloatingComplexCast: 11215 case CK_FloatingComplexToIntegralComplex: 11216 case CK_IntegralComplexToFloatingComplex: 11217 return ICK_Complex_Conversion; 11218 case CK_FloatingComplexToReal: 11219 case CK_FloatingRealToComplex: 11220 case CK_IntegralComplexToReal: 11221 case CK_IntegralRealToComplex: 11222 return ICK_Complex_Real; 11223 } 11224 } 11225 11226 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11227 QualType FromType, 11228 SourceLocation Loc) { 11229 // Check for a narrowing implicit conversion. 11230 StandardConversionSequence SCS; 11231 SCS.setAsIdentityConversion(); 11232 SCS.setToType(0, FromType); 11233 SCS.setToType(1, ToType); 11234 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11235 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11236 11237 APValue PreNarrowingValue; 11238 QualType PreNarrowingType; 11239 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11240 PreNarrowingType, 11241 /*IgnoreFloatToIntegralConversion*/ true)) { 11242 case NK_Dependent_Narrowing: 11243 // Implicit conversion to a narrower type, but the expression is 11244 // value-dependent so we can't tell whether it's actually narrowing. 11245 case NK_Not_Narrowing: 11246 return false; 11247 11248 case NK_Constant_Narrowing: 11249 // Implicit conversion to a narrower type, and the value is not a constant 11250 // expression. 11251 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11252 << /*Constant*/ 1 11253 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11254 return true; 11255 11256 case NK_Variable_Narrowing: 11257 // Implicit conversion to a narrower type, and the value is not a constant 11258 // expression. 11259 case NK_Type_Narrowing: 11260 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11261 << /*Constant*/ 0 << FromType << ToType; 11262 // TODO: It's not a constant expression, but what if the user intended it 11263 // to be? Can we produce notes to help them figure out why it isn't? 11264 return true; 11265 } 11266 llvm_unreachable("unhandled case in switch"); 11267 } 11268 11269 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11270 ExprResult &LHS, 11271 ExprResult &RHS, 11272 SourceLocation Loc) { 11273 QualType LHSType = LHS.get()->getType(); 11274 QualType RHSType = RHS.get()->getType(); 11275 // Dig out the original argument type and expression before implicit casts 11276 // were applied. These are the types/expressions we need to check the 11277 // [expr.spaceship] requirements against. 11278 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11279 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11280 QualType LHSStrippedType = LHSStripped.get()->getType(); 11281 QualType RHSStrippedType = RHSStripped.get()->getType(); 11282 11283 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11284 // other is not, the program is ill-formed. 11285 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11286 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11287 return QualType(); 11288 } 11289 11290 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11291 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11292 RHSStrippedType->isEnumeralType(); 11293 if (NumEnumArgs == 1) { 11294 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11295 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11296 if (OtherTy->hasFloatingRepresentation()) { 11297 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11298 return QualType(); 11299 } 11300 } 11301 if (NumEnumArgs == 2) { 11302 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11303 // type E, the operator yields the result of converting the operands 11304 // to the underlying type of E and applying <=> to the converted operands. 11305 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11306 S.InvalidOperands(Loc, LHS, RHS); 11307 return QualType(); 11308 } 11309 QualType IntType = 11310 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11311 assert(IntType->isArithmeticType()); 11312 11313 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11314 // promote the boolean type, and all other promotable integer types, to 11315 // avoid this. 11316 if (IntType->isPromotableIntegerType()) 11317 IntType = S.Context.getPromotedIntegerType(IntType); 11318 11319 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11320 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11321 LHSType = RHSType = IntType; 11322 } 11323 11324 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11325 // usual arithmetic conversions are applied to the operands. 11326 QualType Type = 11327 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11328 if (LHS.isInvalid() || RHS.isInvalid()) 11329 return QualType(); 11330 if (Type.isNull()) 11331 return S.InvalidOperands(Loc, LHS, RHS); 11332 11333 Optional<ComparisonCategoryType> CCT = 11334 getComparisonCategoryForBuiltinCmp(Type); 11335 if (!CCT) 11336 return S.InvalidOperands(Loc, LHS, RHS); 11337 11338 bool HasNarrowing = checkThreeWayNarrowingConversion( 11339 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11340 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11341 RHS.get()->getBeginLoc()); 11342 if (HasNarrowing) 11343 return QualType(); 11344 11345 assert(!Type.isNull() && "composite type for <=> has not been set"); 11346 11347 return S.CheckComparisonCategoryType( 11348 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11349 } 11350 11351 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11352 ExprResult &RHS, 11353 SourceLocation Loc, 11354 BinaryOperatorKind Opc) { 11355 if (Opc == BO_Cmp) 11356 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11357 11358 // C99 6.5.8p3 / C99 6.5.9p4 11359 QualType Type = 11360 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11361 if (LHS.isInvalid() || RHS.isInvalid()) 11362 return QualType(); 11363 if (Type.isNull()) 11364 return S.InvalidOperands(Loc, LHS, RHS); 11365 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11366 11367 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11368 return S.InvalidOperands(Loc, LHS, RHS); 11369 11370 // Check for comparisons of floating point operands using != and ==. 11371 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11372 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11373 11374 // The result of comparisons is 'bool' in C++, 'int' in C. 11375 return S.Context.getLogicalOperationType(); 11376 } 11377 11378 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11379 if (!NullE.get()->getType()->isAnyPointerType()) 11380 return; 11381 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11382 if (!E.get()->getType()->isAnyPointerType() && 11383 E.get()->isNullPointerConstant(Context, 11384 Expr::NPC_ValueDependentIsNotNull) == 11385 Expr::NPCK_ZeroExpression) { 11386 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11387 if (CL->getValue() == 0) 11388 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11389 << NullValue 11390 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11391 NullValue ? "NULL" : "(void *)0"); 11392 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11393 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11394 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11395 if (T == Context.CharTy) 11396 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11397 << NullValue 11398 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11399 NullValue ? "NULL" : "(void *)0"); 11400 } 11401 } 11402 } 11403 11404 // C99 6.5.8, C++ [expr.rel] 11405 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11406 SourceLocation Loc, 11407 BinaryOperatorKind Opc) { 11408 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11409 bool IsThreeWay = Opc == BO_Cmp; 11410 bool IsOrdered = IsRelational || IsThreeWay; 11411 auto IsAnyPointerType = [](ExprResult E) { 11412 QualType Ty = E.get()->getType(); 11413 return Ty->isPointerType() || Ty->isMemberPointerType(); 11414 }; 11415 11416 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11417 // type, array-to-pointer, ..., conversions are performed on both operands to 11418 // bring them to their composite type. 11419 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11420 // any type-related checks. 11421 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11422 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11423 if (LHS.isInvalid()) 11424 return QualType(); 11425 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11426 if (RHS.isInvalid()) 11427 return QualType(); 11428 } else { 11429 LHS = DefaultLvalueConversion(LHS.get()); 11430 if (LHS.isInvalid()) 11431 return QualType(); 11432 RHS = DefaultLvalueConversion(RHS.get()); 11433 if (RHS.isInvalid()) 11434 return QualType(); 11435 } 11436 11437 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11438 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11439 CheckPtrComparisonWithNullChar(LHS, RHS); 11440 CheckPtrComparisonWithNullChar(RHS, LHS); 11441 } 11442 11443 // Handle vector comparisons separately. 11444 if (LHS.get()->getType()->isVectorType() || 11445 RHS.get()->getType()->isVectorType()) 11446 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11447 11448 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11449 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11450 11451 QualType LHSType = LHS.get()->getType(); 11452 QualType RHSType = RHS.get()->getType(); 11453 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11454 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11455 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11456 11457 const Expr::NullPointerConstantKind LHSNullKind = 11458 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11459 const Expr::NullPointerConstantKind RHSNullKind = 11460 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11461 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11462 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11463 11464 auto computeResultTy = [&]() { 11465 if (Opc != BO_Cmp) 11466 return Context.getLogicalOperationType(); 11467 assert(getLangOpts().CPlusPlus); 11468 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11469 11470 QualType CompositeTy = LHS.get()->getType(); 11471 assert(!CompositeTy->isReferenceType()); 11472 11473 Optional<ComparisonCategoryType> CCT = 11474 getComparisonCategoryForBuiltinCmp(CompositeTy); 11475 if (!CCT) 11476 return InvalidOperands(Loc, LHS, RHS); 11477 11478 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11479 // P0946R0: Comparisons between a null pointer constant and an object 11480 // pointer result in std::strong_equality, which is ill-formed under 11481 // P1959R0. 11482 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11483 << (LHSIsNull ? LHS.get()->getSourceRange() 11484 : RHS.get()->getSourceRange()); 11485 return QualType(); 11486 } 11487 11488 return CheckComparisonCategoryType( 11489 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11490 }; 11491 11492 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11493 bool IsEquality = Opc == BO_EQ; 11494 if (RHSIsNull) 11495 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11496 RHS.get()->getSourceRange()); 11497 else 11498 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11499 LHS.get()->getSourceRange()); 11500 } 11501 11502 if ((LHSType->isIntegerType() && !LHSIsNull) || 11503 (RHSType->isIntegerType() && !RHSIsNull)) { 11504 // Skip normal pointer conversion checks in this case; we have better 11505 // diagnostics for this below. 11506 } else if (getLangOpts().CPlusPlus) { 11507 // Equality comparison of a function pointer to a void pointer is invalid, 11508 // but we allow it as an extension. 11509 // FIXME: If we really want to allow this, should it be part of composite 11510 // pointer type computation so it works in conditionals too? 11511 if (!IsOrdered && 11512 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11513 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11514 // This is a gcc extension compatibility comparison. 11515 // In a SFINAE context, we treat this as a hard error to maintain 11516 // conformance with the C++ standard. 11517 diagnoseFunctionPointerToVoidComparison( 11518 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11519 11520 if (isSFINAEContext()) 11521 return QualType(); 11522 11523 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11524 return computeResultTy(); 11525 } 11526 11527 // C++ [expr.eq]p2: 11528 // If at least one operand is a pointer [...] bring them to their 11529 // composite pointer type. 11530 // C++ [expr.spaceship]p6 11531 // If at least one of the operands is of pointer type, [...] bring them 11532 // to their composite pointer type. 11533 // C++ [expr.rel]p2: 11534 // If both operands are pointers, [...] bring them to their composite 11535 // pointer type. 11536 // For <=>, the only valid non-pointer types are arrays and functions, and 11537 // we already decayed those, so this is really the same as the relational 11538 // comparison rule. 11539 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11540 (IsOrdered ? 2 : 1) && 11541 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11542 RHSType->isObjCObjectPointerType()))) { 11543 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11544 return QualType(); 11545 return computeResultTy(); 11546 } 11547 } else if (LHSType->isPointerType() && 11548 RHSType->isPointerType()) { // C99 6.5.8p2 11549 // All of the following pointer-related warnings are GCC extensions, except 11550 // when handling null pointer constants. 11551 QualType LCanPointeeTy = 11552 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11553 QualType RCanPointeeTy = 11554 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11555 11556 // C99 6.5.9p2 and C99 6.5.8p2 11557 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11558 RCanPointeeTy.getUnqualifiedType())) { 11559 if (IsRelational) { 11560 // Pointers both need to point to complete or incomplete types 11561 if ((LCanPointeeTy->isIncompleteType() != 11562 RCanPointeeTy->isIncompleteType()) && 11563 !getLangOpts().C11) { 11564 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11565 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11566 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11567 << RCanPointeeTy->isIncompleteType(); 11568 } 11569 if (LCanPointeeTy->isFunctionType()) { 11570 // Valid unless a relational comparison of function pointers 11571 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11572 << LHSType << RHSType << LHS.get()->getSourceRange() 11573 << RHS.get()->getSourceRange(); 11574 } 11575 } 11576 } else if (!IsRelational && 11577 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11578 // Valid unless comparison between non-null pointer and function pointer 11579 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11580 && !LHSIsNull && !RHSIsNull) 11581 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11582 /*isError*/false); 11583 } else { 11584 // Invalid 11585 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11586 } 11587 if (LCanPointeeTy != RCanPointeeTy) { 11588 // Treat NULL constant as a special case in OpenCL. 11589 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11590 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11591 Diag(Loc, 11592 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11593 << LHSType << RHSType << 0 /* comparison */ 11594 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11595 } 11596 } 11597 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11598 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11599 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11600 : CK_BitCast; 11601 if (LHSIsNull && !RHSIsNull) 11602 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11603 else 11604 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11605 } 11606 return computeResultTy(); 11607 } 11608 11609 if (getLangOpts().CPlusPlus) { 11610 // C++ [expr.eq]p4: 11611 // Two operands of type std::nullptr_t or one operand of type 11612 // std::nullptr_t and the other a null pointer constant compare equal. 11613 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11614 if (LHSType->isNullPtrType()) { 11615 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11616 return computeResultTy(); 11617 } 11618 if (RHSType->isNullPtrType()) { 11619 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11620 return computeResultTy(); 11621 } 11622 } 11623 11624 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11625 // These aren't covered by the composite pointer type rules. 11626 if (!IsOrdered && RHSType->isNullPtrType() && 11627 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11628 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11629 return computeResultTy(); 11630 } 11631 if (!IsOrdered && LHSType->isNullPtrType() && 11632 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11633 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11634 return computeResultTy(); 11635 } 11636 11637 if (IsRelational && 11638 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11639 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11640 // HACK: Relational comparison of nullptr_t against a pointer type is 11641 // invalid per DR583, but we allow it within std::less<> and friends, 11642 // since otherwise common uses of it break. 11643 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11644 // friends to have std::nullptr_t overload candidates. 11645 DeclContext *DC = CurContext; 11646 if (isa<FunctionDecl>(DC)) 11647 DC = DC->getParent(); 11648 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11649 if (CTSD->isInStdNamespace() && 11650 llvm::StringSwitch<bool>(CTSD->getName()) 11651 .Cases("less", "less_equal", "greater", "greater_equal", true) 11652 .Default(false)) { 11653 if (RHSType->isNullPtrType()) 11654 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11655 else 11656 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11657 return computeResultTy(); 11658 } 11659 } 11660 } 11661 11662 // C++ [expr.eq]p2: 11663 // If at least one operand is a pointer to member, [...] bring them to 11664 // their composite pointer type. 11665 if (!IsOrdered && 11666 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11667 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11668 return QualType(); 11669 else 11670 return computeResultTy(); 11671 } 11672 } 11673 11674 // Handle block pointer types. 11675 if (!IsOrdered && LHSType->isBlockPointerType() && 11676 RHSType->isBlockPointerType()) { 11677 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11678 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11679 11680 if (!LHSIsNull && !RHSIsNull && 11681 !Context.typesAreCompatible(lpointee, rpointee)) { 11682 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11683 << LHSType << RHSType << LHS.get()->getSourceRange() 11684 << RHS.get()->getSourceRange(); 11685 } 11686 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11687 return computeResultTy(); 11688 } 11689 11690 // Allow block pointers to be compared with null pointer constants. 11691 if (!IsOrdered 11692 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11693 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11694 if (!LHSIsNull && !RHSIsNull) { 11695 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11696 ->getPointeeType()->isVoidType()) 11697 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11698 ->getPointeeType()->isVoidType()))) 11699 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11700 << LHSType << RHSType << LHS.get()->getSourceRange() 11701 << RHS.get()->getSourceRange(); 11702 } 11703 if (LHSIsNull && !RHSIsNull) 11704 LHS = ImpCastExprToType(LHS.get(), RHSType, 11705 RHSType->isPointerType() ? CK_BitCast 11706 : CK_AnyPointerToBlockPointerCast); 11707 else 11708 RHS = ImpCastExprToType(RHS.get(), LHSType, 11709 LHSType->isPointerType() ? CK_BitCast 11710 : CK_AnyPointerToBlockPointerCast); 11711 return computeResultTy(); 11712 } 11713 11714 if (LHSType->isObjCObjectPointerType() || 11715 RHSType->isObjCObjectPointerType()) { 11716 const PointerType *LPT = LHSType->getAs<PointerType>(); 11717 const PointerType *RPT = RHSType->getAs<PointerType>(); 11718 if (LPT || RPT) { 11719 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11720 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11721 11722 if (!LPtrToVoid && !RPtrToVoid && 11723 !Context.typesAreCompatible(LHSType, RHSType)) { 11724 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11725 /*isError*/false); 11726 } 11727 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11728 // the RHS, but we have test coverage for this behavior. 11729 // FIXME: Consider using convertPointersToCompositeType in C++. 11730 if (LHSIsNull && !RHSIsNull) { 11731 Expr *E = LHS.get(); 11732 if (getLangOpts().ObjCAutoRefCount) 11733 CheckObjCConversion(SourceRange(), RHSType, E, 11734 CCK_ImplicitConversion); 11735 LHS = ImpCastExprToType(E, RHSType, 11736 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11737 } 11738 else { 11739 Expr *E = RHS.get(); 11740 if (getLangOpts().ObjCAutoRefCount) 11741 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11742 /*Diagnose=*/true, 11743 /*DiagnoseCFAudited=*/false, Opc); 11744 RHS = ImpCastExprToType(E, LHSType, 11745 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11746 } 11747 return computeResultTy(); 11748 } 11749 if (LHSType->isObjCObjectPointerType() && 11750 RHSType->isObjCObjectPointerType()) { 11751 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11752 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11753 /*isError*/false); 11754 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11755 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11756 11757 if (LHSIsNull && !RHSIsNull) 11758 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11759 else 11760 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11761 return computeResultTy(); 11762 } 11763 11764 if (!IsOrdered && LHSType->isBlockPointerType() && 11765 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11766 LHS = ImpCastExprToType(LHS.get(), RHSType, 11767 CK_BlockPointerToObjCPointerCast); 11768 return computeResultTy(); 11769 } else if (!IsOrdered && 11770 LHSType->isBlockCompatibleObjCPointerType(Context) && 11771 RHSType->isBlockPointerType()) { 11772 RHS = ImpCastExprToType(RHS.get(), LHSType, 11773 CK_BlockPointerToObjCPointerCast); 11774 return computeResultTy(); 11775 } 11776 } 11777 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11778 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11779 unsigned DiagID = 0; 11780 bool isError = false; 11781 if (LangOpts.DebuggerSupport) { 11782 // Under a debugger, allow the comparison of pointers to integers, 11783 // since users tend to want to compare addresses. 11784 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11785 (RHSIsNull && RHSType->isIntegerType())) { 11786 if (IsOrdered) { 11787 isError = getLangOpts().CPlusPlus; 11788 DiagID = 11789 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11790 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11791 } 11792 } else if (getLangOpts().CPlusPlus) { 11793 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11794 isError = true; 11795 } else if (IsOrdered) 11796 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11797 else 11798 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11799 11800 if (DiagID) { 11801 Diag(Loc, DiagID) 11802 << LHSType << RHSType << LHS.get()->getSourceRange() 11803 << RHS.get()->getSourceRange(); 11804 if (isError) 11805 return QualType(); 11806 } 11807 11808 if (LHSType->isIntegerType()) 11809 LHS = ImpCastExprToType(LHS.get(), RHSType, 11810 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11811 else 11812 RHS = ImpCastExprToType(RHS.get(), LHSType, 11813 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11814 return computeResultTy(); 11815 } 11816 11817 // Handle block pointers. 11818 if (!IsOrdered && RHSIsNull 11819 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11820 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11821 return computeResultTy(); 11822 } 11823 if (!IsOrdered && LHSIsNull 11824 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11825 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11826 return computeResultTy(); 11827 } 11828 11829 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11830 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11831 return computeResultTy(); 11832 } 11833 11834 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11835 return computeResultTy(); 11836 } 11837 11838 if (LHSIsNull && RHSType->isQueueT()) { 11839 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11840 return computeResultTy(); 11841 } 11842 11843 if (LHSType->isQueueT() && RHSIsNull) { 11844 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11845 return computeResultTy(); 11846 } 11847 } 11848 11849 return InvalidOperands(Loc, LHS, RHS); 11850 } 11851 11852 // Return a signed ext_vector_type that is of identical size and number of 11853 // elements. For floating point vectors, return an integer type of identical 11854 // size and number of elements. In the non ext_vector_type case, search from 11855 // the largest type to the smallest type to avoid cases where long long == long, 11856 // where long gets picked over long long. 11857 QualType Sema::GetSignedVectorType(QualType V) { 11858 const VectorType *VTy = V->castAs<VectorType>(); 11859 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11860 11861 if (isa<ExtVectorType>(VTy)) { 11862 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11863 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11864 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11865 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11866 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11867 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11868 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11869 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11870 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11871 "Unhandled vector element size in vector compare"); 11872 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11873 } 11874 11875 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11876 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11877 VectorType::GenericVector); 11878 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11879 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11880 VectorType::GenericVector); 11881 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11882 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11883 VectorType::GenericVector); 11884 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11885 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11886 VectorType::GenericVector); 11887 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11888 "Unhandled vector element size in vector compare"); 11889 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11890 VectorType::GenericVector); 11891 } 11892 11893 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11894 /// operates on extended vector types. Instead of producing an IntTy result, 11895 /// like a scalar comparison, a vector comparison produces a vector of integer 11896 /// types. 11897 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11898 SourceLocation Loc, 11899 BinaryOperatorKind Opc) { 11900 if (Opc == BO_Cmp) { 11901 Diag(Loc, diag::err_three_way_vector_comparison); 11902 return QualType(); 11903 } 11904 11905 // Check to make sure we're operating on vectors of the same type and width, 11906 // Allowing one side to be a scalar of element type. 11907 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11908 /*AllowBothBool*/true, 11909 /*AllowBoolConversions*/getLangOpts().ZVector); 11910 if (vType.isNull()) 11911 return vType; 11912 11913 QualType LHSType = LHS.get()->getType(); 11914 11915 // If AltiVec, the comparison results in a numeric type, i.e. 11916 // bool for C++, int for C 11917 if (getLangOpts().AltiVec && 11918 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11919 return Context.getLogicalOperationType(); 11920 11921 // For non-floating point types, check for self-comparisons of the form 11922 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11923 // often indicate logic errors in the program. 11924 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11925 11926 // Check for comparisons of floating point operands using != and ==. 11927 if (BinaryOperator::isEqualityOp(Opc) && 11928 LHSType->hasFloatingRepresentation()) { 11929 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11930 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11931 } 11932 11933 // Return a signed type for the vector. 11934 return GetSignedVectorType(vType); 11935 } 11936 11937 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11938 const ExprResult &XorRHS, 11939 const SourceLocation Loc) { 11940 // Do not diagnose macros. 11941 if (Loc.isMacroID()) 11942 return; 11943 11944 bool Negative = false; 11945 bool ExplicitPlus = false; 11946 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11947 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11948 11949 if (!LHSInt) 11950 return; 11951 if (!RHSInt) { 11952 // Check negative literals. 11953 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11954 UnaryOperatorKind Opc = UO->getOpcode(); 11955 if (Opc != UO_Minus && Opc != UO_Plus) 11956 return; 11957 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11958 if (!RHSInt) 11959 return; 11960 Negative = (Opc == UO_Minus); 11961 ExplicitPlus = !Negative; 11962 } else { 11963 return; 11964 } 11965 } 11966 11967 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11968 llvm::APInt RightSideValue = RHSInt->getValue(); 11969 if (LeftSideValue != 2 && LeftSideValue != 10) 11970 return; 11971 11972 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11973 return; 11974 11975 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11976 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11977 llvm::StringRef ExprStr = 11978 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11979 11980 CharSourceRange XorRange = 11981 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11982 llvm::StringRef XorStr = 11983 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11984 // Do not diagnose if xor keyword/macro is used. 11985 if (XorStr == "xor") 11986 return; 11987 11988 std::string LHSStr = std::string(Lexer::getSourceText( 11989 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11990 S.getSourceManager(), S.getLangOpts())); 11991 std::string RHSStr = std::string(Lexer::getSourceText( 11992 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11993 S.getSourceManager(), S.getLangOpts())); 11994 11995 if (Negative) { 11996 RightSideValue = -RightSideValue; 11997 RHSStr = "-" + RHSStr; 11998 } else if (ExplicitPlus) { 11999 RHSStr = "+" + RHSStr; 12000 } 12001 12002 StringRef LHSStrRef = LHSStr; 12003 StringRef RHSStrRef = RHSStr; 12004 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12005 // literals. 12006 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12007 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12008 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12009 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12010 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12011 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12012 LHSStrRef.find('\'') != StringRef::npos || 12013 RHSStrRef.find('\'') != StringRef::npos) 12014 return; 12015 12016 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12017 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12018 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12019 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12020 std::string SuggestedExpr = "1 << " + RHSStr; 12021 bool Overflow = false; 12022 llvm::APInt One = (LeftSideValue - 1); 12023 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12024 if (Overflow) { 12025 if (RightSideIntValue < 64) 12026 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12027 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12028 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12029 else if (RightSideIntValue == 64) 12030 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12031 else 12032 return; 12033 } else { 12034 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12035 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12036 << PowValue.toString(10, true) 12037 << FixItHint::CreateReplacement( 12038 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12039 } 12040 12041 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12042 } else if (LeftSideValue == 10) { 12043 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12044 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12045 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12046 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12047 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12048 } 12049 } 12050 12051 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12052 SourceLocation Loc) { 12053 // Ensure that either both operands are of the same vector type, or 12054 // one operand is of a vector type and the other is of its element type. 12055 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12056 /*AllowBothBool*/true, 12057 /*AllowBoolConversions*/false); 12058 if (vType.isNull()) 12059 return InvalidOperands(Loc, LHS, RHS); 12060 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12061 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12062 return InvalidOperands(Loc, LHS, RHS); 12063 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12064 // usage of the logical operators && and || with vectors in C. This 12065 // check could be notionally dropped. 12066 if (!getLangOpts().CPlusPlus && 12067 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12068 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12069 12070 return GetSignedVectorType(LHS.get()->getType()); 12071 } 12072 12073 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12074 SourceLocation Loc, 12075 bool IsCompAssign) { 12076 if (!IsCompAssign) { 12077 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12078 if (LHS.isInvalid()) 12079 return QualType(); 12080 } 12081 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12082 if (RHS.isInvalid()) 12083 return QualType(); 12084 12085 // For conversion purposes, we ignore any qualifiers. 12086 // For example, "const float" and "float" are equivalent. 12087 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12088 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12089 12090 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12091 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12092 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12093 12094 if (Context.hasSameType(LHSType, RHSType)) 12095 return LHSType; 12096 12097 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12098 // case we have to return InvalidOperands. 12099 ExprResult OriginalLHS = LHS; 12100 ExprResult OriginalRHS = RHS; 12101 if (LHSMatType && !RHSMatType) { 12102 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12103 if (!RHS.isInvalid()) 12104 return LHSType; 12105 12106 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12107 } 12108 12109 if (!LHSMatType && RHSMatType) { 12110 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12111 if (!LHS.isInvalid()) 12112 return RHSType; 12113 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12114 } 12115 12116 return InvalidOperands(Loc, LHS, RHS); 12117 } 12118 12119 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12120 SourceLocation Loc, 12121 bool IsCompAssign) { 12122 if (!IsCompAssign) { 12123 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12124 if (LHS.isInvalid()) 12125 return QualType(); 12126 } 12127 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12128 if (RHS.isInvalid()) 12129 return QualType(); 12130 12131 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12132 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12133 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12134 12135 if (LHSMatType && RHSMatType) { 12136 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12137 return InvalidOperands(Loc, LHS, RHS); 12138 12139 if (!Context.hasSameType(LHSMatType->getElementType(), 12140 RHSMatType->getElementType())) 12141 return InvalidOperands(Loc, LHS, RHS); 12142 12143 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12144 LHSMatType->getNumRows(), 12145 RHSMatType->getNumColumns()); 12146 } 12147 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12148 } 12149 12150 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12151 SourceLocation Loc, 12152 BinaryOperatorKind Opc) { 12153 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12154 12155 bool IsCompAssign = 12156 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12157 12158 if (LHS.get()->getType()->isVectorType() || 12159 RHS.get()->getType()->isVectorType()) { 12160 if (LHS.get()->getType()->hasIntegerRepresentation() && 12161 RHS.get()->getType()->hasIntegerRepresentation()) 12162 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12163 /*AllowBothBool*/true, 12164 /*AllowBoolConversions*/getLangOpts().ZVector); 12165 return InvalidOperands(Loc, LHS, RHS); 12166 } 12167 12168 if (Opc == BO_And) 12169 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12170 12171 if (LHS.get()->getType()->hasFloatingRepresentation() || 12172 RHS.get()->getType()->hasFloatingRepresentation()) 12173 return InvalidOperands(Loc, LHS, RHS); 12174 12175 ExprResult LHSResult = LHS, RHSResult = RHS; 12176 QualType compType = UsualArithmeticConversions( 12177 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12178 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12179 return QualType(); 12180 LHS = LHSResult.get(); 12181 RHS = RHSResult.get(); 12182 12183 if (Opc == BO_Xor) 12184 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12185 12186 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12187 return compType; 12188 return InvalidOperands(Loc, LHS, RHS); 12189 } 12190 12191 // C99 6.5.[13,14] 12192 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12193 SourceLocation Loc, 12194 BinaryOperatorKind Opc) { 12195 // Check vector operands differently. 12196 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12197 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12198 12199 bool EnumConstantInBoolContext = false; 12200 for (const ExprResult &HS : {LHS, RHS}) { 12201 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12202 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12203 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12204 EnumConstantInBoolContext = true; 12205 } 12206 } 12207 12208 if (EnumConstantInBoolContext) 12209 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12210 12211 // Diagnose cases where the user write a logical and/or but probably meant a 12212 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12213 // is a constant. 12214 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12215 !LHS.get()->getType()->isBooleanType() && 12216 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12217 // Don't warn in macros or template instantiations. 12218 !Loc.isMacroID() && !inTemplateInstantiation()) { 12219 // If the RHS can be constant folded, and if it constant folds to something 12220 // that isn't 0 or 1 (which indicate a potential logical operation that 12221 // happened to fold to true/false) then warn. 12222 // Parens on the RHS are ignored. 12223 Expr::EvalResult EVResult; 12224 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12225 llvm::APSInt Result = EVResult.Val.getInt(); 12226 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12227 !RHS.get()->getExprLoc().isMacroID()) || 12228 (Result != 0 && Result != 1)) { 12229 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12230 << RHS.get()->getSourceRange() 12231 << (Opc == BO_LAnd ? "&&" : "||"); 12232 // Suggest replacing the logical operator with the bitwise version 12233 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12234 << (Opc == BO_LAnd ? "&" : "|") 12235 << FixItHint::CreateReplacement(SourceRange( 12236 Loc, getLocForEndOfToken(Loc)), 12237 Opc == BO_LAnd ? "&" : "|"); 12238 if (Opc == BO_LAnd) 12239 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12240 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12241 << FixItHint::CreateRemoval( 12242 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12243 RHS.get()->getEndLoc())); 12244 } 12245 } 12246 } 12247 12248 if (!Context.getLangOpts().CPlusPlus) { 12249 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12250 // not operate on the built-in scalar and vector float types. 12251 if (Context.getLangOpts().OpenCL && 12252 Context.getLangOpts().OpenCLVersion < 120) { 12253 if (LHS.get()->getType()->isFloatingType() || 12254 RHS.get()->getType()->isFloatingType()) 12255 return InvalidOperands(Loc, LHS, RHS); 12256 } 12257 12258 LHS = UsualUnaryConversions(LHS.get()); 12259 if (LHS.isInvalid()) 12260 return QualType(); 12261 12262 RHS = UsualUnaryConversions(RHS.get()); 12263 if (RHS.isInvalid()) 12264 return QualType(); 12265 12266 if (!LHS.get()->getType()->isScalarType() || 12267 !RHS.get()->getType()->isScalarType()) 12268 return InvalidOperands(Loc, LHS, RHS); 12269 12270 return Context.IntTy; 12271 } 12272 12273 // The following is safe because we only use this method for 12274 // non-overloadable operands. 12275 12276 // C++ [expr.log.and]p1 12277 // C++ [expr.log.or]p1 12278 // The operands are both contextually converted to type bool. 12279 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12280 if (LHSRes.isInvalid()) 12281 return InvalidOperands(Loc, LHS, RHS); 12282 LHS = LHSRes; 12283 12284 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12285 if (RHSRes.isInvalid()) 12286 return InvalidOperands(Loc, LHS, RHS); 12287 RHS = RHSRes; 12288 12289 // C++ [expr.log.and]p2 12290 // C++ [expr.log.or]p2 12291 // The result is a bool. 12292 return Context.BoolTy; 12293 } 12294 12295 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12296 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12297 if (!ME) return false; 12298 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12299 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12300 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12301 if (!Base) return false; 12302 return Base->getMethodDecl() != nullptr; 12303 } 12304 12305 /// Is the given expression (which must be 'const') a reference to a 12306 /// variable which was originally non-const, but which has become 12307 /// 'const' due to being captured within a block? 12308 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12309 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12310 assert(E->isLValue() && E->getType().isConstQualified()); 12311 E = E->IgnoreParens(); 12312 12313 // Must be a reference to a declaration from an enclosing scope. 12314 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12315 if (!DRE) return NCCK_None; 12316 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12317 12318 // The declaration must be a variable which is not declared 'const'. 12319 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12320 if (!var) return NCCK_None; 12321 if (var->getType().isConstQualified()) return NCCK_None; 12322 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12323 12324 // Decide whether the first capture was for a block or a lambda. 12325 DeclContext *DC = S.CurContext, *Prev = nullptr; 12326 // Decide whether the first capture was for a block or a lambda. 12327 while (DC) { 12328 // For init-capture, it is possible that the variable belongs to the 12329 // template pattern of the current context. 12330 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12331 if (var->isInitCapture() && 12332 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12333 break; 12334 if (DC == var->getDeclContext()) 12335 break; 12336 Prev = DC; 12337 DC = DC->getParent(); 12338 } 12339 // Unless we have an init-capture, we've gone one step too far. 12340 if (!var->isInitCapture()) 12341 DC = Prev; 12342 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12343 } 12344 12345 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12346 Ty = Ty.getNonReferenceType(); 12347 if (IsDereference && Ty->isPointerType()) 12348 Ty = Ty->getPointeeType(); 12349 return !Ty.isConstQualified(); 12350 } 12351 12352 // Update err_typecheck_assign_const and note_typecheck_assign_const 12353 // when this enum is changed. 12354 enum { 12355 ConstFunction, 12356 ConstVariable, 12357 ConstMember, 12358 ConstMethod, 12359 NestedConstMember, 12360 ConstUnknown, // Keep as last element 12361 }; 12362 12363 /// Emit the "read-only variable not assignable" error and print notes to give 12364 /// more information about why the variable is not assignable, such as pointing 12365 /// to the declaration of a const variable, showing that a method is const, or 12366 /// that the function is returning a const reference. 12367 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12368 SourceLocation Loc) { 12369 SourceRange ExprRange = E->getSourceRange(); 12370 12371 // Only emit one error on the first const found. All other consts will emit 12372 // a note to the error. 12373 bool DiagnosticEmitted = false; 12374 12375 // Track if the current expression is the result of a dereference, and if the 12376 // next checked expression is the result of a dereference. 12377 bool IsDereference = false; 12378 bool NextIsDereference = false; 12379 12380 // Loop to process MemberExpr chains. 12381 while (true) { 12382 IsDereference = NextIsDereference; 12383 12384 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12385 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12386 NextIsDereference = ME->isArrow(); 12387 const ValueDecl *VD = ME->getMemberDecl(); 12388 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12389 // Mutable fields can be modified even if the class is const. 12390 if (Field->isMutable()) { 12391 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12392 break; 12393 } 12394 12395 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12396 if (!DiagnosticEmitted) { 12397 S.Diag(Loc, diag::err_typecheck_assign_const) 12398 << ExprRange << ConstMember << false /*static*/ << Field 12399 << Field->getType(); 12400 DiagnosticEmitted = true; 12401 } 12402 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12403 << ConstMember << false /*static*/ << Field << Field->getType() 12404 << Field->getSourceRange(); 12405 } 12406 E = ME->getBase(); 12407 continue; 12408 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12409 if (VDecl->getType().isConstQualified()) { 12410 if (!DiagnosticEmitted) { 12411 S.Diag(Loc, diag::err_typecheck_assign_const) 12412 << ExprRange << ConstMember << true /*static*/ << VDecl 12413 << VDecl->getType(); 12414 DiagnosticEmitted = true; 12415 } 12416 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12417 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12418 << VDecl->getSourceRange(); 12419 } 12420 // Static fields do not inherit constness from parents. 12421 break; 12422 } 12423 break; // End MemberExpr 12424 } else if (const ArraySubscriptExpr *ASE = 12425 dyn_cast<ArraySubscriptExpr>(E)) { 12426 E = ASE->getBase()->IgnoreParenImpCasts(); 12427 continue; 12428 } else if (const ExtVectorElementExpr *EVE = 12429 dyn_cast<ExtVectorElementExpr>(E)) { 12430 E = EVE->getBase()->IgnoreParenImpCasts(); 12431 continue; 12432 } 12433 break; 12434 } 12435 12436 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12437 // Function calls 12438 const FunctionDecl *FD = CE->getDirectCallee(); 12439 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12440 if (!DiagnosticEmitted) { 12441 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12442 << ConstFunction << FD; 12443 DiagnosticEmitted = true; 12444 } 12445 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12446 diag::note_typecheck_assign_const) 12447 << ConstFunction << FD << FD->getReturnType() 12448 << FD->getReturnTypeSourceRange(); 12449 } 12450 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12451 // Point to variable declaration. 12452 if (const ValueDecl *VD = DRE->getDecl()) { 12453 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12454 if (!DiagnosticEmitted) { 12455 S.Diag(Loc, diag::err_typecheck_assign_const) 12456 << ExprRange << ConstVariable << VD << VD->getType(); 12457 DiagnosticEmitted = true; 12458 } 12459 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12460 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12461 } 12462 } 12463 } else if (isa<CXXThisExpr>(E)) { 12464 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12465 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12466 if (MD->isConst()) { 12467 if (!DiagnosticEmitted) { 12468 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12469 << ConstMethod << MD; 12470 DiagnosticEmitted = true; 12471 } 12472 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12473 << ConstMethod << MD << MD->getSourceRange(); 12474 } 12475 } 12476 } 12477 } 12478 12479 if (DiagnosticEmitted) 12480 return; 12481 12482 // Can't determine a more specific message, so display the generic error. 12483 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12484 } 12485 12486 enum OriginalExprKind { 12487 OEK_Variable, 12488 OEK_Member, 12489 OEK_LValue 12490 }; 12491 12492 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12493 const RecordType *Ty, 12494 SourceLocation Loc, SourceRange Range, 12495 OriginalExprKind OEK, 12496 bool &DiagnosticEmitted) { 12497 std::vector<const RecordType *> RecordTypeList; 12498 RecordTypeList.push_back(Ty); 12499 unsigned NextToCheckIndex = 0; 12500 // We walk the record hierarchy breadth-first to ensure that we print 12501 // diagnostics in field nesting order. 12502 while (RecordTypeList.size() > NextToCheckIndex) { 12503 bool IsNested = NextToCheckIndex > 0; 12504 for (const FieldDecl *Field : 12505 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12506 // First, check every field for constness. 12507 QualType FieldTy = Field->getType(); 12508 if (FieldTy.isConstQualified()) { 12509 if (!DiagnosticEmitted) { 12510 S.Diag(Loc, diag::err_typecheck_assign_const) 12511 << Range << NestedConstMember << OEK << VD 12512 << IsNested << Field; 12513 DiagnosticEmitted = true; 12514 } 12515 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12516 << NestedConstMember << IsNested << Field 12517 << FieldTy << Field->getSourceRange(); 12518 } 12519 12520 // Then we append it to the list to check next in order. 12521 FieldTy = FieldTy.getCanonicalType(); 12522 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12523 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12524 RecordTypeList.push_back(FieldRecTy); 12525 } 12526 } 12527 ++NextToCheckIndex; 12528 } 12529 } 12530 12531 /// Emit an error for the case where a record we are trying to assign to has a 12532 /// const-qualified field somewhere in its hierarchy. 12533 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12534 SourceLocation Loc) { 12535 QualType Ty = E->getType(); 12536 assert(Ty->isRecordType() && "lvalue was not record?"); 12537 SourceRange Range = E->getSourceRange(); 12538 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12539 bool DiagEmitted = false; 12540 12541 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12542 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12543 Range, OEK_Member, DiagEmitted); 12544 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12545 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12546 Range, OEK_Variable, DiagEmitted); 12547 else 12548 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12549 Range, OEK_LValue, DiagEmitted); 12550 if (!DiagEmitted) 12551 DiagnoseConstAssignment(S, E, Loc); 12552 } 12553 12554 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12555 /// emit an error and return true. If so, return false. 12556 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12557 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12558 12559 S.CheckShadowingDeclModification(E, Loc); 12560 12561 SourceLocation OrigLoc = Loc; 12562 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12563 &Loc); 12564 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12565 IsLV = Expr::MLV_InvalidMessageExpression; 12566 if (IsLV == Expr::MLV_Valid) 12567 return false; 12568 12569 unsigned DiagID = 0; 12570 bool NeedType = false; 12571 switch (IsLV) { // C99 6.5.16p2 12572 case Expr::MLV_ConstQualified: 12573 // Use a specialized diagnostic when we're assigning to an object 12574 // from an enclosing function or block. 12575 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12576 if (NCCK == NCCK_Block) 12577 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12578 else 12579 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12580 break; 12581 } 12582 12583 // In ARC, use some specialized diagnostics for occasions where we 12584 // infer 'const'. These are always pseudo-strong variables. 12585 if (S.getLangOpts().ObjCAutoRefCount) { 12586 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12587 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12588 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12589 12590 // Use the normal diagnostic if it's pseudo-__strong but the 12591 // user actually wrote 'const'. 12592 if (var->isARCPseudoStrong() && 12593 (!var->getTypeSourceInfo() || 12594 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12595 // There are three pseudo-strong cases: 12596 // - self 12597 ObjCMethodDecl *method = S.getCurMethodDecl(); 12598 if (method && var == method->getSelfDecl()) { 12599 DiagID = method->isClassMethod() 12600 ? diag::err_typecheck_arc_assign_self_class_method 12601 : diag::err_typecheck_arc_assign_self; 12602 12603 // - Objective-C externally_retained attribute. 12604 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12605 isa<ParmVarDecl>(var)) { 12606 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12607 12608 // - fast enumeration variables 12609 } else { 12610 DiagID = diag::err_typecheck_arr_assign_enumeration; 12611 } 12612 12613 SourceRange Assign; 12614 if (Loc != OrigLoc) 12615 Assign = SourceRange(OrigLoc, OrigLoc); 12616 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12617 // We need to preserve the AST regardless, so migration tool 12618 // can do its job. 12619 return false; 12620 } 12621 } 12622 } 12623 12624 // If none of the special cases above are triggered, then this is a 12625 // simple const assignment. 12626 if (DiagID == 0) { 12627 DiagnoseConstAssignment(S, E, Loc); 12628 return true; 12629 } 12630 12631 break; 12632 case Expr::MLV_ConstAddrSpace: 12633 DiagnoseConstAssignment(S, E, Loc); 12634 return true; 12635 case Expr::MLV_ConstQualifiedField: 12636 DiagnoseRecursiveConstFields(S, E, Loc); 12637 return true; 12638 case Expr::MLV_ArrayType: 12639 case Expr::MLV_ArrayTemporary: 12640 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12641 NeedType = true; 12642 break; 12643 case Expr::MLV_NotObjectType: 12644 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12645 NeedType = true; 12646 break; 12647 case Expr::MLV_LValueCast: 12648 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12649 break; 12650 case Expr::MLV_Valid: 12651 llvm_unreachable("did not take early return for MLV_Valid"); 12652 case Expr::MLV_InvalidExpression: 12653 case Expr::MLV_MemberFunction: 12654 case Expr::MLV_ClassTemporary: 12655 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12656 break; 12657 case Expr::MLV_IncompleteType: 12658 case Expr::MLV_IncompleteVoidType: 12659 return S.RequireCompleteType(Loc, E->getType(), 12660 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12661 case Expr::MLV_DuplicateVectorComponents: 12662 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12663 break; 12664 case Expr::MLV_NoSetterProperty: 12665 llvm_unreachable("readonly properties should be processed differently"); 12666 case Expr::MLV_InvalidMessageExpression: 12667 DiagID = diag::err_readonly_message_assignment; 12668 break; 12669 case Expr::MLV_SubObjCPropertySetting: 12670 DiagID = diag::err_no_subobject_property_setting; 12671 break; 12672 } 12673 12674 SourceRange Assign; 12675 if (Loc != OrigLoc) 12676 Assign = SourceRange(OrigLoc, OrigLoc); 12677 if (NeedType) 12678 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12679 else 12680 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12681 return true; 12682 } 12683 12684 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12685 SourceLocation Loc, 12686 Sema &Sema) { 12687 if (Sema.inTemplateInstantiation()) 12688 return; 12689 if (Sema.isUnevaluatedContext()) 12690 return; 12691 if (Loc.isInvalid() || Loc.isMacroID()) 12692 return; 12693 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12694 return; 12695 12696 // C / C++ fields 12697 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12698 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12699 if (ML && MR) { 12700 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12701 return; 12702 const ValueDecl *LHSDecl = 12703 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12704 const ValueDecl *RHSDecl = 12705 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12706 if (LHSDecl != RHSDecl) 12707 return; 12708 if (LHSDecl->getType().isVolatileQualified()) 12709 return; 12710 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12711 if (RefTy->getPointeeType().isVolatileQualified()) 12712 return; 12713 12714 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12715 } 12716 12717 // Objective-C instance variables 12718 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12719 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12720 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12721 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12722 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12723 if (RL && RR && RL->getDecl() == RR->getDecl()) 12724 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12725 } 12726 } 12727 12728 // C99 6.5.16.1 12729 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12730 SourceLocation Loc, 12731 QualType CompoundType) { 12732 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12733 12734 // Verify that LHS is a modifiable lvalue, and emit error if not. 12735 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12736 return QualType(); 12737 12738 QualType LHSType = LHSExpr->getType(); 12739 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12740 CompoundType; 12741 // OpenCL v1.2 s6.1.1.1 p2: 12742 // The half data type can only be used to declare a pointer to a buffer that 12743 // contains half values 12744 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12745 LHSType->isHalfType()) { 12746 Diag(Loc, diag::err_opencl_half_load_store) << 1 12747 << LHSType.getUnqualifiedType(); 12748 return QualType(); 12749 } 12750 12751 AssignConvertType ConvTy; 12752 if (CompoundType.isNull()) { 12753 Expr *RHSCheck = RHS.get(); 12754 12755 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12756 12757 QualType LHSTy(LHSType); 12758 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12759 if (RHS.isInvalid()) 12760 return QualType(); 12761 // Special case of NSObject attributes on c-style pointer types. 12762 if (ConvTy == IncompatiblePointer && 12763 ((Context.isObjCNSObjectType(LHSType) && 12764 RHSType->isObjCObjectPointerType()) || 12765 (Context.isObjCNSObjectType(RHSType) && 12766 LHSType->isObjCObjectPointerType()))) 12767 ConvTy = Compatible; 12768 12769 if (ConvTy == Compatible && 12770 LHSType->isObjCObjectType()) 12771 Diag(Loc, diag::err_objc_object_assignment) 12772 << LHSType; 12773 12774 // If the RHS is a unary plus or minus, check to see if they = and + are 12775 // right next to each other. If so, the user may have typo'd "x =+ 4" 12776 // instead of "x += 4". 12777 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12778 RHSCheck = ICE->getSubExpr(); 12779 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12780 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12781 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12782 // Only if the two operators are exactly adjacent. 12783 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12784 // And there is a space or other character before the subexpr of the 12785 // unary +/-. We don't want to warn on "x=-1". 12786 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12787 UO->getSubExpr()->getBeginLoc().isFileID()) { 12788 Diag(Loc, diag::warn_not_compound_assign) 12789 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12790 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12791 } 12792 } 12793 12794 if (ConvTy == Compatible) { 12795 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12796 // Warn about retain cycles where a block captures the LHS, but 12797 // not if the LHS is a simple variable into which the block is 12798 // being stored...unless that variable can be captured by reference! 12799 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12800 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12801 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12802 checkRetainCycles(LHSExpr, RHS.get()); 12803 } 12804 12805 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12806 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12807 // It is safe to assign a weak reference into a strong variable. 12808 // Although this code can still have problems: 12809 // id x = self.weakProp; 12810 // id y = self.weakProp; 12811 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12812 // paths through the function. This should be revisited if 12813 // -Wrepeated-use-of-weak is made flow-sensitive. 12814 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12815 // variable, which will be valid for the current autorelease scope. 12816 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12817 RHS.get()->getBeginLoc())) 12818 getCurFunction()->markSafeWeakUse(RHS.get()); 12819 12820 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12821 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12822 } 12823 } 12824 } else { 12825 // Compound assignment "x += y" 12826 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12827 } 12828 12829 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12830 RHS.get(), AA_Assigning)) 12831 return QualType(); 12832 12833 CheckForNullPointerDereference(*this, LHSExpr); 12834 12835 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12836 if (CompoundType.isNull()) { 12837 // C++2a [expr.ass]p5: 12838 // A simple-assignment whose left operand is of a volatile-qualified 12839 // type is deprecated unless the assignment is either a discarded-value 12840 // expression or an unevaluated operand 12841 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12842 } else { 12843 // C++2a [expr.ass]p6: 12844 // [Compound-assignment] expressions are deprecated if E1 has 12845 // volatile-qualified type 12846 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12847 } 12848 } 12849 12850 // C99 6.5.16p3: The type of an assignment expression is the type of the 12851 // left operand unless the left operand has qualified type, in which case 12852 // it is the unqualified version of the type of the left operand. 12853 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12854 // is converted to the type of the assignment expression (above). 12855 // C++ 5.17p1: the type of the assignment expression is that of its left 12856 // operand. 12857 return (getLangOpts().CPlusPlus 12858 ? LHSType : LHSType.getUnqualifiedType()); 12859 } 12860 12861 // Only ignore explicit casts to void. 12862 static bool IgnoreCommaOperand(const Expr *E) { 12863 E = E->IgnoreParens(); 12864 12865 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12866 if (CE->getCastKind() == CK_ToVoid) { 12867 return true; 12868 } 12869 12870 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12871 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12872 CE->getSubExpr()->getType()->isDependentType()) { 12873 return true; 12874 } 12875 } 12876 12877 return false; 12878 } 12879 12880 // Look for instances where it is likely the comma operator is confused with 12881 // another operator. There is an explicit list of acceptable expressions for 12882 // the left hand side of the comma operator, otherwise emit a warning. 12883 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12884 // No warnings in macros 12885 if (Loc.isMacroID()) 12886 return; 12887 12888 // Don't warn in template instantiations. 12889 if (inTemplateInstantiation()) 12890 return; 12891 12892 // Scope isn't fine-grained enough to explicitly list the specific cases, so 12893 // instead, skip more than needed, then call back into here with the 12894 // CommaVisitor in SemaStmt.cpp. 12895 // The listed locations are the initialization and increment portions 12896 // of a for loop. The additional checks are on the condition of 12897 // if statements, do/while loops, and for loops. 12898 // Differences in scope flags for C89 mode requires the extra logic. 12899 const unsigned ForIncrementFlags = 12900 getLangOpts().C99 || getLangOpts().CPlusPlus 12901 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12902 : Scope::ContinueScope | Scope::BreakScope; 12903 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12904 const unsigned ScopeFlags = getCurScope()->getFlags(); 12905 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12906 (ScopeFlags & ForInitFlags) == ForInitFlags) 12907 return; 12908 12909 // If there are multiple comma operators used together, get the RHS of the 12910 // of the comma operator as the LHS. 12911 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12912 if (BO->getOpcode() != BO_Comma) 12913 break; 12914 LHS = BO->getRHS(); 12915 } 12916 12917 // Only allow some expressions on LHS to not warn. 12918 if (IgnoreCommaOperand(LHS)) 12919 return; 12920 12921 Diag(Loc, diag::warn_comma_operator); 12922 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12923 << LHS->getSourceRange() 12924 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12925 LangOpts.CPlusPlus ? "static_cast<void>(" 12926 : "(void)(") 12927 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12928 ")"); 12929 } 12930 12931 // C99 6.5.17 12932 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12933 SourceLocation Loc) { 12934 LHS = S.CheckPlaceholderExpr(LHS.get()); 12935 RHS = S.CheckPlaceholderExpr(RHS.get()); 12936 if (LHS.isInvalid() || RHS.isInvalid()) 12937 return QualType(); 12938 12939 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12940 // operands, but not unary promotions. 12941 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12942 12943 // So we treat the LHS as a ignored value, and in C++ we allow the 12944 // containing site to determine what should be done with the RHS. 12945 LHS = S.IgnoredValueConversions(LHS.get()); 12946 if (LHS.isInvalid()) 12947 return QualType(); 12948 12949 S.DiagnoseUnusedExprResult(LHS.get()); 12950 12951 if (!S.getLangOpts().CPlusPlus) { 12952 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12953 if (RHS.isInvalid()) 12954 return QualType(); 12955 if (!RHS.get()->getType()->isVoidType()) 12956 S.RequireCompleteType(Loc, RHS.get()->getType(), 12957 diag::err_incomplete_type); 12958 } 12959 12960 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12961 S.DiagnoseCommaOperator(LHS.get(), Loc); 12962 12963 return RHS.get()->getType(); 12964 } 12965 12966 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12967 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12968 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12969 ExprValueKind &VK, 12970 ExprObjectKind &OK, 12971 SourceLocation OpLoc, 12972 bool IsInc, bool IsPrefix) { 12973 if (Op->isTypeDependent()) 12974 return S.Context.DependentTy; 12975 12976 QualType ResType = Op->getType(); 12977 // Atomic types can be used for increment / decrement where the non-atomic 12978 // versions can, so ignore the _Atomic() specifier for the purpose of 12979 // checking. 12980 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12981 ResType = ResAtomicType->getValueType(); 12982 12983 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12984 12985 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12986 // Decrement of bool is not allowed. 12987 if (!IsInc) { 12988 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12989 return QualType(); 12990 } 12991 // Increment of bool sets it to true, but is deprecated. 12992 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12993 : diag::warn_increment_bool) 12994 << Op->getSourceRange(); 12995 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12996 // Error on enum increments and decrements in C++ mode 12997 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12998 return QualType(); 12999 } else if (ResType->isRealType()) { 13000 // OK! 13001 } else if (ResType->isPointerType()) { 13002 // C99 6.5.2.4p2, 6.5.6p2 13003 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13004 return QualType(); 13005 } else if (ResType->isObjCObjectPointerType()) { 13006 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13007 // Otherwise, we just need a complete type. 13008 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13009 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13010 return QualType(); 13011 } else if (ResType->isAnyComplexType()) { 13012 // C99 does not support ++/-- on complex types, we allow as an extension. 13013 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13014 << ResType << Op->getSourceRange(); 13015 } else if (ResType->isPlaceholderType()) { 13016 ExprResult PR = S.CheckPlaceholderExpr(Op); 13017 if (PR.isInvalid()) return QualType(); 13018 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13019 IsInc, IsPrefix); 13020 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13021 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13022 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13023 (ResType->castAs<VectorType>()->getVectorKind() != 13024 VectorType::AltiVecBool)) { 13025 // The z vector extensions allow ++ and -- for non-bool vectors. 13026 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13027 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13028 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13029 } else { 13030 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13031 << ResType << int(IsInc) << Op->getSourceRange(); 13032 return QualType(); 13033 } 13034 // At this point, we know we have a real, complex or pointer type. 13035 // Now make sure the operand is a modifiable lvalue. 13036 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13037 return QualType(); 13038 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13039 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13040 // An operand with volatile-qualified type is deprecated 13041 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13042 << IsInc << ResType; 13043 } 13044 // In C++, a prefix increment is the same type as the operand. Otherwise 13045 // (in C or with postfix), the increment is the unqualified type of the 13046 // operand. 13047 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13048 VK = VK_LValue; 13049 OK = Op->getObjectKind(); 13050 return ResType; 13051 } else { 13052 VK = VK_RValue; 13053 return ResType.getUnqualifiedType(); 13054 } 13055 } 13056 13057 13058 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13059 /// This routine allows us to typecheck complex/recursive expressions 13060 /// where the declaration is needed for type checking. We only need to 13061 /// handle cases when the expression references a function designator 13062 /// or is an lvalue. Here are some examples: 13063 /// - &(x) => x 13064 /// - &*****f => f for f a function designator. 13065 /// - &s.xx => s 13066 /// - &s.zz[1].yy -> s, if zz is an array 13067 /// - *(x + 1) -> x, if x is an array 13068 /// - &"123"[2] -> 0 13069 /// - & __real__ x -> x 13070 /// 13071 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13072 /// members. 13073 static ValueDecl *getPrimaryDecl(Expr *E) { 13074 switch (E->getStmtClass()) { 13075 case Stmt::DeclRefExprClass: 13076 return cast<DeclRefExpr>(E)->getDecl(); 13077 case Stmt::MemberExprClass: 13078 // If this is an arrow operator, the address is an offset from 13079 // the base's value, so the object the base refers to is 13080 // irrelevant. 13081 if (cast<MemberExpr>(E)->isArrow()) 13082 return nullptr; 13083 // Otherwise, the expression refers to a part of the base 13084 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13085 case Stmt::ArraySubscriptExprClass: { 13086 // FIXME: This code shouldn't be necessary! We should catch the implicit 13087 // promotion of register arrays earlier. 13088 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13089 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13090 if (ICE->getSubExpr()->getType()->isArrayType()) 13091 return getPrimaryDecl(ICE->getSubExpr()); 13092 } 13093 return nullptr; 13094 } 13095 case Stmt::UnaryOperatorClass: { 13096 UnaryOperator *UO = cast<UnaryOperator>(E); 13097 13098 switch(UO->getOpcode()) { 13099 case UO_Real: 13100 case UO_Imag: 13101 case UO_Extension: 13102 return getPrimaryDecl(UO->getSubExpr()); 13103 default: 13104 return nullptr; 13105 } 13106 } 13107 case Stmt::ParenExprClass: 13108 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13109 case Stmt::ImplicitCastExprClass: 13110 // If the result of an implicit cast is an l-value, we care about 13111 // the sub-expression; otherwise, the result here doesn't matter. 13112 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13113 case Stmt::CXXUuidofExprClass: 13114 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13115 default: 13116 return nullptr; 13117 } 13118 } 13119 13120 namespace { 13121 enum { 13122 AO_Bit_Field = 0, 13123 AO_Vector_Element = 1, 13124 AO_Property_Expansion = 2, 13125 AO_Register_Variable = 3, 13126 AO_Matrix_Element = 4, 13127 AO_No_Error = 5 13128 }; 13129 } 13130 /// Diagnose invalid operand for address of operations. 13131 /// 13132 /// \param Type The type of operand which cannot have its address taken. 13133 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13134 Expr *E, unsigned Type) { 13135 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13136 } 13137 13138 /// CheckAddressOfOperand - The operand of & must be either a function 13139 /// designator or an lvalue designating an object. If it is an lvalue, the 13140 /// object cannot be declared with storage class register or be a bit field. 13141 /// Note: The usual conversions are *not* applied to the operand of the & 13142 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13143 /// In C++, the operand might be an overloaded function name, in which case 13144 /// we allow the '&' but retain the overloaded-function type. 13145 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13146 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13147 if (PTy->getKind() == BuiltinType::Overload) { 13148 Expr *E = OrigOp.get()->IgnoreParens(); 13149 if (!isa<OverloadExpr>(E)) { 13150 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13151 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13152 << OrigOp.get()->getSourceRange(); 13153 return QualType(); 13154 } 13155 13156 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13157 if (isa<UnresolvedMemberExpr>(Ovl)) 13158 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13159 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13160 << OrigOp.get()->getSourceRange(); 13161 return QualType(); 13162 } 13163 13164 return Context.OverloadTy; 13165 } 13166 13167 if (PTy->getKind() == BuiltinType::UnknownAny) 13168 return Context.UnknownAnyTy; 13169 13170 if (PTy->getKind() == BuiltinType::BoundMember) { 13171 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13172 << OrigOp.get()->getSourceRange(); 13173 return QualType(); 13174 } 13175 13176 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13177 if (OrigOp.isInvalid()) return QualType(); 13178 } 13179 13180 if (OrigOp.get()->isTypeDependent()) 13181 return Context.DependentTy; 13182 13183 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13184 13185 // Make sure to ignore parentheses in subsequent checks 13186 Expr *op = OrigOp.get()->IgnoreParens(); 13187 13188 // In OpenCL captures for blocks called as lambda functions 13189 // are located in the private address space. Blocks used in 13190 // enqueue_kernel can be located in a different address space 13191 // depending on a vendor implementation. Thus preventing 13192 // taking an address of the capture to avoid invalid AS casts. 13193 if (LangOpts.OpenCL) { 13194 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13195 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13196 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13197 return QualType(); 13198 } 13199 } 13200 13201 if (getLangOpts().C99) { 13202 // Implement C99-only parts of addressof rules. 13203 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13204 if (uOp->getOpcode() == UO_Deref) 13205 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13206 // (assuming the deref expression is valid). 13207 return uOp->getSubExpr()->getType(); 13208 } 13209 // Technically, there should be a check for array subscript 13210 // expressions here, but the result of one is always an lvalue anyway. 13211 } 13212 ValueDecl *dcl = getPrimaryDecl(op); 13213 13214 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13215 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13216 op->getBeginLoc())) 13217 return QualType(); 13218 13219 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13220 unsigned AddressOfError = AO_No_Error; 13221 13222 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13223 bool sfinae = (bool)isSFINAEContext(); 13224 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13225 : diag::ext_typecheck_addrof_temporary) 13226 << op->getType() << op->getSourceRange(); 13227 if (sfinae) 13228 return QualType(); 13229 // Materialize the temporary as an lvalue so that we can take its address. 13230 OrigOp = op = 13231 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13232 } else if (isa<ObjCSelectorExpr>(op)) { 13233 return Context.getPointerType(op->getType()); 13234 } else if (lval == Expr::LV_MemberFunction) { 13235 // If it's an instance method, make a member pointer. 13236 // The expression must have exactly the form &A::foo. 13237 13238 // If the underlying expression isn't a decl ref, give up. 13239 if (!isa<DeclRefExpr>(op)) { 13240 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13241 << OrigOp.get()->getSourceRange(); 13242 return QualType(); 13243 } 13244 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13245 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13246 13247 // The id-expression was parenthesized. 13248 if (OrigOp.get() != DRE) { 13249 Diag(OpLoc, diag::err_parens_pointer_member_function) 13250 << OrigOp.get()->getSourceRange(); 13251 13252 // The method was named without a qualifier. 13253 } else if (!DRE->getQualifier()) { 13254 if (MD->getParent()->getName().empty()) 13255 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13256 << op->getSourceRange(); 13257 else { 13258 SmallString<32> Str; 13259 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13260 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13261 << op->getSourceRange() 13262 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13263 } 13264 } 13265 13266 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13267 if (isa<CXXDestructorDecl>(MD)) 13268 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13269 13270 QualType MPTy = Context.getMemberPointerType( 13271 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13272 // Under the MS ABI, lock down the inheritance model now. 13273 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13274 (void)isCompleteType(OpLoc, MPTy); 13275 return MPTy; 13276 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13277 // C99 6.5.3.2p1 13278 // The operand must be either an l-value or a function designator 13279 if (!op->getType()->isFunctionType()) { 13280 // Use a special diagnostic for loads from property references. 13281 if (isa<PseudoObjectExpr>(op)) { 13282 AddressOfError = AO_Property_Expansion; 13283 } else { 13284 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13285 << op->getType() << op->getSourceRange(); 13286 return QualType(); 13287 } 13288 } 13289 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13290 // The operand cannot be a bit-field 13291 AddressOfError = AO_Bit_Field; 13292 } else if (op->getObjectKind() == OK_VectorComponent) { 13293 // The operand cannot be an element of a vector 13294 AddressOfError = AO_Vector_Element; 13295 } else if (op->getObjectKind() == OK_MatrixComponent) { 13296 // The operand cannot be an element of a matrix. 13297 AddressOfError = AO_Matrix_Element; 13298 } else if (dcl) { // C99 6.5.3.2p1 13299 // We have an lvalue with a decl. Make sure the decl is not declared 13300 // with the register storage-class specifier. 13301 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13302 // in C++ it is not error to take address of a register 13303 // variable (c++03 7.1.1P3) 13304 if (vd->getStorageClass() == SC_Register && 13305 !getLangOpts().CPlusPlus) { 13306 AddressOfError = AO_Register_Variable; 13307 } 13308 } else if (isa<MSPropertyDecl>(dcl)) { 13309 AddressOfError = AO_Property_Expansion; 13310 } else if (isa<FunctionTemplateDecl>(dcl)) { 13311 return Context.OverloadTy; 13312 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13313 // Okay: we can take the address of a field. 13314 // Could be a pointer to member, though, if there is an explicit 13315 // scope qualifier for the class. 13316 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13317 DeclContext *Ctx = dcl->getDeclContext(); 13318 if (Ctx && Ctx->isRecord()) { 13319 if (dcl->getType()->isReferenceType()) { 13320 Diag(OpLoc, 13321 diag::err_cannot_form_pointer_to_member_of_reference_type) 13322 << dcl->getDeclName() << dcl->getType(); 13323 return QualType(); 13324 } 13325 13326 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13327 Ctx = Ctx->getParent(); 13328 13329 QualType MPTy = Context.getMemberPointerType( 13330 op->getType(), 13331 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13332 // Under the MS ABI, lock down the inheritance model now. 13333 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13334 (void)isCompleteType(OpLoc, MPTy); 13335 return MPTy; 13336 } 13337 } 13338 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13339 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13340 llvm_unreachable("Unknown/unexpected decl type"); 13341 } 13342 13343 if (AddressOfError != AO_No_Error) { 13344 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13345 return QualType(); 13346 } 13347 13348 if (lval == Expr::LV_IncompleteVoidType) { 13349 // Taking the address of a void variable is technically illegal, but we 13350 // allow it in cases which are otherwise valid. 13351 // Example: "extern void x; void* y = &x;". 13352 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13353 } 13354 13355 // If the operand has type "type", the result has type "pointer to type". 13356 if (op->getType()->isObjCObjectType()) 13357 return Context.getObjCObjectPointerType(op->getType()); 13358 13359 CheckAddressOfPackedMember(op); 13360 13361 return Context.getPointerType(op->getType()); 13362 } 13363 13364 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13365 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13366 if (!DRE) 13367 return; 13368 const Decl *D = DRE->getDecl(); 13369 if (!D) 13370 return; 13371 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13372 if (!Param) 13373 return; 13374 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13375 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13376 return; 13377 if (FunctionScopeInfo *FD = S.getCurFunction()) 13378 if (!FD->ModifiedNonNullParams.count(Param)) 13379 FD->ModifiedNonNullParams.insert(Param); 13380 } 13381 13382 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13383 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13384 SourceLocation OpLoc) { 13385 if (Op->isTypeDependent()) 13386 return S.Context.DependentTy; 13387 13388 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13389 if (ConvResult.isInvalid()) 13390 return QualType(); 13391 Op = ConvResult.get(); 13392 QualType OpTy = Op->getType(); 13393 QualType Result; 13394 13395 if (isa<CXXReinterpretCastExpr>(Op)) { 13396 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13397 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13398 Op->getSourceRange()); 13399 } 13400 13401 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13402 { 13403 Result = PT->getPointeeType(); 13404 } 13405 else if (const ObjCObjectPointerType *OPT = 13406 OpTy->getAs<ObjCObjectPointerType>()) 13407 Result = OPT->getPointeeType(); 13408 else { 13409 ExprResult PR = S.CheckPlaceholderExpr(Op); 13410 if (PR.isInvalid()) return QualType(); 13411 if (PR.get() != Op) 13412 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13413 } 13414 13415 if (Result.isNull()) { 13416 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13417 << OpTy << Op->getSourceRange(); 13418 return QualType(); 13419 } 13420 13421 // Note that per both C89 and C99, indirection is always legal, even if Result 13422 // is an incomplete type or void. It would be possible to warn about 13423 // dereferencing a void pointer, but it's completely well-defined, and such a 13424 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13425 // for pointers to 'void' but is fine for any other pointer type: 13426 // 13427 // C++ [expr.unary.op]p1: 13428 // [...] the expression to which [the unary * operator] is applied shall 13429 // be a pointer to an object type, or a pointer to a function type 13430 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13431 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13432 << OpTy << Op->getSourceRange(); 13433 13434 // Dereferences are usually l-values... 13435 VK = VK_LValue; 13436 13437 // ...except that certain expressions are never l-values in C. 13438 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13439 VK = VK_RValue; 13440 13441 return Result; 13442 } 13443 13444 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13445 BinaryOperatorKind Opc; 13446 switch (Kind) { 13447 default: llvm_unreachable("Unknown binop!"); 13448 case tok::periodstar: Opc = BO_PtrMemD; break; 13449 case tok::arrowstar: Opc = BO_PtrMemI; break; 13450 case tok::star: Opc = BO_Mul; break; 13451 case tok::slash: Opc = BO_Div; break; 13452 case tok::percent: Opc = BO_Rem; break; 13453 case tok::plus: Opc = BO_Add; break; 13454 case tok::minus: Opc = BO_Sub; break; 13455 case tok::lessless: Opc = BO_Shl; break; 13456 case tok::greatergreater: Opc = BO_Shr; break; 13457 case tok::lessequal: Opc = BO_LE; break; 13458 case tok::less: Opc = BO_LT; break; 13459 case tok::greaterequal: Opc = BO_GE; break; 13460 case tok::greater: Opc = BO_GT; break; 13461 case tok::exclaimequal: Opc = BO_NE; break; 13462 case tok::equalequal: Opc = BO_EQ; break; 13463 case tok::spaceship: Opc = BO_Cmp; break; 13464 case tok::amp: Opc = BO_And; break; 13465 case tok::caret: Opc = BO_Xor; break; 13466 case tok::pipe: Opc = BO_Or; break; 13467 case tok::ampamp: Opc = BO_LAnd; break; 13468 case tok::pipepipe: Opc = BO_LOr; break; 13469 case tok::equal: Opc = BO_Assign; break; 13470 case tok::starequal: Opc = BO_MulAssign; break; 13471 case tok::slashequal: Opc = BO_DivAssign; break; 13472 case tok::percentequal: Opc = BO_RemAssign; break; 13473 case tok::plusequal: Opc = BO_AddAssign; break; 13474 case tok::minusequal: Opc = BO_SubAssign; break; 13475 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13476 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13477 case tok::ampequal: Opc = BO_AndAssign; break; 13478 case tok::caretequal: Opc = BO_XorAssign; break; 13479 case tok::pipeequal: Opc = BO_OrAssign; break; 13480 case tok::comma: Opc = BO_Comma; break; 13481 } 13482 return Opc; 13483 } 13484 13485 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13486 tok::TokenKind Kind) { 13487 UnaryOperatorKind Opc; 13488 switch (Kind) { 13489 default: llvm_unreachable("Unknown unary op!"); 13490 case tok::plusplus: Opc = UO_PreInc; break; 13491 case tok::minusminus: Opc = UO_PreDec; break; 13492 case tok::amp: Opc = UO_AddrOf; break; 13493 case tok::star: Opc = UO_Deref; break; 13494 case tok::plus: Opc = UO_Plus; break; 13495 case tok::minus: Opc = UO_Minus; break; 13496 case tok::tilde: Opc = UO_Not; break; 13497 case tok::exclaim: Opc = UO_LNot; break; 13498 case tok::kw___real: Opc = UO_Real; break; 13499 case tok::kw___imag: Opc = UO_Imag; break; 13500 case tok::kw___extension__: Opc = UO_Extension; break; 13501 } 13502 return Opc; 13503 } 13504 13505 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13506 /// This warning suppressed in the event of macro expansions. 13507 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13508 SourceLocation OpLoc, bool IsBuiltin) { 13509 if (S.inTemplateInstantiation()) 13510 return; 13511 if (S.isUnevaluatedContext()) 13512 return; 13513 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13514 return; 13515 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13516 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13517 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13518 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13519 if (!LHSDeclRef || !RHSDeclRef || 13520 LHSDeclRef->getLocation().isMacroID() || 13521 RHSDeclRef->getLocation().isMacroID()) 13522 return; 13523 const ValueDecl *LHSDecl = 13524 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13525 const ValueDecl *RHSDecl = 13526 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13527 if (LHSDecl != RHSDecl) 13528 return; 13529 if (LHSDecl->getType().isVolatileQualified()) 13530 return; 13531 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13532 if (RefTy->getPointeeType().isVolatileQualified()) 13533 return; 13534 13535 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13536 : diag::warn_self_assignment_overloaded) 13537 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13538 << RHSExpr->getSourceRange(); 13539 } 13540 13541 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13542 /// is usually indicative of introspection within the Objective-C pointer. 13543 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13544 SourceLocation OpLoc) { 13545 if (!S.getLangOpts().ObjC) 13546 return; 13547 13548 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13549 const Expr *LHS = L.get(); 13550 const Expr *RHS = R.get(); 13551 13552 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13553 ObjCPointerExpr = LHS; 13554 OtherExpr = RHS; 13555 } 13556 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13557 ObjCPointerExpr = RHS; 13558 OtherExpr = LHS; 13559 } 13560 13561 // This warning is deliberately made very specific to reduce false 13562 // positives with logic that uses '&' for hashing. This logic mainly 13563 // looks for code trying to introspect into tagged pointers, which 13564 // code should generally never do. 13565 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13566 unsigned Diag = diag::warn_objc_pointer_masking; 13567 // Determine if we are introspecting the result of performSelectorXXX. 13568 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13569 // Special case messages to -performSelector and friends, which 13570 // can return non-pointer values boxed in a pointer value. 13571 // Some clients may wish to silence warnings in this subcase. 13572 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13573 Selector S = ME->getSelector(); 13574 StringRef SelArg0 = S.getNameForSlot(0); 13575 if (SelArg0.startswith("performSelector")) 13576 Diag = diag::warn_objc_pointer_masking_performSelector; 13577 } 13578 13579 S.Diag(OpLoc, Diag) 13580 << ObjCPointerExpr->getSourceRange(); 13581 } 13582 } 13583 13584 static NamedDecl *getDeclFromExpr(Expr *E) { 13585 if (!E) 13586 return nullptr; 13587 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13588 return DRE->getDecl(); 13589 if (auto *ME = dyn_cast<MemberExpr>(E)) 13590 return ME->getMemberDecl(); 13591 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13592 return IRE->getDecl(); 13593 return nullptr; 13594 } 13595 13596 // This helper function promotes a binary operator's operands (which are of a 13597 // half vector type) to a vector of floats and then truncates the result to 13598 // a vector of either half or short. 13599 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13600 BinaryOperatorKind Opc, QualType ResultTy, 13601 ExprValueKind VK, ExprObjectKind OK, 13602 bool IsCompAssign, SourceLocation OpLoc, 13603 FPOptionsOverride FPFeatures) { 13604 auto &Context = S.getASTContext(); 13605 assert((isVector(ResultTy, Context.HalfTy) || 13606 isVector(ResultTy, Context.ShortTy)) && 13607 "Result must be a vector of half or short"); 13608 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13609 isVector(RHS.get()->getType(), Context.HalfTy) && 13610 "both operands expected to be a half vector"); 13611 13612 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13613 QualType BinOpResTy = RHS.get()->getType(); 13614 13615 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13616 // change BinOpResTy to a vector of ints. 13617 if (isVector(ResultTy, Context.ShortTy)) 13618 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13619 13620 if (IsCompAssign) 13621 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13622 ResultTy, VK, OK, OpLoc, FPFeatures, 13623 BinOpResTy, BinOpResTy); 13624 13625 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13626 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13627 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13628 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13629 } 13630 13631 static std::pair<ExprResult, ExprResult> 13632 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13633 Expr *RHSExpr) { 13634 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13635 if (!S.getLangOpts().CPlusPlus) { 13636 // C cannot handle TypoExpr nodes on either side of a binop because it 13637 // doesn't handle dependent types properly, so make sure any TypoExprs have 13638 // been dealt with before checking the operands. 13639 LHS = S.CorrectDelayedTyposInExpr(LHS); 13640 RHS = S.CorrectDelayedTyposInExpr( 13641 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13642 [Opc, LHS](Expr *E) { 13643 if (Opc != BO_Assign) 13644 return ExprResult(E); 13645 // Avoid correcting the RHS to the same Expr as the LHS. 13646 Decl *D = getDeclFromExpr(E); 13647 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13648 }); 13649 } 13650 return std::make_pair(LHS, RHS); 13651 } 13652 13653 /// Returns true if conversion between vectors of halfs and vectors of floats 13654 /// is needed. 13655 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13656 Expr *E0, Expr *E1 = nullptr) { 13657 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13658 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13659 return false; 13660 13661 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13662 QualType Ty = E->IgnoreImplicit()->getType(); 13663 13664 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13665 // to vectors of floats. Although the element type of the vectors is __fp16, 13666 // the vectors shouldn't be treated as storage-only types. See the 13667 // discussion here: https://reviews.llvm.org/rG825235c140e7 13668 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13669 if (VT->getVectorKind() == VectorType::NeonVector) 13670 return false; 13671 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13672 } 13673 return false; 13674 }; 13675 13676 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13677 } 13678 13679 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13680 /// operator @p Opc at location @c TokLoc. This routine only supports 13681 /// built-in operations; ActOnBinOp handles overloaded operators. 13682 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13683 BinaryOperatorKind Opc, 13684 Expr *LHSExpr, Expr *RHSExpr) { 13685 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13686 // The syntax only allows initializer lists on the RHS of assignment, 13687 // so we don't need to worry about accepting invalid code for 13688 // non-assignment operators. 13689 // C++11 5.17p9: 13690 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13691 // of x = {} is x = T(). 13692 InitializationKind Kind = InitializationKind::CreateDirectList( 13693 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13694 InitializedEntity Entity = 13695 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13696 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13697 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13698 if (Init.isInvalid()) 13699 return Init; 13700 RHSExpr = Init.get(); 13701 } 13702 13703 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13704 QualType ResultTy; // Result type of the binary operator. 13705 // The following two variables are used for compound assignment operators 13706 QualType CompLHSTy; // Type of LHS after promotions for computation 13707 QualType CompResultTy; // Type of computation result 13708 ExprValueKind VK = VK_RValue; 13709 ExprObjectKind OK = OK_Ordinary; 13710 bool ConvertHalfVec = false; 13711 13712 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13713 if (!LHS.isUsable() || !RHS.isUsable()) 13714 return ExprError(); 13715 13716 if (getLangOpts().OpenCL) { 13717 QualType LHSTy = LHSExpr->getType(); 13718 QualType RHSTy = RHSExpr->getType(); 13719 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13720 // the ATOMIC_VAR_INIT macro. 13721 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13722 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13723 if (BO_Assign == Opc) 13724 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13725 else 13726 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13727 return ExprError(); 13728 } 13729 13730 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13731 // only with a builtin functions and therefore should be disallowed here. 13732 if (LHSTy->isImageType() || RHSTy->isImageType() || 13733 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13734 LHSTy->isPipeType() || RHSTy->isPipeType() || 13735 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13736 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13737 return ExprError(); 13738 } 13739 } 13740 13741 switch (Opc) { 13742 case BO_Assign: 13743 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13744 if (getLangOpts().CPlusPlus && 13745 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13746 VK = LHS.get()->getValueKind(); 13747 OK = LHS.get()->getObjectKind(); 13748 } 13749 if (!ResultTy.isNull()) { 13750 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13751 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13752 13753 // Avoid copying a block to the heap if the block is assigned to a local 13754 // auto variable that is declared in the same scope as the block. This 13755 // optimization is unsafe if the local variable is declared in an outer 13756 // scope. For example: 13757 // 13758 // BlockTy b; 13759 // { 13760 // b = ^{...}; 13761 // } 13762 // // It is unsafe to invoke the block here if it wasn't copied to the 13763 // // heap. 13764 // b(); 13765 13766 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13767 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13768 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13769 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13770 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13771 13772 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13773 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13774 NTCUC_Assignment, NTCUK_Copy); 13775 } 13776 RecordModifiableNonNullParam(*this, LHS.get()); 13777 break; 13778 case BO_PtrMemD: 13779 case BO_PtrMemI: 13780 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13781 Opc == BO_PtrMemI); 13782 break; 13783 case BO_Mul: 13784 case BO_Div: 13785 ConvertHalfVec = true; 13786 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13787 Opc == BO_Div); 13788 break; 13789 case BO_Rem: 13790 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13791 break; 13792 case BO_Add: 13793 ConvertHalfVec = true; 13794 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13795 break; 13796 case BO_Sub: 13797 ConvertHalfVec = true; 13798 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13799 break; 13800 case BO_Shl: 13801 case BO_Shr: 13802 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13803 break; 13804 case BO_LE: 13805 case BO_LT: 13806 case BO_GE: 13807 case BO_GT: 13808 ConvertHalfVec = true; 13809 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13810 break; 13811 case BO_EQ: 13812 case BO_NE: 13813 ConvertHalfVec = true; 13814 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13815 break; 13816 case BO_Cmp: 13817 ConvertHalfVec = true; 13818 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13819 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13820 break; 13821 case BO_And: 13822 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13823 LLVM_FALLTHROUGH; 13824 case BO_Xor: 13825 case BO_Or: 13826 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13827 break; 13828 case BO_LAnd: 13829 case BO_LOr: 13830 ConvertHalfVec = true; 13831 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13832 break; 13833 case BO_MulAssign: 13834 case BO_DivAssign: 13835 ConvertHalfVec = true; 13836 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13837 Opc == BO_DivAssign); 13838 CompLHSTy = CompResultTy; 13839 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13840 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13841 break; 13842 case BO_RemAssign: 13843 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13844 CompLHSTy = CompResultTy; 13845 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13846 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13847 break; 13848 case BO_AddAssign: 13849 ConvertHalfVec = true; 13850 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13851 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13852 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13853 break; 13854 case BO_SubAssign: 13855 ConvertHalfVec = true; 13856 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13857 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13858 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13859 break; 13860 case BO_ShlAssign: 13861 case BO_ShrAssign: 13862 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13863 CompLHSTy = CompResultTy; 13864 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13865 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13866 break; 13867 case BO_AndAssign: 13868 case BO_OrAssign: // fallthrough 13869 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13870 LLVM_FALLTHROUGH; 13871 case BO_XorAssign: 13872 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13873 CompLHSTy = CompResultTy; 13874 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13875 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13876 break; 13877 case BO_Comma: 13878 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13879 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13880 VK = RHS.get()->getValueKind(); 13881 OK = RHS.get()->getObjectKind(); 13882 } 13883 break; 13884 } 13885 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13886 return ExprError(); 13887 13888 // Some of the binary operations require promoting operands of half vector to 13889 // float vectors and truncating the result back to half vector. For now, we do 13890 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13891 // arm64). 13892 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13893 isVector(LHS.get()->getType(), Context.HalfTy) && 13894 "both sides are half vectors or neither sides are"); 13895 ConvertHalfVec = 13896 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13897 13898 // Check for array bounds violations for both sides of the BinaryOperator 13899 CheckArrayAccess(LHS.get()); 13900 CheckArrayAccess(RHS.get()); 13901 13902 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13903 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13904 &Context.Idents.get("object_setClass"), 13905 SourceLocation(), LookupOrdinaryName); 13906 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13907 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13908 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13909 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13910 "object_setClass(") 13911 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13912 ",") 13913 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13914 } 13915 else 13916 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13917 } 13918 else if (const ObjCIvarRefExpr *OIRE = 13919 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13920 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13921 13922 // Opc is not a compound assignment if CompResultTy is null. 13923 if (CompResultTy.isNull()) { 13924 if (ConvertHalfVec) 13925 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13926 OpLoc, CurFPFeatureOverrides()); 13927 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13928 VK, OK, OpLoc, CurFPFeatureOverrides()); 13929 } 13930 13931 // Handle compound assignments. 13932 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13933 OK_ObjCProperty) { 13934 VK = VK_LValue; 13935 OK = LHS.get()->getObjectKind(); 13936 } 13937 13938 // The LHS is not converted to the result type for fixed-point compound 13939 // assignment as the common type is computed on demand. Reset the CompLHSTy 13940 // to the LHS type we would have gotten after unary conversions. 13941 if (CompResultTy->isFixedPointType()) 13942 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13943 13944 if (ConvertHalfVec) 13945 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13946 OpLoc, CurFPFeatureOverrides()); 13947 13948 return CompoundAssignOperator::Create( 13949 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 13950 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 13951 } 13952 13953 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13954 /// operators are mixed in a way that suggests that the programmer forgot that 13955 /// comparison operators have higher precedence. The most typical example of 13956 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13957 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13958 SourceLocation OpLoc, Expr *LHSExpr, 13959 Expr *RHSExpr) { 13960 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13961 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13962 13963 // Check that one of the sides is a comparison operator and the other isn't. 13964 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13965 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13966 if (isLeftComp == isRightComp) 13967 return; 13968 13969 // Bitwise operations are sometimes used as eager logical ops. 13970 // Don't diagnose this. 13971 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13972 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13973 if (isLeftBitwise || isRightBitwise) 13974 return; 13975 13976 SourceRange DiagRange = isLeftComp 13977 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13978 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13979 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13980 SourceRange ParensRange = 13981 isLeftComp 13982 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13983 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13984 13985 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13986 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13987 SuggestParentheses(Self, OpLoc, 13988 Self.PDiag(diag::note_precedence_silence) << OpStr, 13989 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13990 SuggestParentheses(Self, OpLoc, 13991 Self.PDiag(diag::note_precedence_bitwise_first) 13992 << BinaryOperator::getOpcodeStr(Opc), 13993 ParensRange); 13994 } 13995 13996 /// It accepts a '&&' expr that is inside a '||' one. 13997 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13998 /// in parentheses. 13999 static void 14000 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14001 BinaryOperator *Bop) { 14002 assert(Bop->getOpcode() == BO_LAnd); 14003 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14004 << Bop->getSourceRange() << OpLoc; 14005 SuggestParentheses(Self, Bop->getOperatorLoc(), 14006 Self.PDiag(diag::note_precedence_silence) 14007 << Bop->getOpcodeStr(), 14008 Bop->getSourceRange()); 14009 } 14010 14011 /// Returns true if the given expression can be evaluated as a constant 14012 /// 'true'. 14013 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14014 bool Res; 14015 return !E->isValueDependent() && 14016 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14017 } 14018 14019 /// Returns true if the given expression can be evaluated as a constant 14020 /// 'false'. 14021 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14022 bool Res; 14023 return !E->isValueDependent() && 14024 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14025 } 14026 14027 /// Look for '&&' in the left hand of a '||' expr. 14028 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14029 Expr *LHSExpr, Expr *RHSExpr) { 14030 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14031 if (Bop->getOpcode() == BO_LAnd) { 14032 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14033 if (EvaluatesAsFalse(S, RHSExpr)) 14034 return; 14035 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14036 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14037 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14038 } else if (Bop->getOpcode() == BO_LOr) { 14039 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14040 // If it's "a || b && 1 || c" we didn't warn earlier for 14041 // "a || b && 1", but warn now. 14042 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14043 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14044 } 14045 } 14046 } 14047 } 14048 14049 /// Look for '&&' in the right hand of a '||' expr. 14050 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14051 Expr *LHSExpr, Expr *RHSExpr) { 14052 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14053 if (Bop->getOpcode() == BO_LAnd) { 14054 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14055 if (EvaluatesAsFalse(S, LHSExpr)) 14056 return; 14057 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14058 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14059 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14060 } 14061 } 14062 } 14063 14064 /// Look for bitwise op in the left or right hand of a bitwise op with 14065 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14066 /// the '&' expression in parentheses. 14067 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14068 SourceLocation OpLoc, Expr *SubExpr) { 14069 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14070 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14071 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14072 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14073 << Bop->getSourceRange() << OpLoc; 14074 SuggestParentheses(S, Bop->getOperatorLoc(), 14075 S.PDiag(diag::note_precedence_silence) 14076 << Bop->getOpcodeStr(), 14077 Bop->getSourceRange()); 14078 } 14079 } 14080 } 14081 14082 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14083 Expr *SubExpr, StringRef Shift) { 14084 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14085 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14086 StringRef Op = Bop->getOpcodeStr(); 14087 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14088 << Bop->getSourceRange() << OpLoc << Shift << Op; 14089 SuggestParentheses(S, Bop->getOperatorLoc(), 14090 S.PDiag(diag::note_precedence_silence) << Op, 14091 Bop->getSourceRange()); 14092 } 14093 } 14094 } 14095 14096 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14097 Expr *LHSExpr, Expr *RHSExpr) { 14098 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14099 if (!OCE) 14100 return; 14101 14102 FunctionDecl *FD = OCE->getDirectCallee(); 14103 if (!FD || !FD->isOverloadedOperator()) 14104 return; 14105 14106 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14107 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14108 return; 14109 14110 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14111 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14112 << (Kind == OO_LessLess); 14113 SuggestParentheses(S, OCE->getOperatorLoc(), 14114 S.PDiag(diag::note_precedence_silence) 14115 << (Kind == OO_LessLess ? "<<" : ">>"), 14116 OCE->getSourceRange()); 14117 SuggestParentheses( 14118 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14119 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14120 } 14121 14122 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14123 /// precedence. 14124 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14125 SourceLocation OpLoc, Expr *LHSExpr, 14126 Expr *RHSExpr){ 14127 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14128 if (BinaryOperator::isBitwiseOp(Opc)) 14129 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14130 14131 // Diagnose "arg1 & arg2 | arg3" 14132 if ((Opc == BO_Or || Opc == BO_Xor) && 14133 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14134 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14135 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14136 } 14137 14138 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14139 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14140 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14141 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14142 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14143 } 14144 14145 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14146 || Opc == BO_Shr) { 14147 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14148 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14149 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14150 } 14151 14152 // Warn on overloaded shift operators and comparisons, such as: 14153 // cout << 5 == 4; 14154 if (BinaryOperator::isComparisonOp(Opc)) 14155 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14156 } 14157 14158 // Binary Operators. 'Tok' is the token for the operator. 14159 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14160 tok::TokenKind Kind, 14161 Expr *LHSExpr, Expr *RHSExpr) { 14162 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14163 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14164 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14165 14166 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14167 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14168 14169 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14170 } 14171 14172 /// Build an overloaded binary operator expression in the given scope. 14173 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14174 BinaryOperatorKind Opc, 14175 Expr *LHS, Expr *RHS) { 14176 switch (Opc) { 14177 case BO_Assign: 14178 case BO_DivAssign: 14179 case BO_RemAssign: 14180 case BO_SubAssign: 14181 case BO_AndAssign: 14182 case BO_OrAssign: 14183 case BO_XorAssign: 14184 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14185 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14186 break; 14187 default: 14188 break; 14189 } 14190 14191 // Find all of the overloaded operators visible from this 14192 // point. We perform both an operator-name lookup from the local 14193 // scope and an argument-dependent lookup based on the types of 14194 // the arguments. 14195 UnresolvedSet<16> Functions; 14196 OverloadedOperatorKind OverOp 14197 = BinaryOperator::getOverloadedOperator(Opc); 14198 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 14199 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 14200 RHS->getType(), Functions); 14201 14202 // In C++20 onwards, we may have a second operator to look up. 14203 if (S.getLangOpts().CPlusPlus20) { 14204 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14205 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 14206 RHS->getType(), Functions); 14207 } 14208 14209 // Build the (potentially-overloaded, potentially-dependent) 14210 // binary operation. 14211 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14212 } 14213 14214 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14215 BinaryOperatorKind Opc, 14216 Expr *LHSExpr, Expr *RHSExpr) { 14217 ExprResult LHS, RHS; 14218 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14219 if (!LHS.isUsable() || !RHS.isUsable()) 14220 return ExprError(); 14221 LHSExpr = LHS.get(); 14222 RHSExpr = RHS.get(); 14223 14224 // We want to end up calling one of checkPseudoObjectAssignment 14225 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14226 // both expressions are overloadable or either is type-dependent), 14227 // or CreateBuiltinBinOp (in any other case). We also want to get 14228 // any placeholder types out of the way. 14229 14230 // Handle pseudo-objects in the LHS. 14231 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14232 // Assignments with a pseudo-object l-value need special analysis. 14233 if (pty->getKind() == BuiltinType::PseudoObject && 14234 BinaryOperator::isAssignmentOp(Opc)) 14235 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14236 14237 // Don't resolve overloads if the other type is overloadable. 14238 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14239 // We can't actually test that if we still have a placeholder, 14240 // though. Fortunately, none of the exceptions we see in that 14241 // code below are valid when the LHS is an overload set. Note 14242 // that an overload set can be dependently-typed, but it never 14243 // instantiates to having an overloadable type. 14244 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14245 if (resolvedRHS.isInvalid()) return ExprError(); 14246 RHSExpr = resolvedRHS.get(); 14247 14248 if (RHSExpr->isTypeDependent() || 14249 RHSExpr->getType()->isOverloadableType()) 14250 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14251 } 14252 14253 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14254 // template, diagnose the missing 'template' keyword instead of diagnosing 14255 // an invalid use of a bound member function. 14256 // 14257 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14258 // to C++1z [over.over]/1.4, but we already checked for that case above. 14259 if (Opc == BO_LT && inTemplateInstantiation() && 14260 (pty->getKind() == BuiltinType::BoundMember || 14261 pty->getKind() == BuiltinType::Overload)) { 14262 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14263 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14264 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14265 return isa<FunctionTemplateDecl>(ND); 14266 })) { 14267 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14268 : OE->getNameLoc(), 14269 diag::err_template_kw_missing) 14270 << OE->getName().getAsString() << ""; 14271 return ExprError(); 14272 } 14273 } 14274 14275 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14276 if (LHS.isInvalid()) return ExprError(); 14277 LHSExpr = LHS.get(); 14278 } 14279 14280 // Handle pseudo-objects in the RHS. 14281 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14282 // An overload in the RHS can potentially be resolved by the type 14283 // being assigned to. 14284 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14285 if (getLangOpts().CPlusPlus && 14286 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14287 LHSExpr->getType()->isOverloadableType())) 14288 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14289 14290 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14291 } 14292 14293 // Don't resolve overloads if the other type is overloadable. 14294 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14295 LHSExpr->getType()->isOverloadableType()) 14296 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14297 14298 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14299 if (!resolvedRHS.isUsable()) return ExprError(); 14300 RHSExpr = resolvedRHS.get(); 14301 } 14302 14303 if (getLangOpts().CPlusPlus) { 14304 // If either expression is type-dependent, always build an 14305 // overloaded op. 14306 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14307 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14308 14309 // Otherwise, build an overloaded op if either expression has an 14310 // overloadable type. 14311 if (LHSExpr->getType()->isOverloadableType() || 14312 RHSExpr->getType()->isOverloadableType()) 14313 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14314 } 14315 14316 // Build a built-in binary operation. 14317 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14318 } 14319 14320 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14321 if (T.isNull() || T->isDependentType()) 14322 return false; 14323 14324 if (!T->isPromotableIntegerType()) 14325 return true; 14326 14327 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14328 } 14329 14330 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14331 UnaryOperatorKind Opc, 14332 Expr *InputExpr) { 14333 ExprResult Input = InputExpr; 14334 ExprValueKind VK = VK_RValue; 14335 ExprObjectKind OK = OK_Ordinary; 14336 QualType resultType; 14337 bool CanOverflow = false; 14338 14339 bool ConvertHalfVec = false; 14340 if (getLangOpts().OpenCL) { 14341 QualType Ty = InputExpr->getType(); 14342 // The only legal unary operation for atomics is '&'. 14343 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14344 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14345 // only with a builtin functions and therefore should be disallowed here. 14346 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14347 || Ty->isBlockPointerType())) { 14348 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14349 << InputExpr->getType() 14350 << Input.get()->getSourceRange()); 14351 } 14352 } 14353 14354 switch (Opc) { 14355 case UO_PreInc: 14356 case UO_PreDec: 14357 case UO_PostInc: 14358 case UO_PostDec: 14359 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14360 OpLoc, 14361 Opc == UO_PreInc || 14362 Opc == UO_PostInc, 14363 Opc == UO_PreInc || 14364 Opc == UO_PreDec); 14365 CanOverflow = isOverflowingIntegerType(Context, resultType); 14366 break; 14367 case UO_AddrOf: 14368 resultType = CheckAddressOfOperand(Input, OpLoc); 14369 CheckAddressOfNoDeref(InputExpr); 14370 RecordModifiableNonNullParam(*this, InputExpr); 14371 break; 14372 case UO_Deref: { 14373 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14374 if (Input.isInvalid()) return ExprError(); 14375 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14376 break; 14377 } 14378 case UO_Plus: 14379 case UO_Minus: 14380 CanOverflow = Opc == UO_Minus && 14381 isOverflowingIntegerType(Context, Input.get()->getType()); 14382 Input = UsualUnaryConversions(Input.get()); 14383 if (Input.isInvalid()) return ExprError(); 14384 // Unary plus and minus require promoting an operand of half vector to a 14385 // float vector and truncating the result back to a half vector. For now, we 14386 // do this only when HalfArgsAndReturns is set (that is, when the target is 14387 // arm or arm64). 14388 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14389 14390 // If the operand is a half vector, promote it to a float vector. 14391 if (ConvertHalfVec) 14392 Input = convertVector(Input.get(), Context.FloatTy, *this); 14393 resultType = Input.get()->getType(); 14394 if (resultType->isDependentType()) 14395 break; 14396 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14397 break; 14398 else if (resultType->isVectorType() && 14399 // The z vector extensions don't allow + or - with bool vectors. 14400 (!Context.getLangOpts().ZVector || 14401 resultType->castAs<VectorType>()->getVectorKind() != 14402 VectorType::AltiVecBool)) 14403 break; 14404 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14405 Opc == UO_Plus && 14406 resultType->isPointerType()) 14407 break; 14408 14409 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14410 << resultType << Input.get()->getSourceRange()); 14411 14412 case UO_Not: // bitwise complement 14413 Input = UsualUnaryConversions(Input.get()); 14414 if (Input.isInvalid()) 14415 return ExprError(); 14416 resultType = Input.get()->getType(); 14417 if (resultType->isDependentType()) 14418 break; 14419 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14420 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14421 // C99 does not support '~' for complex conjugation. 14422 Diag(OpLoc, diag::ext_integer_complement_complex) 14423 << resultType << Input.get()->getSourceRange(); 14424 else if (resultType->hasIntegerRepresentation()) 14425 break; 14426 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14427 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14428 // on vector float types. 14429 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14430 if (!T->isIntegerType()) 14431 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14432 << resultType << Input.get()->getSourceRange()); 14433 } else { 14434 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14435 << resultType << Input.get()->getSourceRange()); 14436 } 14437 break; 14438 14439 case UO_LNot: // logical negation 14440 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14441 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14442 if (Input.isInvalid()) return ExprError(); 14443 resultType = Input.get()->getType(); 14444 14445 // Though we still have to promote half FP to float... 14446 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14447 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14448 resultType = Context.FloatTy; 14449 } 14450 14451 if (resultType->isDependentType()) 14452 break; 14453 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14454 // C99 6.5.3.3p1: ok, fallthrough; 14455 if (Context.getLangOpts().CPlusPlus) { 14456 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14457 // operand contextually converted to bool. 14458 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14459 ScalarTypeToBooleanCastKind(resultType)); 14460 } else if (Context.getLangOpts().OpenCL && 14461 Context.getLangOpts().OpenCLVersion < 120) { 14462 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14463 // operate on scalar float types. 14464 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14465 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14466 << resultType << Input.get()->getSourceRange()); 14467 } 14468 } else if (resultType->isExtVectorType()) { 14469 if (Context.getLangOpts().OpenCL && 14470 Context.getLangOpts().OpenCLVersion < 120 && 14471 !Context.getLangOpts().OpenCLCPlusPlus) { 14472 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14473 // operate on vector float types. 14474 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14475 if (!T->isIntegerType()) 14476 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14477 << resultType << Input.get()->getSourceRange()); 14478 } 14479 // Vector logical not returns the signed variant of the operand type. 14480 resultType = GetSignedVectorType(resultType); 14481 break; 14482 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14483 const VectorType *VTy = resultType->castAs<VectorType>(); 14484 if (VTy->getVectorKind() != VectorType::GenericVector) 14485 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14486 << resultType << Input.get()->getSourceRange()); 14487 14488 // Vector logical not returns the signed variant of the operand type. 14489 resultType = GetSignedVectorType(resultType); 14490 break; 14491 } else { 14492 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14493 << resultType << Input.get()->getSourceRange()); 14494 } 14495 14496 // LNot always has type int. C99 6.5.3.3p5. 14497 // In C++, it's bool. C++ 5.3.1p8 14498 resultType = Context.getLogicalOperationType(); 14499 break; 14500 case UO_Real: 14501 case UO_Imag: 14502 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14503 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14504 // complex l-values to ordinary l-values and all other values to r-values. 14505 if (Input.isInvalid()) return ExprError(); 14506 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14507 if (Input.get()->getValueKind() != VK_RValue && 14508 Input.get()->getObjectKind() == OK_Ordinary) 14509 VK = Input.get()->getValueKind(); 14510 } else if (!getLangOpts().CPlusPlus) { 14511 // In C, a volatile scalar is read by __imag. In C++, it is not. 14512 Input = DefaultLvalueConversion(Input.get()); 14513 } 14514 break; 14515 case UO_Extension: 14516 resultType = Input.get()->getType(); 14517 VK = Input.get()->getValueKind(); 14518 OK = Input.get()->getObjectKind(); 14519 break; 14520 case UO_Coawait: 14521 // It's unnecessary to represent the pass-through operator co_await in the 14522 // AST; just return the input expression instead. 14523 assert(!Input.get()->getType()->isDependentType() && 14524 "the co_await expression must be non-dependant before " 14525 "building operator co_await"); 14526 return Input; 14527 } 14528 if (resultType.isNull() || Input.isInvalid()) 14529 return ExprError(); 14530 14531 // Check for array bounds violations in the operand of the UnaryOperator, 14532 // except for the '*' and '&' operators that have to be handled specially 14533 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14534 // that are explicitly defined as valid by the standard). 14535 if (Opc != UO_AddrOf && Opc != UO_Deref) 14536 CheckArrayAccess(Input.get()); 14537 14538 auto *UO = 14539 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14540 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14541 14542 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14543 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14544 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14545 14546 // Convert the result back to a half vector. 14547 if (ConvertHalfVec) 14548 return convertVector(UO, Context.HalfTy, *this); 14549 return UO; 14550 } 14551 14552 /// Determine whether the given expression is a qualified member 14553 /// access expression, of a form that could be turned into a pointer to member 14554 /// with the address-of operator. 14555 bool Sema::isQualifiedMemberAccess(Expr *E) { 14556 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14557 if (!DRE->getQualifier()) 14558 return false; 14559 14560 ValueDecl *VD = DRE->getDecl(); 14561 if (!VD->isCXXClassMember()) 14562 return false; 14563 14564 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14565 return true; 14566 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14567 return Method->isInstance(); 14568 14569 return false; 14570 } 14571 14572 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14573 if (!ULE->getQualifier()) 14574 return false; 14575 14576 for (NamedDecl *D : ULE->decls()) { 14577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14578 if (Method->isInstance()) 14579 return true; 14580 } else { 14581 // Overload set does not contain methods. 14582 break; 14583 } 14584 } 14585 14586 return false; 14587 } 14588 14589 return false; 14590 } 14591 14592 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14593 UnaryOperatorKind Opc, Expr *Input) { 14594 // First things first: handle placeholders so that the 14595 // overloaded-operator check considers the right type. 14596 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14597 // Increment and decrement of pseudo-object references. 14598 if (pty->getKind() == BuiltinType::PseudoObject && 14599 UnaryOperator::isIncrementDecrementOp(Opc)) 14600 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14601 14602 // extension is always a builtin operator. 14603 if (Opc == UO_Extension) 14604 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14605 14606 // & gets special logic for several kinds of placeholder. 14607 // The builtin code knows what to do. 14608 if (Opc == UO_AddrOf && 14609 (pty->getKind() == BuiltinType::Overload || 14610 pty->getKind() == BuiltinType::UnknownAny || 14611 pty->getKind() == BuiltinType::BoundMember)) 14612 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14613 14614 // Anything else needs to be handled now. 14615 ExprResult Result = CheckPlaceholderExpr(Input); 14616 if (Result.isInvalid()) return ExprError(); 14617 Input = Result.get(); 14618 } 14619 14620 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14621 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14622 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14623 // Find all of the overloaded operators visible from this 14624 // point. We perform both an operator-name lookup from the local 14625 // scope and an argument-dependent lookup based on the types of 14626 // the arguments. 14627 UnresolvedSet<16> Functions; 14628 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14629 if (S && OverOp != OO_None) 14630 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 14631 Functions); 14632 14633 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14634 } 14635 14636 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14637 } 14638 14639 // Unary Operators. 'Tok' is the token for the operator. 14640 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14641 tok::TokenKind Op, Expr *Input) { 14642 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14643 } 14644 14645 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14646 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14647 LabelDecl *TheDecl) { 14648 TheDecl->markUsed(Context); 14649 // Create the AST node. The address of a label always has type 'void*'. 14650 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14651 Context.getPointerType(Context.VoidTy)); 14652 } 14653 14654 void Sema::ActOnStartStmtExpr() { 14655 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14656 } 14657 14658 void Sema::ActOnStmtExprError() { 14659 // Note that function is also called by TreeTransform when leaving a 14660 // StmtExpr scope without rebuilding anything. 14661 14662 DiscardCleanupsInEvaluationContext(); 14663 PopExpressionEvaluationContext(); 14664 } 14665 14666 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14667 SourceLocation RPLoc) { 14668 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14669 } 14670 14671 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14672 SourceLocation RPLoc, unsigned TemplateDepth) { 14673 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14674 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14675 14676 if (hasAnyUnrecoverableErrorsInThisFunction()) 14677 DiscardCleanupsInEvaluationContext(); 14678 assert(!Cleanup.exprNeedsCleanups() && 14679 "cleanups within StmtExpr not correctly bound!"); 14680 PopExpressionEvaluationContext(); 14681 14682 // FIXME: there are a variety of strange constraints to enforce here, for 14683 // example, it is not possible to goto into a stmt expression apparently. 14684 // More semantic analysis is needed. 14685 14686 // If there are sub-stmts in the compound stmt, take the type of the last one 14687 // as the type of the stmtexpr. 14688 QualType Ty = Context.VoidTy; 14689 bool StmtExprMayBindToTemp = false; 14690 if (!Compound->body_empty()) { 14691 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14692 if (const auto *LastStmt = 14693 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14694 if (const Expr *Value = LastStmt->getExprStmt()) { 14695 StmtExprMayBindToTemp = true; 14696 Ty = Value->getType(); 14697 } 14698 } 14699 } 14700 14701 // FIXME: Check that expression type is complete/non-abstract; statement 14702 // expressions are not lvalues. 14703 Expr *ResStmtExpr = 14704 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14705 if (StmtExprMayBindToTemp) 14706 return MaybeBindToTemporary(ResStmtExpr); 14707 return ResStmtExpr; 14708 } 14709 14710 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14711 if (ER.isInvalid()) 14712 return ExprError(); 14713 14714 // Do function/array conversion on the last expression, but not 14715 // lvalue-to-rvalue. However, initialize an unqualified type. 14716 ER = DefaultFunctionArrayConversion(ER.get()); 14717 if (ER.isInvalid()) 14718 return ExprError(); 14719 Expr *E = ER.get(); 14720 14721 if (E->isTypeDependent()) 14722 return E; 14723 14724 // In ARC, if the final expression ends in a consume, splice 14725 // the consume out and bind it later. In the alternate case 14726 // (when dealing with a retainable type), the result 14727 // initialization will create a produce. In both cases the 14728 // result will be +1, and we'll need to balance that out with 14729 // a bind. 14730 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14731 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14732 return Cast->getSubExpr(); 14733 14734 // FIXME: Provide a better location for the initialization. 14735 return PerformCopyInitialization( 14736 InitializedEntity::InitializeStmtExprResult( 14737 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14738 SourceLocation(), E); 14739 } 14740 14741 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14742 TypeSourceInfo *TInfo, 14743 ArrayRef<OffsetOfComponent> Components, 14744 SourceLocation RParenLoc) { 14745 QualType ArgTy = TInfo->getType(); 14746 bool Dependent = ArgTy->isDependentType(); 14747 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14748 14749 // We must have at least one component that refers to the type, and the first 14750 // one is known to be a field designator. Verify that the ArgTy represents 14751 // a struct/union/class. 14752 if (!Dependent && !ArgTy->isRecordType()) 14753 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14754 << ArgTy << TypeRange); 14755 14756 // Type must be complete per C99 7.17p3 because a declaring a variable 14757 // with an incomplete type would be ill-formed. 14758 if (!Dependent 14759 && RequireCompleteType(BuiltinLoc, ArgTy, 14760 diag::err_offsetof_incomplete_type, TypeRange)) 14761 return ExprError(); 14762 14763 bool DidWarnAboutNonPOD = false; 14764 QualType CurrentType = ArgTy; 14765 SmallVector<OffsetOfNode, 4> Comps; 14766 SmallVector<Expr*, 4> Exprs; 14767 for (const OffsetOfComponent &OC : Components) { 14768 if (OC.isBrackets) { 14769 // Offset of an array sub-field. TODO: Should we allow vector elements? 14770 if (!CurrentType->isDependentType()) { 14771 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14772 if(!AT) 14773 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14774 << CurrentType); 14775 CurrentType = AT->getElementType(); 14776 } else 14777 CurrentType = Context.DependentTy; 14778 14779 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14780 if (IdxRval.isInvalid()) 14781 return ExprError(); 14782 Expr *Idx = IdxRval.get(); 14783 14784 // The expression must be an integral expression. 14785 // FIXME: An integral constant expression? 14786 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14787 !Idx->getType()->isIntegerType()) 14788 return ExprError( 14789 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14790 << Idx->getSourceRange()); 14791 14792 // Record this array index. 14793 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14794 Exprs.push_back(Idx); 14795 continue; 14796 } 14797 14798 // Offset of a field. 14799 if (CurrentType->isDependentType()) { 14800 // We have the offset of a field, but we can't look into the dependent 14801 // type. Just record the identifier of the field. 14802 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14803 CurrentType = Context.DependentTy; 14804 continue; 14805 } 14806 14807 // We need to have a complete type to look into. 14808 if (RequireCompleteType(OC.LocStart, CurrentType, 14809 diag::err_offsetof_incomplete_type)) 14810 return ExprError(); 14811 14812 // Look for the designated field. 14813 const RecordType *RC = CurrentType->getAs<RecordType>(); 14814 if (!RC) 14815 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14816 << CurrentType); 14817 RecordDecl *RD = RC->getDecl(); 14818 14819 // C++ [lib.support.types]p5: 14820 // The macro offsetof accepts a restricted set of type arguments in this 14821 // International Standard. type shall be a POD structure or a POD union 14822 // (clause 9). 14823 // C++11 [support.types]p4: 14824 // If type is not a standard-layout class (Clause 9), the results are 14825 // undefined. 14826 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14827 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14828 unsigned DiagID = 14829 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14830 : diag::ext_offsetof_non_pod_type; 14831 14832 if (!IsSafe && !DidWarnAboutNonPOD && 14833 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14834 PDiag(DiagID) 14835 << SourceRange(Components[0].LocStart, OC.LocEnd) 14836 << CurrentType)) 14837 DidWarnAboutNonPOD = true; 14838 } 14839 14840 // Look for the field. 14841 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14842 LookupQualifiedName(R, RD); 14843 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14844 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14845 if (!MemberDecl) { 14846 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14847 MemberDecl = IndirectMemberDecl->getAnonField(); 14848 } 14849 14850 if (!MemberDecl) 14851 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14852 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14853 OC.LocEnd)); 14854 14855 // C99 7.17p3: 14856 // (If the specified member is a bit-field, the behavior is undefined.) 14857 // 14858 // We diagnose this as an error. 14859 if (MemberDecl->isBitField()) { 14860 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14861 << MemberDecl->getDeclName() 14862 << SourceRange(BuiltinLoc, RParenLoc); 14863 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14864 return ExprError(); 14865 } 14866 14867 RecordDecl *Parent = MemberDecl->getParent(); 14868 if (IndirectMemberDecl) 14869 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14870 14871 // If the member was found in a base class, introduce OffsetOfNodes for 14872 // the base class indirections. 14873 CXXBasePaths Paths; 14874 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14875 Paths)) { 14876 if (Paths.getDetectedVirtual()) { 14877 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14878 << MemberDecl->getDeclName() 14879 << SourceRange(BuiltinLoc, RParenLoc); 14880 return ExprError(); 14881 } 14882 14883 CXXBasePath &Path = Paths.front(); 14884 for (const CXXBasePathElement &B : Path) 14885 Comps.push_back(OffsetOfNode(B.Base)); 14886 } 14887 14888 if (IndirectMemberDecl) { 14889 for (auto *FI : IndirectMemberDecl->chain()) { 14890 assert(isa<FieldDecl>(FI)); 14891 Comps.push_back(OffsetOfNode(OC.LocStart, 14892 cast<FieldDecl>(FI), OC.LocEnd)); 14893 } 14894 } else 14895 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14896 14897 CurrentType = MemberDecl->getType().getNonReferenceType(); 14898 } 14899 14900 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14901 Comps, Exprs, RParenLoc); 14902 } 14903 14904 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14905 SourceLocation BuiltinLoc, 14906 SourceLocation TypeLoc, 14907 ParsedType ParsedArgTy, 14908 ArrayRef<OffsetOfComponent> Components, 14909 SourceLocation RParenLoc) { 14910 14911 TypeSourceInfo *ArgTInfo; 14912 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14913 if (ArgTy.isNull()) 14914 return ExprError(); 14915 14916 if (!ArgTInfo) 14917 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14918 14919 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14920 } 14921 14922 14923 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14924 Expr *CondExpr, 14925 Expr *LHSExpr, Expr *RHSExpr, 14926 SourceLocation RPLoc) { 14927 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14928 14929 ExprValueKind VK = VK_RValue; 14930 ExprObjectKind OK = OK_Ordinary; 14931 QualType resType; 14932 bool CondIsTrue = false; 14933 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14934 resType = Context.DependentTy; 14935 } else { 14936 // The conditional expression is required to be a constant expression. 14937 llvm::APSInt condEval(32); 14938 ExprResult CondICE 14939 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14940 diag::err_typecheck_choose_expr_requires_constant, false); 14941 if (CondICE.isInvalid()) 14942 return ExprError(); 14943 CondExpr = CondICE.get(); 14944 CondIsTrue = condEval.getZExtValue(); 14945 14946 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14947 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14948 14949 resType = ActiveExpr->getType(); 14950 VK = ActiveExpr->getValueKind(); 14951 OK = ActiveExpr->getObjectKind(); 14952 } 14953 14954 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14955 resType, VK, OK, RPLoc, CondIsTrue); 14956 } 14957 14958 //===----------------------------------------------------------------------===// 14959 // Clang Extensions. 14960 //===----------------------------------------------------------------------===// 14961 14962 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14963 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14964 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14965 14966 if (LangOpts.CPlusPlus) { 14967 MangleNumberingContext *MCtx; 14968 Decl *ManglingContextDecl; 14969 std::tie(MCtx, ManglingContextDecl) = 14970 getCurrentMangleNumberContext(Block->getDeclContext()); 14971 if (MCtx) { 14972 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14973 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14974 } 14975 } 14976 14977 PushBlockScope(CurScope, Block); 14978 CurContext->addDecl(Block); 14979 if (CurScope) 14980 PushDeclContext(CurScope, Block); 14981 else 14982 CurContext = Block; 14983 14984 getCurBlock()->HasImplicitReturnType = true; 14985 14986 // Enter a new evaluation context to insulate the block from any 14987 // cleanups from the enclosing full-expression. 14988 PushExpressionEvaluationContext( 14989 ExpressionEvaluationContext::PotentiallyEvaluated); 14990 } 14991 14992 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14993 Scope *CurScope) { 14994 assert(ParamInfo.getIdentifier() == nullptr && 14995 "block-id should have no identifier!"); 14996 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14997 BlockScopeInfo *CurBlock = getCurBlock(); 14998 14999 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15000 QualType T = Sig->getType(); 15001 15002 // FIXME: We should allow unexpanded parameter packs here, but that would, 15003 // in turn, make the block expression contain unexpanded parameter packs. 15004 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15005 // Drop the parameters. 15006 FunctionProtoType::ExtProtoInfo EPI; 15007 EPI.HasTrailingReturn = false; 15008 EPI.TypeQuals.addConst(); 15009 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15010 Sig = Context.getTrivialTypeSourceInfo(T); 15011 } 15012 15013 // GetTypeForDeclarator always produces a function type for a block 15014 // literal signature. Furthermore, it is always a FunctionProtoType 15015 // unless the function was written with a typedef. 15016 assert(T->isFunctionType() && 15017 "GetTypeForDeclarator made a non-function block signature"); 15018 15019 // Look for an explicit signature in that function type. 15020 FunctionProtoTypeLoc ExplicitSignature; 15021 15022 if ((ExplicitSignature = Sig->getTypeLoc() 15023 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15024 15025 // Check whether that explicit signature was synthesized by 15026 // GetTypeForDeclarator. If so, don't save that as part of the 15027 // written signature. 15028 if (ExplicitSignature.getLocalRangeBegin() == 15029 ExplicitSignature.getLocalRangeEnd()) { 15030 // This would be much cheaper if we stored TypeLocs instead of 15031 // TypeSourceInfos. 15032 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15033 unsigned Size = Result.getFullDataSize(); 15034 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15035 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15036 15037 ExplicitSignature = FunctionProtoTypeLoc(); 15038 } 15039 } 15040 15041 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15042 CurBlock->FunctionType = T; 15043 15044 const FunctionType *Fn = T->getAs<FunctionType>(); 15045 QualType RetTy = Fn->getReturnType(); 15046 bool isVariadic = 15047 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15048 15049 CurBlock->TheDecl->setIsVariadic(isVariadic); 15050 15051 // Context.DependentTy is used as a placeholder for a missing block 15052 // return type. TODO: what should we do with declarators like: 15053 // ^ * { ... } 15054 // If the answer is "apply template argument deduction".... 15055 if (RetTy != Context.DependentTy) { 15056 CurBlock->ReturnType = RetTy; 15057 CurBlock->TheDecl->setBlockMissingReturnType(false); 15058 CurBlock->HasImplicitReturnType = false; 15059 } 15060 15061 // Push block parameters from the declarator if we had them. 15062 SmallVector<ParmVarDecl*, 8> Params; 15063 if (ExplicitSignature) { 15064 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15065 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15066 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15067 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15068 // Diagnose this as an extension in C17 and earlier. 15069 if (!getLangOpts().C2x) 15070 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15071 } 15072 Params.push_back(Param); 15073 } 15074 15075 // Fake up parameter variables if we have a typedef, like 15076 // ^ fntype { ... } 15077 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15078 for (const auto &I : Fn->param_types()) { 15079 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15080 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15081 Params.push_back(Param); 15082 } 15083 } 15084 15085 // Set the parameters on the block decl. 15086 if (!Params.empty()) { 15087 CurBlock->TheDecl->setParams(Params); 15088 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15089 /*CheckParameterNames=*/false); 15090 } 15091 15092 // Finally we can process decl attributes. 15093 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15094 15095 // Put the parameter variables in scope. 15096 for (auto AI : CurBlock->TheDecl->parameters()) { 15097 AI->setOwningFunction(CurBlock->TheDecl); 15098 15099 // If this has an identifier, add it to the scope stack. 15100 if (AI->getIdentifier()) { 15101 CheckShadow(CurBlock->TheScope, AI); 15102 15103 PushOnScopeChains(AI, CurBlock->TheScope); 15104 } 15105 } 15106 } 15107 15108 /// ActOnBlockError - If there is an error parsing a block, this callback 15109 /// is invoked to pop the information about the block from the action impl. 15110 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15111 // Leave the expression-evaluation context. 15112 DiscardCleanupsInEvaluationContext(); 15113 PopExpressionEvaluationContext(); 15114 15115 // Pop off CurBlock, handle nested blocks. 15116 PopDeclContext(); 15117 PopFunctionScopeInfo(); 15118 } 15119 15120 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15121 /// literal was successfully completed. ^(int x){...} 15122 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15123 Stmt *Body, Scope *CurScope) { 15124 // If blocks are disabled, emit an error. 15125 if (!LangOpts.Blocks) 15126 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15127 15128 // Leave the expression-evaluation context. 15129 if (hasAnyUnrecoverableErrorsInThisFunction()) 15130 DiscardCleanupsInEvaluationContext(); 15131 assert(!Cleanup.exprNeedsCleanups() && 15132 "cleanups within block not correctly bound!"); 15133 PopExpressionEvaluationContext(); 15134 15135 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15136 BlockDecl *BD = BSI->TheDecl; 15137 15138 if (BSI->HasImplicitReturnType) 15139 deduceClosureReturnType(*BSI); 15140 15141 QualType RetTy = Context.VoidTy; 15142 if (!BSI->ReturnType.isNull()) 15143 RetTy = BSI->ReturnType; 15144 15145 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15146 QualType BlockTy; 15147 15148 // If the user wrote a function type in some form, try to use that. 15149 if (!BSI->FunctionType.isNull()) { 15150 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15151 15152 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15153 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15154 15155 // Turn protoless block types into nullary block types. 15156 if (isa<FunctionNoProtoType>(FTy)) { 15157 FunctionProtoType::ExtProtoInfo EPI; 15158 EPI.ExtInfo = Ext; 15159 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15160 15161 // Otherwise, if we don't need to change anything about the function type, 15162 // preserve its sugar structure. 15163 } else if (FTy->getReturnType() == RetTy && 15164 (!NoReturn || FTy->getNoReturnAttr())) { 15165 BlockTy = BSI->FunctionType; 15166 15167 // Otherwise, make the minimal modifications to the function type. 15168 } else { 15169 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15170 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15171 EPI.TypeQuals = Qualifiers(); 15172 EPI.ExtInfo = Ext; 15173 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15174 } 15175 15176 // If we don't have a function type, just build one from nothing. 15177 } else { 15178 FunctionProtoType::ExtProtoInfo EPI; 15179 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15180 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15181 } 15182 15183 DiagnoseUnusedParameters(BD->parameters()); 15184 BlockTy = Context.getBlockPointerType(BlockTy); 15185 15186 // If needed, diagnose invalid gotos and switches in the block. 15187 if (getCurFunction()->NeedsScopeChecking() && 15188 !PP.isCodeCompletionEnabled()) 15189 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15190 15191 BD->setBody(cast<CompoundStmt>(Body)); 15192 15193 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15194 DiagnoseUnguardedAvailabilityViolations(BD); 15195 15196 // Try to apply the named return value optimization. We have to check again 15197 // if we can do this, though, because blocks keep return statements around 15198 // to deduce an implicit return type. 15199 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15200 !BD->isDependentContext()) 15201 computeNRVO(Body, BSI); 15202 15203 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15204 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15205 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15206 NTCUK_Destruct|NTCUK_Copy); 15207 15208 PopDeclContext(); 15209 15210 // Pop the block scope now but keep it alive to the end of this function. 15211 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15212 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15213 15214 // Set the captured variables on the block. 15215 SmallVector<BlockDecl::Capture, 4> Captures; 15216 for (Capture &Cap : BSI->Captures) { 15217 if (Cap.isInvalid() || Cap.isThisCapture()) 15218 continue; 15219 15220 VarDecl *Var = Cap.getVariable(); 15221 Expr *CopyExpr = nullptr; 15222 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15223 if (const RecordType *Record = 15224 Cap.getCaptureType()->getAs<RecordType>()) { 15225 // The capture logic needs the destructor, so make sure we mark it. 15226 // Usually this is unnecessary because most local variables have 15227 // their destructors marked at declaration time, but parameters are 15228 // an exception because it's technically only the call site that 15229 // actually requires the destructor. 15230 if (isa<ParmVarDecl>(Var)) 15231 FinalizeVarWithDestructor(Var, Record); 15232 15233 // Enter a separate potentially-evaluated context while building block 15234 // initializers to isolate their cleanups from those of the block 15235 // itself. 15236 // FIXME: Is this appropriate even when the block itself occurs in an 15237 // unevaluated operand? 15238 EnterExpressionEvaluationContext EvalContext( 15239 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15240 15241 SourceLocation Loc = Cap.getLocation(); 15242 15243 ExprResult Result = BuildDeclarationNameExpr( 15244 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15245 15246 // According to the blocks spec, the capture of a variable from 15247 // the stack requires a const copy constructor. This is not true 15248 // of the copy/move done to move a __block variable to the heap. 15249 if (!Result.isInvalid() && 15250 !Result.get()->getType().isConstQualified()) { 15251 Result = ImpCastExprToType(Result.get(), 15252 Result.get()->getType().withConst(), 15253 CK_NoOp, VK_LValue); 15254 } 15255 15256 if (!Result.isInvalid()) { 15257 Result = PerformCopyInitialization( 15258 InitializedEntity::InitializeBlock(Var->getLocation(), 15259 Cap.getCaptureType(), false), 15260 Loc, Result.get()); 15261 } 15262 15263 // Build a full-expression copy expression if initialization 15264 // succeeded and used a non-trivial constructor. Recover from 15265 // errors by pretending that the copy isn't necessary. 15266 if (!Result.isInvalid() && 15267 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15268 ->isTrivial()) { 15269 Result = MaybeCreateExprWithCleanups(Result); 15270 CopyExpr = Result.get(); 15271 } 15272 } 15273 } 15274 15275 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15276 CopyExpr); 15277 Captures.push_back(NewCap); 15278 } 15279 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15280 15281 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15282 15283 // If the block isn't obviously global, i.e. it captures anything at 15284 // all, then we need to do a few things in the surrounding context: 15285 if (Result->getBlockDecl()->hasCaptures()) { 15286 // First, this expression has a new cleanup object. 15287 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15288 Cleanup.setExprNeedsCleanups(true); 15289 15290 // It also gets a branch-protected scope if any of the captured 15291 // variables needs destruction. 15292 for (const auto &CI : Result->getBlockDecl()->captures()) { 15293 const VarDecl *var = CI.getVariable(); 15294 if (var->getType().isDestructedType() != QualType::DK_none) { 15295 setFunctionHasBranchProtectedScope(); 15296 break; 15297 } 15298 } 15299 } 15300 15301 if (getCurFunction()) 15302 getCurFunction()->addBlock(BD); 15303 15304 return Result; 15305 } 15306 15307 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15308 SourceLocation RPLoc) { 15309 TypeSourceInfo *TInfo; 15310 GetTypeFromParser(Ty, &TInfo); 15311 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15312 } 15313 15314 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15315 Expr *E, TypeSourceInfo *TInfo, 15316 SourceLocation RPLoc) { 15317 Expr *OrigExpr = E; 15318 bool IsMS = false; 15319 15320 // CUDA device code does not support varargs. 15321 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15322 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15323 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15324 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15325 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15326 } 15327 } 15328 15329 // NVPTX does not support va_arg expression. 15330 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15331 Context.getTargetInfo().getTriple().isNVPTX()) 15332 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15333 15334 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15335 // as Microsoft ABI on an actual Microsoft platform, where 15336 // __builtin_ms_va_list and __builtin_va_list are the same.) 15337 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15338 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15339 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15340 if (Context.hasSameType(MSVaListType, E->getType())) { 15341 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15342 return ExprError(); 15343 IsMS = true; 15344 } 15345 } 15346 15347 // Get the va_list type 15348 QualType VaListType = Context.getBuiltinVaListType(); 15349 if (!IsMS) { 15350 if (VaListType->isArrayType()) { 15351 // Deal with implicit array decay; for example, on x86-64, 15352 // va_list is an array, but it's supposed to decay to 15353 // a pointer for va_arg. 15354 VaListType = Context.getArrayDecayedType(VaListType); 15355 // Make sure the input expression also decays appropriately. 15356 ExprResult Result = UsualUnaryConversions(E); 15357 if (Result.isInvalid()) 15358 return ExprError(); 15359 E = Result.get(); 15360 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15361 // If va_list is a record type and we are compiling in C++ mode, 15362 // check the argument using reference binding. 15363 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15364 Context, Context.getLValueReferenceType(VaListType), false); 15365 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15366 if (Init.isInvalid()) 15367 return ExprError(); 15368 E = Init.getAs<Expr>(); 15369 } else { 15370 // Otherwise, the va_list argument must be an l-value because 15371 // it is modified by va_arg. 15372 if (!E->isTypeDependent() && 15373 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15374 return ExprError(); 15375 } 15376 } 15377 15378 if (!IsMS && !E->isTypeDependent() && 15379 !Context.hasSameType(VaListType, E->getType())) 15380 return ExprError( 15381 Diag(E->getBeginLoc(), 15382 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15383 << OrigExpr->getType() << E->getSourceRange()); 15384 15385 if (!TInfo->getType()->isDependentType()) { 15386 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15387 diag::err_second_parameter_to_va_arg_incomplete, 15388 TInfo->getTypeLoc())) 15389 return ExprError(); 15390 15391 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15392 TInfo->getType(), 15393 diag::err_second_parameter_to_va_arg_abstract, 15394 TInfo->getTypeLoc())) 15395 return ExprError(); 15396 15397 if (!TInfo->getType().isPODType(Context)) { 15398 Diag(TInfo->getTypeLoc().getBeginLoc(), 15399 TInfo->getType()->isObjCLifetimeType() 15400 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15401 : diag::warn_second_parameter_to_va_arg_not_pod) 15402 << TInfo->getType() 15403 << TInfo->getTypeLoc().getSourceRange(); 15404 } 15405 15406 // Check for va_arg where arguments of the given type will be promoted 15407 // (i.e. this va_arg is guaranteed to have undefined behavior). 15408 QualType PromoteType; 15409 if (TInfo->getType()->isPromotableIntegerType()) { 15410 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15411 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15412 PromoteType = QualType(); 15413 } 15414 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15415 PromoteType = Context.DoubleTy; 15416 if (!PromoteType.isNull()) 15417 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15418 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15419 << TInfo->getType() 15420 << PromoteType 15421 << TInfo->getTypeLoc().getSourceRange()); 15422 } 15423 15424 QualType T = TInfo->getType().getNonLValueExprType(Context); 15425 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15426 } 15427 15428 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15429 // The type of __null will be int or long, depending on the size of 15430 // pointers on the target. 15431 QualType Ty; 15432 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15433 if (pw == Context.getTargetInfo().getIntWidth()) 15434 Ty = Context.IntTy; 15435 else if (pw == Context.getTargetInfo().getLongWidth()) 15436 Ty = Context.LongTy; 15437 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15438 Ty = Context.LongLongTy; 15439 else { 15440 llvm_unreachable("I don't know size of pointer!"); 15441 } 15442 15443 return new (Context) GNUNullExpr(Ty, TokenLoc); 15444 } 15445 15446 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15447 SourceLocation BuiltinLoc, 15448 SourceLocation RPLoc) { 15449 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15450 } 15451 15452 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15453 SourceLocation BuiltinLoc, 15454 SourceLocation RPLoc, 15455 DeclContext *ParentContext) { 15456 return new (Context) 15457 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15458 } 15459 15460 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15461 bool Diagnose) { 15462 if (!getLangOpts().ObjC) 15463 return false; 15464 15465 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15466 if (!PT) 15467 return false; 15468 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15469 15470 // Ignore any parens, implicit casts (should only be 15471 // array-to-pointer decays), and not-so-opaque values. The last is 15472 // important for making this trigger for property assignments. 15473 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15474 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15475 if (OV->getSourceExpr()) 15476 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15477 15478 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15479 if (!PT->isObjCIdType() && 15480 !(ID && ID->getIdentifier()->isStr("NSString"))) 15481 return false; 15482 if (!SL->isAscii()) 15483 return false; 15484 15485 if (Diagnose) { 15486 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15487 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15488 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15489 } 15490 return true; 15491 } 15492 15493 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15494 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15495 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15496 !SrcExpr->isNullPointerConstant( 15497 getASTContext(), Expr::NPC_NeverValueDependent)) { 15498 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15499 return false; 15500 if (Diagnose) { 15501 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15502 << /*number*/1 15503 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15504 Expr *NumLit = 15505 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15506 if (NumLit) 15507 Exp = NumLit; 15508 } 15509 return true; 15510 } 15511 15512 return false; 15513 } 15514 15515 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15516 const Expr *SrcExpr) { 15517 if (!DstType->isFunctionPointerType() || 15518 !SrcExpr->getType()->isFunctionType()) 15519 return false; 15520 15521 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15522 if (!DRE) 15523 return false; 15524 15525 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15526 if (!FD) 15527 return false; 15528 15529 return !S.checkAddressOfFunctionIsAvailable(FD, 15530 /*Complain=*/true, 15531 SrcExpr->getBeginLoc()); 15532 } 15533 15534 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15535 SourceLocation Loc, 15536 QualType DstType, QualType SrcType, 15537 Expr *SrcExpr, AssignmentAction Action, 15538 bool *Complained) { 15539 if (Complained) 15540 *Complained = false; 15541 15542 // Decode the result (notice that AST's are still created for extensions). 15543 bool CheckInferredResultType = false; 15544 bool isInvalid = false; 15545 unsigned DiagKind = 0; 15546 FixItHint Hint; 15547 ConversionFixItGenerator ConvHints; 15548 bool MayHaveConvFixit = false; 15549 bool MayHaveFunctionDiff = false; 15550 const ObjCInterfaceDecl *IFace = nullptr; 15551 const ObjCProtocolDecl *PDecl = nullptr; 15552 15553 switch (ConvTy) { 15554 case Compatible: 15555 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15556 return false; 15557 15558 case PointerToInt: 15559 if (getLangOpts().CPlusPlus) { 15560 DiagKind = diag::err_typecheck_convert_pointer_int; 15561 isInvalid = true; 15562 } else { 15563 DiagKind = diag::ext_typecheck_convert_pointer_int; 15564 } 15565 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15566 MayHaveConvFixit = true; 15567 break; 15568 case IntToPointer: 15569 if (getLangOpts().CPlusPlus) { 15570 DiagKind = diag::err_typecheck_convert_int_pointer; 15571 isInvalid = true; 15572 } else { 15573 DiagKind = diag::ext_typecheck_convert_int_pointer; 15574 } 15575 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15576 MayHaveConvFixit = true; 15577 break; 15578 case IncompatibleFunctionPointer: 15579 if (getLangOpts().CPlusPlus) { 15580 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15581 isInvalid = true; 15582 } else { 15583 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15584 } 15585 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15586 MayHaveConvFixit = true; 15587 break; 15588 case IncompatiblePointer: 15589 if (Action == AA_Passing_CFAudited) { 15590 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15591 } else if (getLangOpts().CPlusPlus) { 15592 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15593 isInvalid = true; 15594 } else { 15595 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15596 } 15597 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15598 SrcType->isObjCObjectPointerType(); 15599 if (Hint.isNull() && !CheckInferredResultType) { 15600 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15601 } 15602 else if (CheckInferredResultType) { 15603 SrcType = SrcType.getUnqualifiedType(); 15604 DstType = DstType.getUnqualifiedType(); 15605 } 15606 MayHaveConvFixit = true; 15607 break; 15608 case IncompatiblePointerSign: 15609 if (getLangOpts().CPlusPlus) { 15610 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15611 isInvalid = true; 15612 } else { 15613 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15614 } 15615 break; 15616 case FunctionVoidPointer: 15617 if (getLangOpts().CPlusPlus) { 15618 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15619 isInvalid = true; 15620 } else { 15621 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15622 } 15623 break; 15624 case IncompatiblePointerDiscardsQualifiers: { 15625 // Perform array-to-pointer decay if necessary. 15626 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15627 15628 isInvalid = true; 15629 15630 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15631 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15632 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15633 DiagKind = diag::err_typecheck_incompatible_address_space; 15634 break; 15635 15636 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15637 DiagKind = diag::err_typecheck_incompatible_ownership; 15638 break; 15639 } 15640 15641 llvm_unreachable("unknown error case for discarding qualifiers!"); 15642 // fallthrough 15643 } 15644 case CompatiblePointerDiscardsQualifiers: 15645 // If the qualifiers lost were because we were applying the 15646 // (deprecated) C++ conversion from a string literal to a char* 15647 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15648 // Ideally, this check would be performed in 15649 // checkPointerTypesForAssignment. However, that would require a 15650 // bit of refactoring (so that the second argument is an 15651 // expression, rather than a type), which should be done as part 15652 // of a larger effort to fix checkPointerTypesForAssignment for 15653 // C++ semantics. 15654 if (getLangOpts().CPlusPlus && 15655 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15656 return false; 15657 if (getLangOpts().CPlusPlus) { 15658 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15659 isInvalid = true; 15660 } else { 15661 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15662 } 15663 15664 break; 15665 case IncompatibleNestedPointerQualifiers: 15666 if (getLangOpts().CPlusPlus) { 15667 isInvalid = true; 15668 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15669 } else { 15670 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15671 } 15672 break; 15673 case IncompatibleNestedPointerAddressSpaceMismatch: 15674 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15675 isInvalid = true; 15676 break; 15677 case IntToBlockPointer: 15678 DiagKind = diag::err_int_to_block_pointer; 15679 isInvalid = true; 15680 break; 15681 case IncompatibleBlockPointer: 15682 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15683 isInvalid = true; 15684 break; 15685 case IncompatibleObjCQualifiedId: { 15686 if (SrcType->isObjCQualifiedIdType()) { 15687 const ObjCObjectPointerType *srcOPT = 15688 SrcType->castAs<ObjCObjectPointerType>(); 15689 for (auto *srcProto : srcOPT->quals()) { 15690 PDecl = srcProto; 15691 break; 15692 } 15693 if (const ObjCInterfaceType *IFaceT = 15694 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15695 IFace = IFaceT->getDecl(); 15696 } 15697 else if (DstType->isObjCQualifiedIdType()) { 15698 const ObjCObjectPointerType *dstOPT = 15699 DstType->castAs<ObjCObjectPointerType>(); 15700 for (auto *dstProto : dstOPT->quals()) { 15701 PDecl = dstProto; 15702 break; 15703 } 15704 if (const ObjCInterfaceType *IFaceT = 15705 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15706 IFace = IFaceT->getDecl(); 15707 } 15708 if (getLangOpts().CPlusPlus) { 15709 DiagKind = diag::err_incompatible_qualified_id; 15710 isInvalid = true; 15711 } else { 15712 DiagKind = diag::warn_incompatible_qualified_id; 15713 } 15714 break; 15715 } 15716 case IncompatibleVectors: 15717 if (getLangOpts().CPlusPlus) { 15718 DiagKind = diag::err_incompatible_vectors; 15719 isInvalid = true; 15720 } else { 15721 DiagKind = diag::warn_incompatible_vectors; 15722 } 15723 break; 15724 case IncompatibleObjCWeakRef: 15725 DiagKind = diag::err_arc_weak_unavailable_assign; 15726 isInvalid = true; 15727 break; 15728 case Incompatible: 15729 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15730 if (Complained) 15731 *Complained = true; 15732 return true; 15733 } 15734 15735 DiagKind = diag::err_typecheck_convert_incompatible; 15736 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15737 MayHaveConvFixit = true; 15738 isInvalid = true; 15739 MayHaveFunctionDiff = true; 15740 break; 15741 } 15742 15743 QualType FirstType, SecondType; 15744 switch (Action) { 15745 case AA_Assigning: 15746 case AA_Initializing: 15747 // The destination type comes first. 15748 FirstType = DstType; 15749 SecondType = SrcType; 15750 break; 15751 15752 case AA_Returning: 15753 case AA_Passing: 15754 case AA_Passing_CFAudited: 15755 case AA_Converting: 15756 case AA_Sending: 15757 case AA_Casting: 15758 // The source type comes first. 15759 FirstType = SrcType; 15760 SecondType = DstType; 15761 break; 15762 } 15763 15764 PartialDiagnostic FDiag = PDiag(DiagKind); 15765 if (Action == AA_Passing_CFAudited) 15766 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15767 else 15768 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15769 15770 // If we can fix the conversion, suggest the FixIts. 15771 assert(ConvHints.isNull() || Hint.isNull()); 15772 if (!ConvHints.isNull()) { 15773 for (FixItHint &H : ConvHints.Hints) 15774 FDiag << H; 15775 } else { 15776 FDiag << Hint; 15777 } 15778 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15779 15780 if (MayHaveFunctionDiff) 15781 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15782 15783 Diag(Loc, FDiag); 15784 if ((DiagKind == diag::warn_incompatible_qualified_id || 15785 DiagKind == diag::err_incompatible_qualified_id) && 15786 PDecl && IFace && !IFace->hasDefinition()) 15787 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15788 << IFace << PDecl; 15789 15790 if (SecondType == Context.OverloadTy) 15791 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15792 FirstType, /*TakingAddress=*/true); 15793 15794 if (CheckInferredResultType) 15795 EmitRelatedResultTypeNote(SrcExpr); 15796 15797 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15798 EmitRelatedResultTypeNoteForReturn(DstType); 15799 15800 if (Complained) 15801 *Complained = true; 15802 return isInvalid; 15803 } 15804 15805 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15806 llvm::APSInt *Result) { 15807 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15808 public: 15809 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15810 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15811 } 15812 } Diagnoser; 15813 15814 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15815 } 15816 15817 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15818 llvm::APSInt *Result, 15819 unsigned DiagID, 15820 bool AllowFold) { 15821 class IDDiagnoser : public VerifyICEDiagnoser { 15822 unsigned DiagID; 15823 15824 public: 15825 IDDiagnoser(unsigned DiagID) 15826 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15827 15828 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15829 S.Diag(Loc, DiagID) << SR; 15830 } 15831 } Diagnoser(DiagID); 15832 15833 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15834 } 15835 15836 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15837 SourceRange SR) { 15838 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15839 } 15840 15841 ExprResult 15842 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15843 VerifyICEDiagnoser &Diagnoser, 15844 bool AllowFold) { 15845 SourceLocation DiagLoc = E->getBeginLoc(); 15846 15847 if (getLangOpts().CPlusPlus11) { 15848 // C++11 [expr.const]p5: 15849 // If an expression of literal class type is used in a context where an 15850 // integral constant expression is required, then that class type shall 15851 // have a single non-explicit conversion function to an integral or 15852 // unscoped enumeration type 15853 ExprResult Converted; 15854 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15855 public: 15856 CXX11ConvertDiagnoser(bool Silent) 15857 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15858 Silent, true) {} 15859 15860 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15861 QualType T) override { 15862 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15863 } 15864 15865 SemaDiagnosticBuilder diagnoseIncomplete( 15866 Sema &S, SourceLocation Loc, QualType T) override { 15867 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15868 } 15869 15870 SemaDiagnosticBuilder diagnoseExplicitConv( 15871 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15872 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15873 } 15874 15875 SemaDiagnosticBuilder noteExplicitConv( 15876 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15877 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15878 << ConvTy->isEnumeralType() << ConvTy; 15879 } 15880 15881 SemaDiagnosticBuilder diagnoseAmbiguous( 15882 Sema &S, SourceLocation Loc, QualType T) override { 15883 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15884 } 15885 15886 SemaDiagnosticBuilder noteAmbiguous( 15887 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15888 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15889 << ConvTy->isEnumeralType() << ConvTy; 15890 } 15891 15892 SemaDiagnosticBuilder diagnoseConversion( 15893 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15894 llvm_unreachable("conversion functions are permitted"); 15895 } 15896 } ConvertDiagnoser(Diagnoser.Suppress); 15897 15898 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15899 ConvertDiagnoser); 15900 if (Converted.isInvalid()) 15901 return Converted; 15902 E = Converted.get(); 15903 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15904 return ExprError(); 15905 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15906 // An ICE must be of integral or unscoped enumeration type. 15907 if (!Diagnoser.Suppress) 15908 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15909 return ExprError(); 15910 } 15911 15912 ExprResult RValueExpr = DefaultLvalueConversion(E); 15913 if (RValueExpr.isInvalid()) 15914 return ExprError(); 15915 15916 E = RValueExpr.get(); 15917 15918 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15919 // in the non-ICE case. 15920 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15921 if (Result) 15922 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15923 if (!isa<ConstantExpr>(E)) 15924 E = ConstantExpr::Create(Context, E); 15925 return E; 15926 } 15927 15928 Expr::EvalResult EvalResult; 15929 SmallVector<PartialDiagnosticAt, 8> Notes; 15930 EvalResult.Diag = &Notes; 15931 15932 // Try to evaluate the expression, and produce diagnostics explaining why it's 15933 // not a constant expression as a side-effect. 15934 bool Folded = 15935 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15936 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15937 15938 if (!isa<ConstantExpr>(E)) 15939 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15940 15941 // In C++11, we can rely on diagnostics being produced for any expression 15942 // which is not a constant expression. If no diagnostics were produced, then 15943 // this is a constant expression. 15944 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15945 if (Result) 15946 *Result = EvalResult.Val.getInt(); 15947 return E; 15948 } 15949 15950 // If our only note is the usual "invalid subexpression" note, just point 15951 // the caret at its location rather than producing an essentially 15952 // redundant note. 15953 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15954 diag::note_invalid_subexpr_in_const_expr) { 15955 DiagLoc = Notes[0].first; 15956 Notes.clear(); 15957 } 15958 15959 if (!Folded || !AllowFold) { 15960 if (!Diagnoser.Suppress) { 15961 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15962 for (const PartialDiagnosticAt &Note : Notes) 15963 Diag(Note.first, Note.second); 15964 } 15965 15966 return ExprError(); 15967 } 15968 15969 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15970 for (const PartialDiagnosticAt &Note : Notes) 15971 Diag(Note.first, Note.second); 15972 15973 if (Result) 15974 *Result = EvalResult.Val.getInt(); 15975 return E; 15976 } 15977 15978 namespace { 15979 // Handle the case where we conclude a expression which we speculatively 15980 // considered to be unevaluated is actually evaluated. 15981 class TransformToPE : public TreeTransform<TransformToPE> { 15982 typedef TreeTransform<TransformToPE> BaseTransform; 15983 15984 public: 15985 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15986 15987 // Make sure we redo semantic analysis 15988 bool AlwaysRebuild() { return true; } 15989 bool ReplacingOriginal() { return true; } 15990 15991 // We need to special-case DeclRefExprs referring to FieldDecls which 15992 // are not part of a member pointer formation; normal TreeTransforming 15993 // doesn't catch this case because of the way we represent them in the AST. 15994 // FIXME: This is a bit ugly; is it really the best way to handle this 15995 // case? 15996 // 15997 // Error on DeclRefExprs referring to FieldDecls. 15998 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15999 if (isa<FieldDecl>(E->getDecl()) && 16000 !SemaRef.isUnevaluatedContext()) 16001 return SemaRef.Diag(E->getLocation(), 16002 diag::err_invalid_non_static_member_use) 16003 << E->getDecl() << E->getSourceRange(); 16004 16005 return BaseTransform::TransformDeclRefExpr(E); 16006 } 16007 16008 // Exception: filter out member pointer formation 16009 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16010 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16011 return E; 16012 16013 return BaseTransform::TransformUnaryOperator(E); 16014 } 16015 16016 // The body of a lambda-expression is in a separate expression evaluation 16017 // context so never needs to be transformed. 16018 // FIXME: Ideally we wouldn't transform the closure type either, and would 16019 // just recreate the capture expressions and lambda expression. 16020 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16021 return SkipLambdaBody(E, Body); 16022 } 16023 }; 16024 } 16025 16026 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16027 assert(isUnevaluatedContext() && 16028 "Should only transform unevaluated expressions"); 16029 ExprEvalContexts.back().Context = 16030 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16031 if (isUnevaluatedContext()) 16032 return E; 16033 return TransformToPE(*this).TransformExpr(E); 16034 } 16035 16036 void 16037 Sema::PushExpressionEvaluationContext( 16038 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16039 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16040 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16041 LambdaContextDecl, ExprContext); 16042 Cleanup.reset(); 16043 if (!MaybeODRUseExprs.empty()) 16044 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16045 } 16046 16047 void 16048 Sema::PushExpressionEvaluationContext( 16049 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16050 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16051 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16052 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16053 } 16054 16055 namespace { 16056 16057 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16058 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16059 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16060 if (E->getOpcode() == UO_Deref) 16061 return CheckPossibleDeref(S, E->getSubExpr()); 16062 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16063 return CheckPossibleDeref(S, E->getBase()); 16064 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16065 return CheckPossibleDeref(S, E->getBase()); 16066 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16067 QualType Inner; 16068 QualType Ty = E->getType(); 16069 if (const auto *Ptr = Ty->getAs<PointerType>()) 16070 Inner = Ptr->getPointeeType(); 16071 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16072 Inner = Arr->getElementType(); 16073 else 16074 return nullptr; 16075 16076 if (Inner->hasAttr(attr::NoDeref)) 16077 return E; 16078 } 16079 return nullptr; 16080 } 16081 16082 } // namespace 16083 16084 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16085 for (const Expr *E : Rec.PossibleDerefs) { 16086 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16087 if (DeclRef) { 16088 const ValueDecl *Decl = DeclRef->getDecl(); 16089 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16090 << Decl->getName() << E->getSourceRange(); 16091 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16092 } else { 16093 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16094 << E->getSourceRange(); 16095 } 16096 } 16097 Rec.PossibleDerefs.clear(); 16098 } 16099 16100 /// Check whether E, which is either a discarded-value expression or an 16101 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16102 /// and if so, remove it from the list of volatile-qualified assignments that 16103 /// we are going to warn are deprecated. 16104 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16105 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16106 return; 16107 16108 // Note: ignoring parens here is not justified by the standard rules, but 16109 // ignoring parentheses seems like a more reasonable approach, and this only 16110 // drives a deprecation warning so doesn't affect conformance. 16111 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16112 if (BO->getOpcode() == BO_Assign) { 16113 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16114 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16115 LHSs.end()); 16116 } 16117 } 16118 } 16119 16120 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16121 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16122 RebuildingImmediateInvocation) 16123 return E; 16124 16125 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16126 /// It's OK if this fails; we'll also remove this in 16127 /// HandleImmediateInvocations, but catching it here allows us to avoid 16128 /// walking the AST looking for it in simple cases. 16129 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16130 if (auto *DeclRef = 16131 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16132 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16133 16134 E = MaybeCreateExprWithCleanups(E); 16135 16136 ConstantExpr *Res = ConstantExpr::Create( 16137 getASTContext(), E.get(), 16138 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16139 getASTContext()), 16140 /*IsImmediateInvocation*/ true); 16141 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16142 return Res; 16143 } 16144 16145 static void EvaluateAndDiagnoseImmediateInvocation( 16146 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16147 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16148 Expr::EvalResult Eval; 16149 Eval.Diag = &Notes; 16150 ConstantExpr *CE = Candidate.getPointer(); 16151 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 16152 SemaRef.getASTContext(), true); 16153 if (!Result || !Notes.empty()) { 16154 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16155 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16156 InnerExpr = FunctionalCast->getSubExpr(); 16157 FunctionDecl *FD = nullptr; 16158 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16159 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16160 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16161 FD = Call->getConstructor(); 16162 else 16163 llvm_unreachable("unhandled decl kind"); 16164 assert(FD->isConsteval()); 16165 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16166 for (auto &Note : Notes) 16167 SemaRef.Diag(Note.first, Note.second); 16168 return; 16169 } 16170 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16171 } 16172 16173 static void RemoveNestedImmediateInvocation( 16174 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16175 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16176 struct ComplexRemove : TreeTransform<ComplexRemove> { 16177 using Base = TreeTransform<ComplexRemove>; 16178 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16179 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16180 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16181 CurrentII; 16182 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16183 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16184 SmallVector<Sema::ImmediateInvocationCandidate, 16185 4>::reverse_iterator Current) 16186 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16187 void RemoveImmediateInvocation(ConstantExpr* E) { 16188 auto It = std::find_if(CurrentII, IISet.rend(), 16189 [E](Sema::ImmediateInvocationCandidate Elem) { 16190 return Elem.getPointer() == E; 16191 }); 16192 assert(It != IISet.rend() && 16193 "ConstantExpr marked IsImmediateInvocation should " 16194 "be present"); 16195 It->setInt(1); // Mark as deleted 16196 } 16197 ExprResult TransformConstantExpr(ConstantExpr *E) { 16198 if (!E->isImmediateInvocation()) 16199 return Base::TransformConstantExpr(E); 16200 RemoveImmediateInvocation(E); 16201 return Base::TransformExpr(E->getSubExpr()); 16202 } 16203 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16204 /// we need to remove its DeclRefExpr from the DRSet. 16205 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16206 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16207 return Base::TransformCXXOperatorCallExpr(E); 16208 } 16209 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16210 /// here. 16211 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16212 if (!Init) 16213 return Init; 16214 /// ConstantExpr are the first layer of implicit node to be removed so if 16215 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16216 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16217 if (CE->isImmediateInvocation()) 16218 RemoveImmediateInvocation(CE); 16219 return Base::TransformInitializer(Init, NotCopyInit); 16220 } 16221 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16222 DRSet.erase(E); 16223 return E; 16224 } 16225 bool AlwaysRebuild() { return false; } 16226 bool ReplacingOriginal() { return true; } 16227 bool AllowSkippingCXXConstructExpr() { 16228 bool Res = AllowSkippingFirstCXXConstructExpr; 16229 AllowSkippingFirstCXXConstructExpr = true; 16230 return Res; 16231 } 16232 bool AllowSkippingFirstCXXConstructExpr = true; 16233 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16234 Rec.ImmediateInvocationCandidates, It); 16235 16236 /// CXXConstructExpr with a single argument are getting skipped by 16237 /// TreeTransform in some situtation because they could be implicit. This 16238 /// can only occur for the top-level CXXConstructExpr because it is used 16239 /// nowhere in the expression being transformed therefore will not be rebuilt. 16240 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16241 /// skipping the first CXXConstructExpr. 16242 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16243 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16244 16245 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16246 assert(Res.isUsable()); 16247 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16248 It->getPointer()->setSubExpr(Res.get()); 16249 } 16250 16251 static void 16252 HandleImmediateInvocations(Sema &SemaRef, 16253 Sema::ExpressionEvaluationContextRecord &Rec) { 16254 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16255 Rec.ReferenceToConsteval.size() == 0) || 16256 SemaRef.RebuildingImmediateInvocation) 16257 return; 16258 16259 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16260 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16261 /// need to remove ReferenceToConsteval in the immediate invocation. 16262 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16263 16264 /// Prevent sema calls during the tree transform from adding pointers that 16265 /// are already in the sets. 16266 llvm::SaveAndRestore<bool> DisableIITracking( 16267 SemaRef.RebuildingImmediateInvocation, true); 16268 16269 /// Prevent diagnostic during tree transfrom as they are duplicates 16270 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16271 16272 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16273 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16274 if (!It->getInt()) 16275 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16276 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16277 Rec.ReferenceToConsteval.size()) { 16278 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16279 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16280 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16281 bool VisitDeclRefExpr(DeclRefExpr *E) { 16282 DRSet.erase(E); 16283 return DRSet.size(); 16284 } 16285 } Visitor(Rec.ReferenceToConsteval); 16286 Visitor.TraverseStmt( 16287 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16288 } 16289 for (auto CE : Rec.ImmediateInvocationCandidates) 16290 if (!CE.getInt()) 16291 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16292 for (auto DR : Rec.ReferenceToConsteval) { 16293 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16294 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16295 << FD; 16296 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16297 } 16298 } 16299 16300 void Sema::PopExpressionEvaluationContext() { 16301 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16302 unsigned NumTypos = Rec.NumTypos; 16303 16304 if (!Rec.Lambdas.empty()) { 16305 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16306 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16307 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16308 unsigned D; 16309 if (Rec.isUnevaluated()) { 16310 // C++11 [expr.prim.lambda]p2: 16311 // A lambda-expression shall not appear in an unevaluated operand 16312 // (Clause 5). 16313 D = diag::err_lambda_unevaluated_operand; 16314 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16315 // C++1y [expr.const]p2: 16316 // A conditional-expression e is a core constant expression unless the 16317 // evaluation of e, following the rules of the abstract machine, would 16318 // evaluate [...] a lambda-expression. 16319 D = diag::err_lambda_in_constant_expression; 16320 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16321 // C++17 [expr.prim.lamda]p2: 16322 // A lambda-expression shall not appear [...] in a template-argument. 16323 D = diag::err_lambda_in_invalid_context; 16324 } else 16325 llvm_unreachable("Couldn't infer lambda error message."); 16326 16327 for (const auto *L : Rec.Lambdas) 16328 Diag(L->getBeginLoc(), D); 16329 } 16330 } 16331 16332 WarnOnPendingNoDerefs(Rec); 16333 HandleImmediateInvocations(*this, Rec); 16334 16335 // Warn on any volatile-qualified simple-assignments that are not discarded- 16336 // value expressions nor unevaluated operands (those cases get removed from 16337 // this list by CheckUnusedVolatileAssignment). 16338 for (auto *BO : Rec.VolatileAssignmentLHSs) 16339 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16340 << BO->getType(); 16341 16342 // When are coming out of an unevaluated context, clear out any 16343 // temporaries that we may have created as part of the evaluation of 16344 // the expression in that context: they aren't relevant because they 16345 // will never be constructed. 16346 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16347 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16348 ExprCleanupObjects.end()); 16349 Cleanup = Rec.ParentCleanup; 16350 CleanupVarDeclMarking(); 16351 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16352 // Otherwise, merge the contexts together. 16353 } else { 16354 Cleanup.mergeFrom(Rec.ParentCleanup); 16355 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16356 Rec.SavedMaybeODRUseExprs.end()); 16357 } 16358 16359 // Pop the current expression evaluation context off the stack. 16360 ExprEvalContexts.pop_back(); 16361 16362 // The global expression evaluation context record is never popped. 16363 ExprEvalContexts.back().NumTypos += NumTypos; 16364 } 16365 16366 void Sema::DiscardCleanupsInEvaluationContext() { 16367 ExprCleanupObjects.erase( 16368 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16369 ExprCleanupObjects.end()); 16370 Cleanup.reset(); 16371 MaybeODRUseExprs.clear(); 16372 } 16373 16374 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16375 ExprResult Result = CheckPlaceholderExpr(E); 16376 if (Result.isInvalid()) 16377 return ExprError(); 16378 E = Result.get(); 16379 if (!E->getType()->isVariablyModifiedType()) 16380 return E; 16381 return TransformToPotentiallyEvaluated(E); 16382 } 16383 16384 /// Are we in a context that is potentially constant evaluated per C++20 16385 /// [expr.const]p12? 16386 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16387 /// C++2a [expr.const]p12: 16388 // An expression or conversion is potentially constant evaluated if it is 16389 switch (SemaRef.ExprEvalContexts.back().Context) { 16390 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16391 // -- a manifestly constant-evaluated expression, 16392 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16393 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16394 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16395 // -- a potentially-evaluated expression, 16396 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16397 // -- an immediate subexpression of a braced-init-list, 16398 16399 // -- [FIXME] an expression of the form & cast-expression that occurs 16400 // within a templated entity 16401 // -- a subexpression of one of the above that is not a subexpression of 16402 // a nested unevaluated operand. 16403 return true; 16404 16405 case Sema::ExpressionEvaluationContext::Unevaluated: 16406 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16407 // Expressions in this context are never evaluated. 16408 return false; 16409 } 16410 llvm_unreachable("Invalid context"); 16411 } 16412 16413 /// Return true if this function has a calling convention that requires mangling 16414 /// in the size of the parameter pack. 16415 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16416 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16417 // we don't need parameter type sizes. 16418 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16419 if (!TT.isOSWindows() || !TT.isX86()) 16420 return false; 16421 16422 // If this is C++ and this isn't an extern "C" function, parameters do not 16423 // need to be complete. In this case, C++ mangling will apply, which doesn't 16424 // use the size of the parameters. 16425 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16426 return false; 16427 16428 // Stdcall, fastcall, and vectorcall need this special treatment. 16429 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16430 switch (CC) { 16431 case CC_X86StdCall: 16432 case CC_X86FastCall: 16433 case CC_X86VectorCall: 16434 return true; 16435 default: 16436 break; 16437 } 16438 return false; 16439 } 16440 16441 /// Require that all of the parameter types of function be complete. Normally, 16442 /// parameter types are only required to be complete when a function is called 16443 /// or defined, but to mangle functions with certain calling conventions, the 16444 /// mangler needs to know the size of the parameter list. In this situation, 16445 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16446 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16447 /// result in a linker error. Clang doesn't implement this behavior, and instead 16448 /// attempts to error at compile time. 16449 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16450 SourceLocation Loc) { 16451 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16452 FunctionDecl *FD; 16453 ParmVarDecl *Param; 16454 16455 public: 16456 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16457 : FD(FD), Param(Param) {} 16458 16459 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16460 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16461 StringRef CCName; 16462 switch (CC) { 16463 case CC_X86StdCall: 16464 CCName = "stdcall"; 16465 break; 16466 case CC_X86FastCall: 16467 CCName = "fastcall"; 16468 break; 16469 case CC_X86VectorCall: 16470 CCName = "vectorcall"; 16471 break; 16472 default: 16473 llvm_unreachable("CC does not need mangling"); 16474 } 16475 16476 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16477 << Param->getDeclName() << FD->getDeclName() << CCName; 16478 } 16479 }; 16480 16481 for (ParmVarDecl *Param : FD->parameters()) { 16482 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16483 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16484 } 16485 } 16486 16487 namespace { 16488 enum class OdrUseContext { 16489 /// Declarations in this context are not odr-used. 16490 None, 16491 /// Declarations in this context are formally odr-used, but this is a 16492 /// dependent context. 16493 Dependent, 16494 /// Declarations in this context are odr-used but not actually used (yet). 16495 FormallyOdrUsed, 16496 /// Declarations in this context are used. 16497 Used 16498 }; 16499 } 16500 16501 /// Are we within a context in which references to resolved functions or to 16502 /// variables result in odr-use? 16503 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16504 OdrUseContext Result; 16505 16506 switch (SemaRef.ExprEvalContexts.back().Context) { 16507 case Sema::ExpressionEvaluationContext::Unevaluated: 16508 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16509 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16510 return OdrUseContext::None; 16511 16512 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16513 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16514 Result = OdrUseContext::Used; 16515 break; 16516 16517 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16518 Result = OdrUseContext::FormallyOdrUsed; 16519 break; 16520 16521 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16522 // A default argument formally results in odr-use, but doesn't actually 16523 // result in a use in any real sense until it itself is used. 16524 Result = OdrUseContext::FormallyOdrUsed; 16525 break; 16526 } 16527 16528 if (SemaRef.CurContext->isDependentContext()) 16529 return OdrUseContext::Dependent; 16530 16531 return Result; 16532 } 16533 16534 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16535 return Func->isConstexpr() && 16536 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 16537 } 16538 16539 /// Mark a function referenced, and check whether it is odr-used 16540 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16541 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16542 bool MightBeOdrUse) { 16543 assert(Func && "No function?"); 16544 16545 Func->setReferenced(); 16546 16547 // Recursive functions aren't really used until they're used from some other 16548 // context. 16549 bool IsRecursiveCall = CurContext == Func; 16550 16551 // C++11 [basic.def.odr]p3: 16552 // A function whose name appears as a potentially-evaluated expression is 16553 // odr-used if it is the unique lookup result or the selected member of a 16554 // set of overloaded functions [...]. 16555 // 16556 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16557 // can just check that here. 16558 OdrUseContext OdrUse = 16559 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16560 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16561 OdrUse = OdrUseContext::FormallyOdrUsed; 16562 16563 // Trivial default constructors and destructors are never actually used. 16564 // FIXME: What about other special members? 16565 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16566 OdrUse == OdrUseContext::Used) { 16567 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16568 if (Constructor->isDefaultConstructor()) 16569 OdrUse = OdrUseContext::FormallyOdrUsed; 16570 if (isa<CXXDestructorDecl>(Func)) 16571 OdrUse = OdrUseContext::FormallyOdrUsed; 16572 } 16573 16574 // C++20 [expr.const]p12: 16575 // A function [...] is needed for constant evaluation if it is [...] a 16576 // constexpr function that is named by an expression that is potentially 16577 // constant evaluated 16578 bool NeededForConstantEvaluation = 16579 isPotentiallyConstantEvaluatedContext(*this) && 16580 isImplicitlyDefinableConstexprFunction(Func); 16581 16582 // Determine whether we require a function definition to exist, per 16583 // C++11 [temp.inst]p3: 16584 // Unless a function template specialization has been explicitly 16585 // instantiated or explicitly specialized, the function template 16586 // specialization is implicitly instantiated when the specialization is 16587 // referenced in a context that requires a function definition to exist. 16588 // C++20 [temp.inst]p7: 16589 // The existence of a definition of a [...] function is considered to 16590 // affect the semantics of the program if the [...] function is needed for 16591 // constant evaluation by an expression 16592 // C++20 [basic.def.odr]p10: 16593 // Every program shall contain exactly one definition of every non-inline 16594 // function or variable that is odr-used in that program outside of a 16595 // discarded statement 16596 // C++20 [special]p1: 16597 // The implementation will implicitly define [defaulted special members] 16598 // if they are odr-used or needed for constant evaluation. 16599 // 16600 // Note that we skip the implicit instantiation of templates that are only 16601 // used in unused default arguments or by recursive calls to themselves. 16602 // This is formally non-conforming, but seems reasonable in practice. 16603 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16604 NeededForConstantEvaluation); 16605 16606 // C++14 [temp.expl.spec]p6: 16607 // If a template [...] is explicitly specialized then that specialization 16608 // shall be declared before the first use of that specialization that would 16609 // cause an implicit instantiation to take place, in every translation unit 16610 // in which such a use occurs 16611 if (NeedDefinition && 16612 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16613 Func->getMemberSpecializationInfo())) 16614 checkSpecializationVisibility(Loc, Func); 16615 16616 if (getLangOpts().CUDA) 16617 CheckCUDACall(Loc, Func); 16618 16619 if (getLangOpts().SYCLIsDevice) 16620 checkSYCLDeviceFunction(Loc, Func); 16621 16622 // If we need a definition, try to create one. 16623 if (NeedDefinition && !Func->getBody()) { 16624 runWithSufficientStackSpace(Loc, [&] { 16625 if (CXXConstructorDecl *Constructor = 16626 dyn_cast<CXXConstructorDecl>(Func)) { 16627 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16628 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16629 if (Constructor->isDefaultConstructor()) { 16630 if (Constructor->isTrivial() && 16631 !Constructor->hasAttr<DLLExportAttr>()) 16632 return; 16633 DefineImplicitDefaultConstructor(Loc, Constructor); 16634 } else if (Constructor->isCopyConstructor()) { 16635 DefineImplicitCopyConstructor(Loc, Constructor); 16636 } else if (Constructor->isMoveConstructor()) { 16637 DefineImplicitMoveConstructor(Loc, Constructor); 16638 } 16639 } else if (Constructor->getInheritedConstructor()) { 16640 DefineInheritingConstructor(Loc, Constructor); 16641 } 16642 } else if (CXXDestructorDecl *Destructor = 16643 dyn_cast<CXXDestructorDecl>(Func)) { 16644 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16645 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16646 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16647 return; 16648 DefineImplicitDestructor(Loc, Destructor); 16649 } 16650 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16651 MarkVTableUsed(Loc, Destructor->getParent()); 16652 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16653 if (MethodDecl->isOverloadedOperator() && 16654 MethodDecl->getOverloadedOperator() == OO_Equal) { 16655 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16656 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16657 if (MethodDecl->isCopyAssignmentOperator()) 16658 DefineImplicitCopyAssignment(Loc, MethodDecl); 16659 else if (MethodDecl->isMoveAssignmentOperator()) 16660 DefineImplicitMoveAssignment(Loc, MethodDecl); 16661 } 16662 } else if (isa<CXXConversionDecl>(MethodDecl) && 16663 MethodDecl->getParent()->isLambda()) { 16664 CXXConversionDecl *Conversion = 16665 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16666 if (Conversion->isLambdaToBlockPointerConversion()) 16667 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16668 else 16669 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16670 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16671 MarkVTableUsed(Loc, MethodDecl->getParent()); 16672 } 16673 16674 if (Func->isDefaulted() && !Func->isDeleted()) { 16675 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16676 if (DCK != DefaultedComparisonKind::None) 16677 DefineDefaultedComparison(Loc, Func, DCK); 16678 } 16679 16680 // Implicit instantiation of function templates and member functions of 16681 // class templates. 16682 if (Func->isImplicitlyInstantiable()) { 16683 TemplateSpecializationKind TSK = 16684 Func->getTemplateSpecializationKindForInstantiation(); 16685 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16686 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16687 if (FirstInstantiation) { 16688 PointOfInstantiation = Loc; 16689 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16690 } else if (TSK != TSK_ImplicitInstantiation) { 16691 // Use the point of use as the point of instantiation, instead of the 16692 // point of explicit instantiation (which we track as the actual point 16693 // of instantiation). This gives better backtraces in diagnostics. 16694 PointOfInstantiation = Loc; 16695 } 16696 16697 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16698 Func->isConstexpr()) { 16699 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16700 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16701 CodeSynthesisContexts.size()) 16702 PendingLocalImplicitInstantiations.push_back( 16703 std::make_pair(Func, PointOfInstantiation)); 16704 else if (Func->isConstexpr()) 16705 // Do not defer instantiations of constexpr functions, to avoid the 16706 // expression evaluator needing to call back into Sema if it sees a 16707 // call to such a function. 16708 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16709 else { 16710 Func->setInstantiationIsPending(true); 16711 PendingInstantiations.push_back( 16712 std::make_pair(Func, PointOfInstantiation)); 16713 // Notify the consumer that a function was implicitly instantiated. 16714 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16715 } 16716 } 16717 } else { 16718 // Walk redefinitions, as some of them may be instantiable. 16719 for (auto i : Func->redecls()) { 16720 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16721 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16722 } 16723 } 16724 }); 16725 } 16726 16727 // C++14 [except.spec]p17: 16728 // An exception-specification is considered to be needed when: 16729 // - the function is odr-used or, if it appears in an unevaluated operand, 16730 // would be odr-used if the expression were potentially-evaluated; 16731 // 16732 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16733 // function is a pure virtual function we're calling, and in that case the 16734 // function was selected by overload resolution and we need to resolve its 16735 // exception specification for a different reason. 16736 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16737 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16738 ResolveExceptionSpec(Loc, FPT); 16739 16740 // If this is the first "real" use, act on that. 16741 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16742 // Keep track of used but undefined functions. 16743 if (!Func->isDefined()) { 16744 if (mightHaveNonExternalLinkage(Func)) 16745 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16746 else if (Func->getMostRecentDecl()->isInlined() && 16747 !LangOpts.GNUInline && 16748 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16749 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16750 else if (isExternalWithNoLinkageType(Func)) 16751 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16752 } 16753 16754 // Some x86 Windows calling conventions mangle the size of the parameter 16755 // pack into the name. Computing the size of the parameters requires the 16756 // parameter types to be complete. Check that now. 16757 if (funcHasParameterSizeMangling(*this, Func)) 16758 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16759 16760 // In the MS C++ ABI, the compiler emits destructor variants where they are 16761 // used. If the destructor is used here but defined elsewhere, mark the 16762 // virtual base destructors referenced. If those virtual base destructors 16763 // are inline, this will ensure they are defined when emitting the complete 16764 // destructor variant. This checking may be redundant if the destructor is 16765 // provided later in this TU. 16766 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16767 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16768 CXXRecordDecl *Parent = Dtor->getParent(); 16769 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16770 CheckCompleteDestructorVariant(Loc, Dtor); 16771 } 16772 } 16773 16774 Func->markUsed(Context); 16775 } 16776 } 16777 16778 /// Directly mark a variable odr-used. Given a choice, prefer to use 16779 /// MarkVariableReferenced since it does additional checks and then 16780 /// calls MarkVarDeclODRUsed. 16781 /// If the variable must be captured: 16782 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16783 /// - else capture it in the DeclContext that maps to the 16784 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16785 static void 16786 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16787 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16788 // Keep track of used but undefined variables. 16789 // FIXME: We shouldn't suppress this warning for static data members. 16790 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16791 (!Var->isExternallyVisible() || Var->isInline() || 16792 SemaRef.isExternalWithNoLinkageType(Var)) && 16793 !(Var->isStaticDataMember() && Var->hasInit())) { 16794 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16795 if (old.isInvalid()) 16796 old = Loc; 16797 } 16798 QualType CaptureType, DeclRefType; 16799 if (SemaRef.LangOpts.OpenMP) 16800 SemaRef.tryCaptureOpenMPLambdas(Var); 16801 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16802 /*EllipsisLoc*/ SourceLocation(), 16803 /*BuildAndDiagnose*/ true, 16804 CaptureType, DeclRefType, 16805 FunctionScopeIndexToStopAt); 16806 16807 Var->markUsed(SemaRef.Context); 16808 } 16809 16810 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16811 SourceLocation Loc, 16812 unsigned CapturingScopeIndex) { 16813 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16814 } 16815 16816 static void 16817 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16818 ValueDecl *var, DeclContext *DC) { 16819 DeclContext *VarDC = var->getDeclContext(); 16820 16821 // If the parameter still belongs to the translation unit, then 16822 // we're actually just using one parameter in the declaration of 16823 // the next. 16824 if (isa<ParmVarDecl>(var) && 16825 isa<TranslationUnitDecl>(VarDC)) 16826 return; 16827 16828 // For C code, don't diagnose about capture if we're not actually in code 16829 // right now; it's impossible to write a non-constant expression outside of 16830 // function context, so we'll get other (more useful) diagnostics later. 16831 // 16832 // For C++, things get a bit more nasty... it would be nice to suppress this 16833 // diagnostic for certain cases like using a local variable in an array bound 16834 // for a member of a local class, but the correct predicate is not obvious. 16835 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16836 return; 16837 16838 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16839 unsigned ContextKind = 3; // unknown 16840 if (isa<CXXMethodDecl>(VarDC) && 16841 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16842 ContextKind = 2; 16843 } else if (isa<FunctionDecl>(VarDC)) { 16844 ContextKind = 0; 16845 } else if (isa<BlockDecl>(VarDC)) { 16846 ContextKind = 1; 16847 } 16848 16849 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16850 << var << ValueKind << ContextKind << VarDC; 16851 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16852 << var; 16853 16854 // FIXME: Add additional diagnostic info about class etc. which prevents 16855 // capture. 16856 } 16857 16858 16859 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16860 bool &SubCapturesAreNested, 16861 QualType &CaptureType, 16862 QualType &DeclRefType) { 16863 // Check whether we've already captured it. 16864 if (CSI->CaptureMap.count(Var)) { 16865 // If we found a capture, any subcaptures are nested. 16866 SubCapturesAreNested = true; 16867 16868 // Retrieve the capture type for this variable. 16869 CaptureType = CSI->getCapture(Var).getCaptureType(); 16870 16871 // Compute the type of an expression that refers to this variable. 16872 DeclRefType = CaptureType.getNonReferenceType(); 16873 16874 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16875 // are mutable in the sense that user can change their value - they are 16876 // private instances of the captured declarations. 16877 const Capture &Cap = CSI->getCapture(Var); 16878 if (Cap.isCopyCapture() && 16879 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16880 !(isa<CapturedRegionScopeInfo>(CSI) && 16881 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16882 DeclRefType.addConst(); 16883 return true; 16884 } 16885 return false; 16886 } 16887 16888 // Only block literals, captured statements, and lambda expressions can 16889 // capture; other scopes don't work. 16890 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16891 SourceLocation Loc, 16892 const bool Diagnose, Sema &S) { 16893 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16894 return getLambdaAwareParentOfDeclContext(DC); 16895 else if (Var->hasLocalStorage()) { 16896 if (Diagnose) 16897 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16898 } 16899 return nullptr; 16900 } 16901 16902 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16903 // certain types of variables (unnamed, variably modified types etc.) 16904 // so check for eligibility. 16905 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16906 SourceLocation Loc, 16907 const bool Diagnose, Sema &S) { 16908 16909 bool IsBlock = isa<BlockScopeInfo>(CSI); 16910 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16911 16912 // Lambdas are not allowed to capture unnamed variables 16913 // (e.g. anonymous unions). 16914 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16915 // assuming that's the intent. 16916 if (IsLambda && !Var->getDeclName()) { 16917 if (Diagnose) { 16918 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16919 S.Diag(Var->getLocation(), diag::note_declared_at); 16920 } 16921 return false; 16922 } 16923 16924 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16925 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16926 if (Diagnose) { 16927 S.Diag(Loc, diag::err_ref_vm_type); 16928 S.Diag(Var->getLocation(), diag::note_previous_decl) 16929 << Var->getDeclName(); 16930 } 16931 return false; 16932 } 16933 // Prohibit structs with flexible array members too. 16934 // We cannot capture what is in the tail end of the struct. 16935 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16936 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16937 if (Diagnose) { 16938 if (IsBlock) 16939 S.Diag(Loc, diag::err_ref_flexarray_type); 16940 else 16941 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16942 << Var->getDeclName(); 16943 S.Diag(Var->getLocation(), diag::note_previous_decl) 16944 << Var->getDeclName(); 16945 } 16946 return false; 16947 } 16948 } 16949 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16950 // Lambdas and captured statements are not allowed to capture __block 16951 // variables; they don't support the expected semantics. 16952 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16953 if (Diagnose) { 16954 S.Diag(Loc, diag::err_capture_block_variable) 16955 << Var->getDeclName() << !IsLambda; 16956 S.Diag(Var->getLocation(), diag::note_previous_decl) 16957 << Var->getDeclName(); 16958 } 16959 return false; 16960 } 16961 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16962 if (S.getLangOpts().OpenCL && IsBlock && 16963 Var->getType()->isBlockPointerType()) { 16964 if (Diagnose) 16965 S.Diag(Loc, diag::err_opencl_block_ref_block); 16966 return false; 16967 } 16968 16969 return true; 16970 } 16971 16972 // Returns true if the capture by block was successful. 16973 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16974 SourceLocation Loc, 16975 const bool BuildAndDiagnose, 16976 QualType &CaptureType, 16977 QualType &DeclRefType, 16978 const bool Nested, 16979 Sema &S, bool Invalid) { 16980 bool ByRef = false; 16981 16982 // Blocks are not allowed to capture arrays, excepting OpenCL. 16983 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16984 // (decayed to pointers). 16985 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16986 if (BuildAndDiagnose) { 16987 S.Diag(Loc, diag::err_ref_array_type); 16988 S.Diag(Var->getLocation(), diag::note_previous_decl) 16989 << Var->getDeclName(); 16990 Invalid = true; 16991 } else { 16992 return false; 16993 } 16994 } 16995 16996 // Forbid the block-capture of autoreleasing variables. 16997 if (!Invalid && 16998 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16999 if (BuildAndDiagnose) { 17000 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17001 << /*block*/ 0; 17002 S.Diag(Var->getLocation(), diag::note_previous_decl) 17003 << Var->getDeclName(); 17004 Invalid = true; 17005 } else { 17006 return false; 17007 } 17008 } 17009 17010 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17011 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17012 QualType PointeeTy = PT->getPointeeType(); 17013 17014 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17015 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17016 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17017 if (BuildAndDiagnose) { 17018 SourceLocation VarLoc = Var->getLocation(); 17019 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17020 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17021 } 17022 } 17023 } 17024 17025 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17026 if (HasBlocksAttr || CaptureType->isReferenceType() || 17027 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17028 // Block capture by reference does not change the capture or 17029 // declaration reference types. 17030 ByRef = true; 17031 } else { 17032 // Block capture by copy introduces 'const'. 17033 CaptureType = CaptureType.getNonReferenceType().withConst(); 17034 DeclRefType = CaptureType; 17035 } 17036 17037 // Actually capture the variable. 17038 if (BuildAndDiagnose) 17039 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17040 CaptureType, Invalid); 17041 17042 return !Invalid; 17043 } 17044 17045 17046 /// Capture the given variable in the captured region. 17047 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17048 VarDecl *Var, 17049 SourceLocation Loc, 17050 const bool BuildAndDiagnose, 17051 QualType &CaptureType, 17052 QualType &DeclRefType, 17053 const bool RefersToCapturedVariable, 17054 Sema &S, bool Invalid) { 17055 // By default, capture variables by reference. 17056 bool ByRef = true; 17057 // Using an LValue reference type is consistent with Lambdas (see below). 17058 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17059 if (S.isOpenMPCapturedDecl(Var)) { 17060 bool HasConst = DeclRefType.isConstQualified(); 17061 DeclRefType = DeclRefType.getUnqualifiedType(); 17062 // Don't lose diagnostics about assignments to const. 17063 if (HasConst) 17064 DeclRefType.addConst(); 17065 } 17066 // Do not capture firstprivates in tasks. 17067 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17068 OMPC_unknown) 17069 return true; 17070 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17071 RSI->OpenMPCaptureLevel); 17072 } 17073 17074 if (ByRef) 17075 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17076 else 17077 CaptureType = DeclRefType; 17078 17079 // Actually capture the variable. 17080 if (BuildAndDiagnose) 17081 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17082 Loc, SourceLocation(), CaptureType, Invalid); 17083 17084 return !Invalid; 17085 } 17086 17087 /// Capture the given variable in the lambda. 17088 static bool captureInLambda(LambdaScopeInfo *LSI, 17089 VarDecl *Var, 17090 SourceLocation Loc, 17091 const bool BuildAndDiagnose, 17092 QualType &CaptureType, 17093 QualType &DeclRefType, 17094 const bool RefersToCapturedVariable, 17095 const Sema::TryCaptureKind Kind, 17096 SourceLocation EllipsisLoc, 17097 const bool IsTopScope, 17098 Sema &S, bool Invalid) { 17099 // Determine whether we are capturing by reference or by value. 17100 bool ByRef = false; 17101 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17102 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17103 } else { 17104 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17105 } 17106 17107 // Compute the type of the field that will capture this variable. 17108 if (ByRef) { 17109 // C++11 [expr.prim.lambda]p15: 17110 // An entity is captured by reference if it is implicitly or 17111 // explicitly captured but not captured by copy. It is 17112 // unspecified whether additional unnamed non-static data 17113 // members are declared in the closure type for entities 17114 // captured by reference. 17115 // 17116 // FIXME: It is not clear whether we want to build an lvalue reference 17117 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17118 // to do the former, while EDG does the latter. Core issue 1249 will 17119 // clarify, but for now we follow GCC because it's a more permissive and 17120 // easily defensible position. 17121 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17122 } else { 17123 // C++11 [expr.prim.lambda]p14: 17124 // For each entity captured by copy, an unnamed non-static 17125 // data member is declared in the closure type. The 17126 // declaration order of these members is unspecified. The type 17127 // of such a data member is the type of the corresponding 17128 // captured entity if the entity is not a reference to an 17129 // object, or the referenced type otherwise. [Note: If the 17130 // captured entity is a reference to a function, the 17131 // corresponding data member is also a reference to a 17132 // function. - end note ] 17133 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17134 if (!RefType->getPointeeType()->isFunctionType()) 17135 CaptureType = RefType->getPointeeType(); 17136 } 17137 17138 // Forbid the lambda copy-capture of autoreleasing variables. 17139 if (!Invalid && 17140 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17141 if (BuildAndDiagnose) { 17142 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17143 S.Diag(Var->getLocation(), diag::note_previous_decl) 17144 << Var->getDeclName(); 17145 Invalid = true; 17146 } else { 17147 return false; 17148 } 17149 } 17150 17151 // Make sure that by-copy captures are of a complete and non-abstract type. 17152 if (!Invalid && BuildAndDiagnose) { 17153 if (!CaptureType->isDependentType() && 17154 S.RequireCompleteSizedType( 17155 Loc, CaptureType, 17156 diag::err_capture_of_incomplete_or_sizeless_type, 17157 Var->getDeclName())) 17158 Invalid = true; 17159 else if (S.RequireNonAbstractType(Loc, CaptureType, 17160 diag::err_capture_of_abstract_type)) 17161 Invalid = true; 17162 } 17163 } 17164 17165 // Compute the type of a reference to this captured variable. 17166 if (ByRef) 17167 DeclRefType = CaptureType.getNonReferenceType(); 17168 else { 17169 // C++ [expr.prim.lambda]p5: 17170 // The closure type for a lambda-expression has a public inline 17171 // function call operator [...]. This function call operator is 17172 // declared const (9.3.1) if and only if the lambda-expression's 17173 // parameter-declaration-clause is not followed by mutable. 17174 DeclRefType = CaptureType.getNonReferenceType(); 17175 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17176 DeclRefType.addConst(); 17177 } 17178 17179 // Add the capture. 17180 if (BuildAndDiagnose) 17181 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17182 Loc, EllipsisLoc, CaptureType, Invalid); 17183 17184 return !Invalid; 17185 } 17186 17187 bool Sema::tryCaptureVariable( 17188 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17189 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17190 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17191 // An init-capture is notionally from the context surrounding its 17192 // declaration, but its parent DC is the lambda class. 17193 DeclContext *VarDC = Var->getDeclContext(); 17194 if (Var->isInitCapture()) 17195 VarDC = VarDC->getParent(); 17196 17197 DeclContext *DC = CurContext; 17198 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17199 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17200 // We need to sync up the Declaration Context with the 17201 // FunctionScopeIndexToStopAt 17202 if (FunctionScopeIndexToStopAt) { 17203 unsigned FSIndex = FunctionScopes.size() - 1; 17204 while (FSIndex != MaxFunctionScopesIndex) { 17205 DC = getLambdaAwareParentOfDeclContext(DC); 17206 --FSIndex; 17207 } 17208 } 17209 17210 17211 // If the variable is declared in the current context, there is no need to 17212 // capture it. 17213 if (VarDC == DC) return true; 17214 17215 // Capture global variables if it is required to use private copy of this 17216 // variable. 17217 bool IsGlobal = !Var->hasLocalStorage(); 17218 if (IsGlobal && 17219 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17220 MaxFunctionScopesIndex))) 17221 return true; 17222 Var = Var->getCanonicalDecl(); 17223 17224 // Walk up the stack to determine whether we can capture the variable, 17225 // performing the "simple" checks that don't depend on type. We stop when 17226 // we've either hit the declared scope of the variable or find an existing 17227 // capture of that variable. We start from the innermost capturing-entity 17228 // (the DC) and ensure that all intervening capturing-entities 17229 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17230 // declcontext can either capture the variable or have already captured 17231 // the variable. 17232 CaptureType = Var->getType(); 17233 DeclRefType = CaptureType.getNonReferenceType(); 17234 bool Nested = false; 17235 bool Explicit = (Kind != TryCapture_Implicit); 17236 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17237 do { 17238 // Only block literals, captured statements, and lambda expressions can 17239 // capture; other scopes don't work. 17240 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17241 ExprLoc, 17242 BuildAndDiagnose, 17243 *this); 17244 // We need to check for the parent *first* because, if we *have* 17245 // private-captured a global variable, we need to recursively capture it in 17246 // intermediate blocks, lambdas, etc. 17247 if (!ParentDC) { 17248 if (IsGlobal) { 17249 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17250 break; 17251 } 17252 return true; 17253 } 17254 17255 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17256 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17257 17258 17259 // Check whether we've already captured it. 17260 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17261 DeclRefType)) { 17262 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17263 break; 17264 } 17265 // If we are instantiating a generic lambda call operator body, 17266 // we do not want to capture new variables. What was captured 17267 // during either a lambdas transformation or initial parsing 17268 // should be used. 17269 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17270 if (BuildAndDiagnose) { 17271 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17272 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17273 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17274 Diag(Var->getLocation(), diag::note_previous_decl) 17275 << Var->getDeclName(); 17276 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17277 } else 17278 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17279 } 17280 return true; 17281 } 17282 17283 // Try to capture variable-length arrays types. 17284 if (Var->getType()->isVariablyModifiedType()) { 17285 // We're going to walk down into the type and look for VLA 17286 // expressions. 17287 QualType QTy = Var->getType(); 17288 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17289 QTy = PVD->getOriginalType(); 17290 captureVariablyModifiedType(Context, QTy, CSI); 17291 } 17292 17293 if (getLangOpts().OpenMP) { 17294 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17295 // OpenMP private variables should not be captured in outer scope, so 17296 // just break here. Similarly, global variables that are captured in a 17297 // target region should not be captured outside the scope of the region. 17298 if (RSI->CapRegionKind == CR_OpenMP) { 17299 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17300 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17301 // If the variable is private (i.e. not captured) and has variably 17302 // modified type, we still need to capture the type for correct 17303 // codegen in all regions, associated with the construct. Currently, 17304 // it is captured in the innermost captured region only. 17305 if (IsOpenMPPrivateDecl != OMPC_unknown && 17306 Var->getType()->isVariablyModifiedType()) { 17307 QualType QTy = Var->getType(); 17308 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17309 QTy = PVD->getOriginalType(); 17310 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17311 I < E; ++I) { 17312 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17313 FunctionScopes[FunctionScopesIndex - I]); 17314 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17315 "Wrong number of captured regions associated with the " 17316 "OpenMP construct."); 17317 captureVariablyModifiedType(Context, QTy, OuterRSI); 17318 } 17319 } 17320 bool IsTargetCap = 17321 IsOpenMPPrivateDecl != OMPC_private && 17322 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17323 RSI->OpenMPCaptureLevel); 17324 // Do not capture global if it is not privatized in outer regions. 17325 bool IsGlobalCap = 17326 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17327 RSI->OpenMPCaptureLevel); 17328 17329 // When we detect target captures we are looking from inside the 17330 // target region, therefore we need to propagate the capture from the 17331 // enclosing region. Therefore, the capture is not initially nested. 17332 if (IsTargetCap) 17333 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17334 17335 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17336 (IsGlobal && !IsGlobalCap)) { 17337 Nested = !IsTargetCap; 17338 DeclRefType = DeclRefType.getUnqualifiedType(); 17339 CaptureType = Context.getLValueReferenceType(DeclRefType); 17340 break; 17341 } 17342 } 17343 } 17344 } 17345 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17346 // No capture-default, and this is not an explicit capture 17347 // so cannot capture this variable. 17348 if (BuildAndDiagnose) { 17349 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17350 Diag(Var->getLocation(), diag::note_previous_decl) 17351 << Var->getDeclName(); 17352 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17353 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17354 diag::note_lambda_decl); 17355 // FIXME: If we error out because an outer lambda can not implicitly 17356 // capture a variable that an inner lambda explicitly captures, we 17357 // should have the inner lambda do the explicit capture - because 17358 // it makes for cleaner diagnostics later. This would purely be done 17359 // so that the diagnostic does not misleadingly claim that a variable 17360 // can not be captured by a lambda implicitly even though it is captured 17361 // explicitly. Suggestion: 17362 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17363 // at the function head 17364 // - cache the StartingDeclContext - this must be a lambda 17365 // - captureInLambda in the innermost lambda the variable. 17366 } 17367 return true; 17368 } 17369 17370 FunctionScopesIndex--; 17371 DC = ParentDC; 17372 Explicit = false; 17373 } while (!VarDC->Equals(DC)); 17374 17375 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17376 // computing the type of the capture at each step, checking type-specific 17377 // requirements, and adding captures if requested. 17378 // If the variable had already been captured previously, we start capturing 17379 // at the lambda nested within that one. 17380 bool Invalid = false; 17381 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17382 ++I) { 17383 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17384 17385 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17386 // certain types of variables (unnamed, variably modified types etc.) 17387 // so check for eligibility. 17388 if (!Invalid) 17389 Invalid = 17390 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17391 17392 // After encountering an error, if we're actually supposed to capture, keep 17393 // capturing in nested contexts to suppress any follow-on diagnostics. 17394 if (Invalid && !BuildAndDiagnose) 17395 return true; 17396 17397 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17398 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17399 DeclRefType, Nested, *this, Invalid); 17400 Nested = true; 17401 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17402 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17403 CaptureType, DeclRefType, Nested, 17404 *this, Invalid); 17405 Nested = true; 17406 } else { 17407 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17408 Invalid = 17409 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17410 DeclRefType, Nested, Kind, EllipsisLoc, 17411 /*IsTopScope*/ I == N - 1, *this, Invalid); 17412 Nested = true; 17413 } 17414 17415 if (Invalid && !BuildAndDiagnose) 17416 return true; 17417 } 17418 return Invalid; 17419 } 17420 17421 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17422 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17423 QualType CaptureType; 17424 QualType DeclRefType; 17425 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17426 /*BuildAndDiagnose=*/true, CaptureType, 17427 DeclRefType, nullptr); 17428 } 17429 17430 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17431 QualType CaptureType; 17432 QualType DeclRefType; 17433 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17434 /*BuildAndDiagnose=*/false, CaptureType, 17435 DeclRefType, nullptr); 17436 } 17437 17438 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17439 QualType CaptureType; 17440 QualType DeclRefType; 17441 17442 // Determine whether we can capture this variable. 17443 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17444 /*BuildAndDiagnose=*/false, CaptureType, 17445 DeclRefType, nullptr)) 17446 return QualType(); 17447 17448 return DeclRefType; 17449 } 17450 17451 namespace { 17452 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17453 // The produced TemplateArgumentListInfo* points to data stored within this 17454 // object, so should only be used in contexts where the pointer will not be 17455 // used after the CopiedTemplateArgs object is destroyed. 17456 class CopiedTemplateArgs { 17457 bool HasArgs; 17458 TemplateArgumentListInfo TemplateArgStorage; 17459 public: 17460 template<typename RefExpr> 17461 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17462 if (HasArgs) 17463 E->copyTemplateArgumentsInto(TemplateArgStorage); 17464 } 17465 operator TemplateArgumentListInfo*() 17466 #ifdef __has_cpp_attribute 17467 #if __has_cpp_attribute(clang::lifetimebound) 17468 [[clang::lifetimebound]] 17469 #endif 17470 #endif 17471 { 17472 return HasArgs ? &TemplateArgStorage : nullptr; 17473 } 17474 }; 17475 } 17476 17477 /// Walk the set of potential results of an expression and mark them all as 17478 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17479 /// 17480 /// \return A new expression if we found any potential results, ExprEmpty() if 17481 /// not, and ExprError() if we diagnosed an error. 17482 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17483 NonOdrUseReason NOUR) { 17484 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17485 // an object that satisfies the requirements for appearing in a 17486 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17487 // is immediately applied." This function handles the lvalue-to-rvalue 17488 // conversion part. 17489 // 17490 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17491 // transform it into the relevant kind of non-odr-use node and rebuild the 17492 // tree of nodes leading to it. 17493 // 17494 // This is a mini-TreeTransform that only transforms a restricted subset of 17495 // nodes (and only certain operands of them). 17496 17497 // Rebuild a subexpression. 17498 auto Rebuild = [&](Expr *Sub) { 17499 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17500 }; 17501 17502 // Check whether a potential result satisfies the requirements of NOUR. 17503 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17504 // Any entity other than a VarDecl is always odr-used whenever it's named 17505 // in a potentially-evaluated expression. 17506 auto *VD = dyn_cast<VarDecl>(D); 17507 if (!VD) 17508 return true; 17509 17510 // C++2a [basic.def.odr]p4: 17511 // A variable x whose name appears as a potentially-evalauted expression 17512 // e is odr-used by e unless 17513 // -- x is a reference that is usable in constant expressions, or 17514 // -- x is a variable of non-reference type that is usable in constant 17515 // expressions and has no mutable subobjects, and e is an element of 17516 // the set of potential results of an expression of 17517 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17518 // conversion is applied, or 17519 // -- x is a variable of non-reference type, and e is an element of the 17520 // set of potential results of a discarded-value expression to which 17521 // the lvalue-to-rvalue conversion is not applied 17522 // 17523 // We check the first bullet and the "potentially-evaluated" condition in 17524 // BuildDeclRefExpr. We check the type requirements in the second bullet 17525 // in CheckLValueToRValueConversionOperand below. 17526 switch (NOUR) { 17527 case NOUR_None: 17528 case NOUR_Unevaluated: 17529 llvm_unreachable("unexpected non-odr-use-reason"); 17530 17531 case NOUR_Constant: 17532 // Constant references were handled when they were built. 17533 if (VD->getType()->isReferenceType()) 17534 return true; 17535 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17536 if (RD->hasMutableFields()) 17537 return true; 17538 if (!VD->isUsableInConstantExpressions(S.Context)) 17539 return true; 17540 break; 17541 17542 case NOUR_Discarded: 17543 if (VD->getType()->isReferenceType()) 17544 return true; 17545 break; 17546 } 17547 return false; 17548 }; 17549 17550 // Mark that this expression does not constitute an odr-use. 17551 auto MarkNotOdrUsed = [&] { 17552 S.MaybeODRUseExprs.remove(E); 17553 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17554 LSI->markVariableExprAsNonODRUsed(E); 17555 }; 17556 17557 // C++2a [basic.def.odr]p2: 17558 // The set of potential results of an expression e is defined as follows: 17559 switch (E->getStmtClass()) { 17560 // -- If e is an id-expression, ... 17561 case Expr::DeclRefExprClass: { 17562 auto *DRE = cast<DeclRefExpr>(E); 17563 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17564 break; 17565 17566 // Rebuild as a non-odr-use DeclRefExpr. 17567 MarkNotOdrUsed(); 17568 return DeclRefExpr::Create( 17569 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17570 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17571 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17572 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17573 } 17574 17575 case Expr::FunctionParmPackExprClass: { 17576 auto *FPPE = cast<FunctionParmPackExpr>(E); 17577 // If any of the declarations in the pack is odr-used, then the expression 17578 // as a whole constitutes an odr-use. 17579 for (VarDecl *D : *FPPE) 17580 if (IsPotentialResultOdrUsed(D)) 17581 return ExprEmpty(); 17582 17583 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17584 // nothing cares about whether we marked this as an odr-use, but it might 17585 // be useful for non-compiler tools. 17586 MarkNotOdrUsed(); 17587 break; 17588 } 17589 17590 // -- If e is a subscripting operation with an array operand... 17591 case Expr::ArraySubscriptExprClass: { 17592 auto *ASE = cast<ArraySubscriptExpr>(E); 17593 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17594 if (!OldBase->getType()->isArrayType()) 17595 break; 17596 ExprResult Base = Rebuild(OldBase); 17597 if (!Base.isUsable()) 17598 return Base; 17599 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17600 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17601 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17602 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17603 ASE->getRBracketLoc()); 17604 } 17605 17606 case Expr::MemberExprClass: { 17607 auto *ME = cast<MemberExpr>(E); 17608 // -- If e is a class member access expression [...] naming a non-static 17609 // data member... 17610 if (isa<FieldDecl>(ME->getMemberDecl())) { 17611 ExprResult Base = Rebuild(ME->getBase()); 17612 if (!Base.isUsable()) 17613 return Base; 17614 return MemberExpr::Create( 17615 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17616 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17617 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17618 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17619 ME->getObjectKind(), ME->isNonOdrUse()); 17620 } 17621 17622 if (ME->getMemberDecl()->isCXXInstanceMember()) 17623 break; 17624 17625 // -- If e is a class member access expression naming a static data member, 17626 // ... 17627 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17628 break; 17629 17630 // Rebuild as a non-odr-use MemberExpr. 17631 MarkNotOdrUsed(); 17632 return MemberExpr::Create( 17633 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17634 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17635 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17636 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17637 return ExprEmpty(); 17638 } 17639 17640 case Expr::BinaryOperatorClass: { 17641 auto *BO = cast<BinaryOperator>(E); 17642 Expr *LHS = BO->getLHS(); 17643 Expr *RHS = BO->getRHS(); 17644 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17645 if (BO->getOpcode() == BO_PtrMemD) { 17646 ExprResult Sub = Rebuild(LHS); 17647 if (!Sub.isUsable()) 17648 return Sub; 17649 LHS = Sub.get(); 17650 // -- If e is a comma expression, ... 17651 } else if (BO->getOpcode() == BO_Comma) { 17652 ExprResult Sub = Rebuild(RHS); 17653 if (!Sub.isUsable()) 17654 return Sub; 17655 RHS = Sub.get(); 17656 } else { 17657 break; 17658 } 17659 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17660 LHS, RHS); 17661 } 17662 17663 // -- If e has the form (e1)... 17664 case Expr::ParenExprClass: { 17665 auto *PE = cast<ParenExpr>(E); 17666 ExprResult Sub = Rebuild(PE->getSubExpr()); 17667 if (!Sub.isUsable()) 17668 return Sub; 17669 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17670 } 17671 17672 // -- If e is a glvalue conditional expression, ... 17673 // We don't apply this to a binary conditional operator. FIXME: Should we? 17674 case Expr::ConditionalOperatorClass: { 17675 auto *CO = cast<ConditionalOperator>(E); 17676 ExprResult LHS = Rebuild(CO->getLHS()); 17677 if (LHS.isInvalid()) 17678 return ExprError(); 17679 ExprResult RHS = Rebuild(CO->getRHS()); 17680 if (RHS.isInvalid()) 17681 return ExprError(); 17682 if (!LHS.isUsable() && !RHS.isUsable()) 17683 return ExprEmpty(); 17684 if (!LHS.isUsable()) 17685 LHS = CO->getLHS(); 17686 if (!RHS.isUsable()) 17687 RHS = CO->getRHS(); 17688 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17689 CO->getCond(), LHS.get(), RHS.get()); 17690 } 17691 17692 // [Clang extension] 17693 // -- If e has the form __extension__ e1... 17694 case Expr::UnaryOperatorClass: { 17695 auto *UO = cast<UnaryOperator>(E); 17696 if (UO->getOpcode() != UO_Extension) 17697 break; 17698 ExprResult Sub = Rebuild(UO->getSubExpr()); 17699 if (!Sub.isUsable()) 17700 return Sub; 17701 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17702 Sub.get()); 17703 } 17704 17705 // [Clang extension] 17706 // -- If e has the form _Generic(...), the set of potential results is the 17707 // union of the sets of potential results of the associated expressions. 17708 case Expr::GenericSelectionExprClass: { 17709 auto *GSE = cast<GenericSelectionExpr>(E); 17710 17711 SmallVector<Expr *, 4> AssocExprs; 17712 bool AnyChanged = false; 17713 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17714 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17715 if (AssocExpr.isInvalid()) 17716 return ExprError(); 17717 if (AssocExpr.isUsable()) { 17718 AssocExprs.push_back(AssocExpr.get()); 17719 AnyChanged = true; 17720 } else { 17721 AssocExprs.push_back(OrigAssocExpr); 17722 } 17723 } 17724 17725 return AnyChanged ? S.CreateGenericSelectionExpr( 17726 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17727 GSE->getRParenLoc(), GSE->getControllingExpr(), 17728 GSE->getAssocTypeSourceInfos(), AssocExprs) 17729 : ExprEmpty(); 17730 } 17731 17732 // [Clang extension] 17733 // -- If e has the form __builtin_choose_expr(...), the set of potential 17734 // results is the union of the sets of potential results of the 17735 // second and third subexpressions. 17736 case Expr::ChooseExprClass: { 17737 auto *CE = cast<ChooseExpr>(E); 17738 17739 ExprResult LHS = Rebuild(CE->getLHS()); 17740 if (LHS.isInvalid()) 17741 return ExprError(); 17742 17743 ExprResult RHS = Rebuild(CE->getLHS()); 17744 if (RHS.isInvalid()) 17745 return ExprError(); 17746 17747 if (!LHS.get() && !RHS.get()) 17748 return ExprEmpty(); 17749 if (!LHS.isUsable()) 17750 LHS = CE->getLHS(); 17751 if (!RHS.isUsable()) 17752 RHS = CE->getRHS(); 17753 17754 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17755 RHS.get(), CE->getRParenLoc()); 17756 } 17757 17758 // Step through non-syntactic nodes. 17759 case Expr::ConstantExprClass: { 17760 auto *CE = cast<ConstantExpr>(E); 17761 ExprResult Sub = Rebuild(CE->getSubExpr()); 17762 if (!Sub.isUsable()) 17763 return Sub; 17764 return ConstantExpr::Create(S.Context, Sub.get()); 17765 } 17766 17767 // We could mostly rely on the recursive rebuilding to rebuild implicit 17768 // casts, but not at the top level, so rebuild them here. 17769 case Expr::ImplicitCastExprClass: { 17770 auto *ICE = cast<ImplicitCastExpr>(E); 17771 // Only step through the narrow set of cast kinds we expect to encounter. 17772 // Anything else suggests we've left the region in which potential results 17773 // can be found. 17774 switch (ICE->getCastKind()) { 17775 case CK_NoOp: 17776 case CK_DerivedToBase: 17777 case CK_UncheckedDerivedToBase: { 17778 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17779 if (!Sub.isUsable()) 17780 return Sub; 17781 CXXCastPath Path(ICE->path()); 17782 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17783 ICE->getValueKind(), &Path); 17784 } 17785 17786 default: 17787 break; 17788 } 17789 break; 17790 } 17791 17792 default: 17793 break; 17794 } 17795 17796 // Can't traverse through this node. Nothing to do. 17797 return ExprEmpty(); 17798 } 17799 17800 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17801 // Check whether the operand is or contains an object of non-trivial C union 17802 // type. 17803 if (E->getType().isVolatileQualified() && 17804 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17805 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17806 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17807 Sema::NTCUC_LValueToRValueVolatile, 17808 NTCUK_Destruct|NTCUK_Copy); 17809 17810 // C++2a [basic.def.odr]p4: 17811 // [...] an expression of non-volatile-qualified non-class type to which 17812 // the lvalue-to-rvalue conversion is applied [...] 17813 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17814 return E; 17815 17816 ExprResult Result = 17817 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17818 if (Result.isInvalid()) 17819 return ExprError(); 17820 return Result.get() ? Result : E; 17821 } 17822 17823 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17824 Res = CorrectDelayedTyposInExpr(Res); 17825 17826 if (!Res.isUsable()) 17827 return Res; 17828 17829 // If a constant-expression is a reference to a variable where we delay 17830 // deciding whether it is an odr-use, just assume we will apply the 17831 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17832 // (a non-type template argument), we have special handling anyway. 17833 return CheckLValueToRValueConversionOperand(Res.get()); 17834 } 17835 17836 void Sema::CleanupVarDeclMarking() { 17837 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17838 // call. 17839 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17840 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17841 17842 for (Expr *E : LocalMaybeODRUseExprs) { 17843 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17844 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17845 DRE->getLocation(), *this); 17846 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17847 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17848 *this); 17849 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17850 for (VarDecl *VD : *FP) 17851 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17852 } else { 17853 llvm_unreachable("Unexpected expression"); 17854 } 17855 } 17856 17857 assert(MaybeODRUseExprs.empty() && 17858 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17859 } 17860 17861 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17862 VarDecl *Var, Expr *E) { 17863 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17864 isa<FunctionParmPackExpr>(E)) && 17865 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17866 Var->setReferenced(); 17867 17868 if (Var->isInvalidDecl()) 17869 return; 17870 17871 auto *MSI = Var->getMemberSpecializationInfo(); 17872 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17873 : Var->getTemplateSpecializationKind(); 17874 17875 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17876 bool UsableInConstantExpr = 17877 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17878 17879 // C++20 [expr.const]p12: 17880 // A variable [...] is needed for constant evaluation if it is [...] a 17881 // variable whose name appears as a potentially constant evaluated 17882 // expression that is either a contexpr variable or is of non-volatile 17883 // const-qualified integral type or of reference type 17884 bool NeededForConstantEvaluation = 17885 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17886 17887 bool NeedDefinition = 17888 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17889 17890 VarTemplateSpecializationDecl *VarSpec = 17891 dyn_cast<VarTemplateSpecializationDecl>(Var); 17892 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17893 "Can't instantiate a partial template specialization."); 17894 17895 // If this might be a member specialization of a static data member, check 17896 // the specialization is visible. We already did the checks for variable 17897 // template specializations when we created them. 17898 if (NeedDefinition && TSK != TSK_Undeclared && 17899 !isa<VarTemplateSpecializationDecl>(Var)) 17900 SemaRef.checkSpecializationVisibility(Loc, Var); 17901 17902 // Perform implicit instantiation of static data members, static data member 17903 // templates of class templates, and variable template specializations. Delay 17904 // instantiations of variable templates, except for those that could be used 17905 // in a constant expression. 17906 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17907 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17908 // instantiation declaration if a variable is usable in a constant 17909 // expression (among other cases). 17910 bool TryInstantiating = 17911 TSK == TSK_ImplicitInstantiation || 17912 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17913 17914 if (TryInstantiating) { 17915 SourceLocation PointOfInstantiation = 17916 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17917 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17918 if (FirstInstantiation) { 17919 PointOfInstantiation = Loc; 17920 if (MSI) 17921 MSI->setPointOfInstantiation(PointOfInstantiation); 17922 else 17923 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17924 } 17925 17926 bool InstantiationDependent = false; 17927 bool IsNonDependent = 17928 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17929 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17930 : true; 17931 17932 // Do not instantiate specializations that are still type-dependent. 17933 if (IsNonDependent) { 17934 if (UsableInConstantExpr) { 17935 // Do not defer instantiations of variables that could be used in a 17936 // constant expression. 17937 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17938 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17939 }); 17940 } else if (FirstInstantiation || 17941 isa<VarTemplateSpecializationDecl>(Var)) { 17942 // FIXME: For a specialization of a variable template, we don't 17943 // distinguish between "declaration and type implicitly instantiated" 17944 // and "implicit instantiation of definition requested", so we have 17945 // no direct way to avoid enqueueing the pending instantiation 17946 // multiple times. 17947 SemaRef.PendingInstantiations 17948 .push_back(std::make_pair(Var, PointOfInstantiation)); 17949 } 17950 } 17951 } 17952 } 17953 17954 // C++2a [basic.def.odr]p4: 17955 // A variable x whose name appears as a potentially-evaluated expression e 17956 // is odr-used by e unless 17957 // -- x is a reference that is usable in constant expressions 17958 // -- x is a variable of non-reference type that is usable in constant 17959 // expressions and has no mutable subobjects [FIXME], and e is an 17960 // element of the set of potential results of an expression of 17961 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17962 // conversion is applied 17963 // -- x is a variable of non-reference type, and e is an element of the set 17964 // of potential results of a discarded-value expression to which the 17965 // lvalue-to-rvalue conversion is not applied [FIXME] 17966 // 17967 // We check the first part of the second bullet here, and 17968 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17969 // FIXME: To get the third bullet right, we need to delay this even for 17970 // variables that are not usable in constant expressions. 17971 17972 // If we already know this isn't an odr-use, there's nothing more to do. 17973 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17974 if (DRE->isNonOdrUse()) 17975 return; 17976 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17977 if (ME->isNonOdrUse()) 17978 return; 17979 17980 switch (OdrUse) { 17981 case OdrUseContext::None: 17982 assert((!E || isa<FunctionParmPackExpr>(E)) && 17983 "missing non-odr-use marking for unevaluated decl ref"); 17984 break; 17985 17986 case OdrUseContext::FormallyOdrUsed: 17987 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17988 // behavior. 17989 break; 17990 17991 case OdrUseContext::Used: 17992 // If we might later find that this expression isn't actually an odr-use, 17993 // delay the marking. 17994 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17995 SemaRef.MaybeODRUseExprs.insert(E); 17996 else 17997 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17998 break; 17999 18000 case OdrUseContext::Dependent: 18001 // If this is a dependent context, we don't need to mark variables as 18002 // odr-used, but we may still need to track them for lambda capture. 18003 // FIXME: Do we also need to do this inside dependent typeid expressions 18004 // (which are modeled as unevaluated at this point)? 18005 const bool RefersToEnclosingScope = 18006 (SemaRef.CurContext != Var->getDeclContext() && 18007 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18008 if (RefersToEnclosingScope) { 18009 LambdaScopeInfo *const LSI = 18010 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18011 if (LSI && (!LSI->CallOperator || 18012 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18013 // If a variable could potentially be odr-used, defer marking it so 18014 // until we finish analyzing the full expression for any 18015 // lvalue-to-rvalue 18016 // or discarded value conversions that would obviate odr-use. 18017 // Add it to the list of potential captures that will be analyzed 18018 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18019 // unless the variable is a reference that was initialized by a constant 18020 // expression (this will never need to be captured or odr-used). 18021 // 18022 // FIXME: We can simplify this a lot after implementing P0588R1. 18023 assert(E && "Capture variable should be used in an expression."); 18024 if (!Var->getType()->isReferenceType() || 18025 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18026 LSI->addPotentialCapture(E->IgnoreParens()); 18027 } 18028 } 18029 break; 18030 } 18031 } 18032 18033 /// Mark a variable referenced, and check whether it is odr-used 18034 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18035 /// used directly for normal expressions referring to VarDecl. 18036 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18037 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18038 } 18039 18040 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18041 Decl *D, Expr *E, bool MightBeOdrUse) { 18042 if (SemaRef.isInOpenMPDeclareTargetContext()) 18043 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18044 18045 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18046 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18047 return; 18048 } 18049 18050 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18051 18052 // If this is a call to a method via a cast, also mark the method in the 18053 // derived class used in case codegen can devirtualize the call. 18054 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18055 if (!ME) 18056 return; 18057 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18058 if (!MD) 18059 return; 18060 // Only attempt to devirtualize if this is truly a virtual call. 18061 bool IsVirtualCall = MD->isVirtual() && 18062 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18063 if (!IsVirtualCall) 18064 return; 18065 18066 // If it's possible to devirtualize the call, mark the called function 18067 // referenced. 18068 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18069 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18070 if (DM) 18071 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18072 } 18073 18074 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18075 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18076 // TODO: update this with DR# once a defect report is filed. 18077 // C++11 defect. The address of a pure member should not be an ODR use, even 18078 // if it's a qualified reference. 18079 bool OdrUse = true; 18080 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18081 if (Method->isVirtual() && 18082 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18083 OdrUse = false; 18084 18085 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18086 if (!isConstantEvaluated() && FD->isConsteval() && 18087 !RebuildingImmediateInvocation) 18088 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18089 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18090 } 18091 18092 /// Perform reference-marking and odr-use handling for a MemberExpr. 18093 void Sema::MarkMemberReferenced(MemberExpr *E) { 18094 // C++11 [basic.def.odr]p2: 18095 // A non-overloaded function whose name appears as a potentially-evaluated 18096 // expression or a member of a set of candidate functions, if selected by 18097 // overload resolution when referred to from a potentially-evaluated 18098 // expression, is odr-used, unless it is a pure virtual function and its 18099 // name is not explicitly qualified. 18100 bool MightBeOdrUse = true; 18101 if (E->performsVirtualDispatch(getLangOpts())) { 18102 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18103 if (Method->isPure()) 18104 MightBeOdrUse = false; 18105 } 18106 SourceLocation Loc = 18107 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18108 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18109 } 18110 18111 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18112 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18113 for (VarDecl *VD : *E) 18114 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18115 } 18116 18117 /// Perform marking for a reference to an arbitrary declaration. It 18118 /// marks the declaration referenced, and performs odr-use checking for 18119 /// functions and variables. This method should not be used when building a 18120 /// normal expression which refers to a variable. 18121 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18122 bool MightBeOdrUse) { 18123 if (MightBeOdrUse) { 18124 if (auto *VD = dyn_cast<VarDecl>(D)) { 18125 MarkVariableReferenced(Loc, VD); 18126 return; 18127 } 18128 } 18129 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18130 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18131 return; 18132 } 18133 D->setReferenced(); 18134 } 18135 18136 namespace { 18137 // Mark all of the declarations used by a type as referenced. 18138 // FIXME: Not fully implemented yet! We need to have a better understanding 18139 // of when we're entering a context we should not recurse into. 18140 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18141 // TreeTransforms rebuilding the type in a new context. Rather than 18142 // duplicating the TreeTransform logic, we should consider reusing it here. 18143 // Currently that causes problems when rebuilding LambdaExprs. 18144 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18145 Sema &S; 18146 SourceLocation Loc; 18147 18148 public: 18149 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18150 18151 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18152 18153 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18154 }; 18155 } 18156 18157 bool MarkReferencedDecls::TraverseTemplateArgument( 18158 const TemplateArgument &Arg) { 18159 { 18160 // A non-type template argument is a constant-evaluated context. 18161 EnterExpressionEvaluationContext Evaluated( 18162 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18163 if (Arg.getKind() == TemplateArgument::Declaration) { 18164 if (Decl *D = Arg.getAsDecl()) 18165 S.MarkAnyDeclReferenced(Loc, D, true); 18166 } else if (Arg.getKind() == TemplateArgument::Expression) { 18167 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18168 } 18169 } 18170 18171 return Inherited::TraverseTemplateArgument(Arg); 18172 } 18173 18174 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18175 MarkReferencedDecls Marker(*this, Loc); 18176 Marker.TraverseType(T); 18177 } 18178 18179 namespace { 18180 /// Helper class that marks all of the declarations referenced by 18181 /// potentially-evaluated subexpressions as "referenced". 18182 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18183 public: 18184 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18185 bool SkipLocalVariables; 18186 18187 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18188 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18189 18190 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18191 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18192 } 18193 18194 void VisitDeclRefExpr(DeclRefExpr *E) { 18195 // If we were asked not to visit local variables, don't. 18196 if (SkipLocalVariables) { 18197 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18198 if (VD->hasLocalStorage()) 18199 return; 18200 } 18201 S.MarkDeclRefReferenced(E); 18202 } 18203 18204 void VisitMemberExpr(MemberExpr *E) { 18205 S.MarkMemberReferenced(E); 18206 Visit(E->getBase()); 18207 } 18208 }; 18209 } // namespace 18210 18211 /// Mark any declarations that appear within this expression or any 18212 /// potentially-evaluated subexpressions as "referenced". 18213 /// 18214 /// \param SkipLocalVariables If true, don't mark local variables as 18215 /// 'referenced'. 18216 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18217 bool SkipLocalVariables) { 18218 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18219 } 18220 18221 /// Emit a diagnostic that describes an effect on the run-time behavior 18222 /// of the program being compiled. 18223 /// 18224 /// This routine emits the given diagnostic when the code currently being 18225 /// type-checked is "potentially evaluated", meaning that there is a 18226 /// possibility that the code will actually be executable. Code in sizeof() 18227 /// expressions, code used only during overload resolution, etc., are not 18228 /// potentially evaluated. This routine will suppress such diagnostics or, 18229 /// in the absolutely nutty case of potentially potentially evaluated 18230 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18231 /// later. 18232 /// 18233 /// This routine should be used for all diagnostics that describe the run-time 18234 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18235 /// Failure to do so will likely result in spurious diagnostics or failures 18236 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18237 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18238 const PartialDiagnostic &PD) { 18239 switch (ExprEvalContexts.back().Context) { 18240 case ExpressionEvaluationContext::Unevaluated: 18241 case ExpressionEvaluationContext::UnevaluatedList: 18242 case ExpressionEvaluationContext::UnevaluatedAbstract: 18243 case ExpressionEvaluationContext::DiscardedStatement: 18244 // The argument will never be evaluated, so don't complain. 18245 break; 18246 18247 case ExpressionEvaluationContext::ConstantEvaluated: 18248 // Relevant diagnostics should be produced by constant evaluation. 18249 break; 18250 18251 case ExpressionEvaluationContext::PotentiallyEvaluated: 18252 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18253 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18254 FunctionScopes.back()->PossiblyUnreachableDiags. 18255 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18256 return true; 18257 } 18258 18259 // The initializer of a constexpr variable or of the first declaration of a 18260 // static data member is not syntactically a constant evaluated constant, 18261 // but nonetheless is always required to be a constant expression, so we 18262 // can skip diagnosing. 18263 // FIXME: Using the mangling context here is a hack. 18264 if (auto *VD = dyn_cast_or_null<VarDecl>( 18265 ExprEvalContexts.back().ManglingContextDecl)) { 18266 if (VD->isConstexpr() || 18267 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18268 break; 18269 // FIXME: For any other kind of variable, we should build a CFG for its 18270 // initializer and check whether the context in question is reachable. 18271 } 18272 18273 Diag(Loc, PD); 18274 return true; 18275 } 18276 18277 return false; 18278 } 18279 18280 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18281 const PartialDiagnostic &PD) { 18282 return DiagRuntimeBehavior( 18283 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18284 } 18285 18286 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18287 CallExpr *CE, FunctionDecl *FD) { 18288 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18289 return false; 18290 18291 // If we're inside a decltype's expression, don't check for a valid return 18292 // type or construct temporaries until we know whether this is the last call. 18293 if (ExprEvalContexts.back().ExprContext == 18294 ExpressionEvaluationContextRecord::EK_Decltype) { 18295 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18296 return false; 18297 } 18298 18299 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18300 FunctionDecl *FD; 18301 CallExpr *CE; 18302 18303 public: 18304 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18305 : FD(FD), CE(CE) { } 18306 18307 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18308 if (!FD) { 18309 S.Diag(Loc, diag::err_call_incomplete_return) 18310 << T << CE->getSourceRange(); 18311 return; 18312 } 18313 18314 S.Diag(Loc, diag::err_call_function_incomplete_return) 18315 << CE->getSourceRange() << FD->getDeclName() << T; 18316 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18317 << FD->getDeclName(); 18318 } 18319 } Diagnoser(FD, CE); 18320 18321 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18322 return true; 18323 18324 return false; 18325 } 18326 18327 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18328 // will prevent this condition from triggering, which is what we want. 18329 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18330 SourceLocation Loc; 18331 18332 unsigned diagnostic = diag::warn_condition_is_assignment; 18333 bool IsOrAssign = false; 18334 18335 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18336 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18337 return; 18338 18339 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18340 18341 // Greylist some idioms by putting them into a warning subcategory. 18342 if (ObjCMessageExpr *ME 18343 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18344 Selector Sel = ME->getSelector(); 18345 18346 // self = [<foo> init...] 18347 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18348 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18349 18350 // <foo> = [<bar> nextObject] 18351 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18352 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18353 } 18354 18355 Loc = Op->getOperatorLoc(); 18356 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18357 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18358 return; 18359 18360 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18361 Loc = Op->getOperatorLoc(); 18362 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18363 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18364 else { 18365 // Not an assignment. 18366 return; 18367 } 18368 18369 Diag(Loc, diagnostic) << E->getSourceRange(); 18370 18371 SourceLocation Open = E->getBeginLoc(); 18372 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18373 Diag(Loc, diag::note_condition_assign_silence) 18374 << FixItHint::CreateInsertion(Open, "(") 18375 << FixItHint::CreateInsertion(Close, ")"); 18376 18377 if (IsOrAssign) 18378 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18379 << FixItHint::CreateReplacement(Loc, "!="); 18380 else 18381 Diag(Loc, diag::note_condition_assign_to_comparison) 18382 << FixItHint::CreateReplacement(Loc, "=="); 18383 } 18384 18385 /// Redundant parentheses over an equality comparison can indicate 18386 /// that the user intended an assignment used as condition. 18387 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18388 // Don't warn if the parens came from a macro. 18389 SourceLocation parenLoc = ParenE->getBeginLoc(); 18390 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18391 return; 18392 // Don't warn for dependent expressions. 18393 if (ParenE->isTypeDependent()) 18394 return; 18395 18396 Expr *E = ParenE->IgnoreParens(); 18397 18398 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18399 if (opE->getOpcode() == BO_EQ && 18400 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18401 == Expr::MLV_Valid) { 18402 SourceLocation Loc = opE->getOperatorLoc(); 18403 18404 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18405 SourceRange ParenERange = ParenE->getSourceRange(); 18406 Diag(Loc, diag::note_equality_comparison_silence) 18407 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18408 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18409 Diag(Loc, diag::note_equality_comparison_to_assign) 18410 << FixItHint::CreateReplacement(Loc, "="); 18411 } 18412 } 18413 18414 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18415 bool IsConstexpr) { 18416 DiagnoseAssignmentAsCondition(E); 18417 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18418 DiagnoseEqualityWithExtraParens(parenE); 18419 18420 ExprResult result = CheckPlaceholderExpr(E); 18421 if (result.isInvalid()) return ExprError(); 18422 E = result.get(); 18423 18424 if (!E->isTypeDependent()) { 18425 if (getLangOpts().CPlusPlus) 18426 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18427 18428 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18429 if (ERes.isInvalid()) 18430 return ExprError(); 18431 E = ERes.get(); 18432 18433 QualType T = E->getType(); 18434 if (!T->isScalarType()) { // C99 6.8.4.1p1 18435 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18436 << T << E->getSourceRange(); 18437 return ExprError(); 18438 } 18439 CheckBoolLikeConversion(E, Loc); 18440 } 18441 18442 return E; 18443 } 18444 18445 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18446 Expr *SubExpr, ConditionKind CK) { 18447 // Empty conditions are valid in for-statements. 18448 if (!SubExpr) 18449 return ConditionResult(); 18450 18451 ExprResult Cond; 18452 switch (CK) { 18453 case ConditionKind::Boolean: 18454 Cond = CheckBooleanCondition(Loc, SubExpr); 18455 break; 18456 18457 case ConditionKind::ConstexprIf: 18458 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18459 break; 18460 18461 case ConditionKind::Switch: 18462 Cond = CheckSwitchCondition(Loc, SubExpr); 18463 break; 18464 } 18465 if (Cond.isInvalid()) 18466 return ConditionError(); 18467 18468 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18469 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18470 if (!FullExpr.get()) 18471 return ConditionError(); 18472 18473 return ConditionResult(*this, nullptr, FullExpr, 18474 CK == ConditionKind::ConstexprIf); 18475 } 18476 18477 namespace { 18478 /// A visitor for rebuilding a call to an __unknown_any expression 18479 /// to have an appropriate type. 18480 struct RebuildUnknownAnyFunction 18481 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18482 18483 Sema &S; 18484 18485 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18486 18487 ExprResult VisitStmt(Stmt *S) { 18488 llvm_unreachable("unexpected statement!"); 18489 } 18490 18491 ExprResult VisitExpr(Expr *E) { 18492 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18493 << E->getSourceRange(); 18494 return ExprError(); 18495 } 18496 18497 /// Rebuild an expression which simply semantically wraps another 18498 /// expression which it shares the type and value kind of. 18499 template <class T> ExprResult rebuildSugarExpr(T *E) { 18500 ExprResult SubResult = Visit(E->getSubExpr()); 18501 if (SubResult.isInvalid()) return ExprError(); 18502 18503 Expr *SubExpr = SubResult.get(); 18504 E->setSubExpr(SubExpr); 18505 E->setType(SubExpr->getType()); 18506 E->setValueKind(SubExpr->getValueKind()); 18507 assert(E->getObjectKind() == OK_Ordinary); 18508 return E; 18509 } 18510 18511 ExprResult VisitParenExpr(ParenExpr *E) { 18512 return rebuildSugarExpr(E); 18513 } 18514 18515 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18516 return rebuildSugarExpr(E); 18517 } 18518 18519 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18520 ExprResult SubResult = Visit(E->getSubExpr()); 18521 if (SubResult.isInvalid()) return ExprError(); 18522 18523 Expr *SubExpr = SubResult.get(); 18524 E->setSubExpr(SubExpr); 18525 E->setType(S.Context.getPointerType(SubExpr->getType())); 18526 assert(E->getValueKind() == VK_RValue); 18527 assert(E->getObjectKind() == OK_Ordinary); 18528 return E; 18529 } 18530 18531 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18532 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18533 18534 E->setType(VD->getType()); 18535 18536 assert(E->getValueKind() == VK_RValue); 18537 if (S.getLangOpts().CPlusPlus && 18538 !(isa<CXXMethodDecl>(VD) && 18539 cast<CXXMethodDecl>(VD)->isInstance())) 18540 E->setValueKind(VK_LValue); 18541 18542 return E; 18543 } 18544 18545 ExprResult VisitMemberExpr(MemberExpr *E) { 18546 return resolveDecl(E, E->getMemberDecl()); 18547 } 18548 18549 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18550 return resolveDecl(E, E->getDecl()); 18551 } 18552 }; 18553 } 18554 18555 /// Given a function expression of unknown-any type, try to rebuild it 18556 /// to have a function type. 18557 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18558 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18559 if (Result.isInvalid()) return ExprError(); 18560 return S.DefaultFunctionArrayConversion(Result.get()); 18561 } 18562 18563 namespace { 18564 /// A visitor for rebuilding an expression of type __unknown_anytype 18565 /// into one which resolves the type directly on the referring 18566 /// expression. Strict preservation of the original source 18567 /// structure is not a goal. 18568 struct RebuildUnknownAnyExpr 18569 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18570 18571 Sema &S; 18572 18573 /// The current destination type. 18574 QualType DestType; 18575 18576 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18577 : S(S), DestType(CastType) {} 18578 18579 ExprResult VisitStmt(Stmt *S) { 18580 llvm_unreachable("unexpected statement!"); 18581 } 18582 18583 ExprResult VisitExpr(Expr *E) { 18584 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18585 << E->getSourceRange(); 18586 return ExprError(); 18587 } 18588 18589 ExprResult VisitCallExpr(CallExpr *E); 18590 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18591 18592 /// Rebuild an expression which simply semantically wraps another 18593 /// expression which it shares the type and value kind of. 18594 template <class T> ExprResult rebuildSugarExpr(T *E) { 18595 ExprResult SubResult = Visit(E->getSubExpr()); 18596 if (SubResult.isInvalid()) return ExprError(); 18597 Expr *SubExpr = SubResult.get(); 18598 E->setSubExpr(SubExpr); 18599 E->setType(SubExpr->getType()); 18600 E->setValueKind(SubExpr->getValueKind()); 18601 assert(E->getObjectKind() == OK_Ordinary); 18602 return E; 18603 } 18604 18605 ExprResult VisitParenExpr(ParenExpr *E) { 18606 return rebuildSugarExpr(E); 18607 } 18608 18609 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18610 return rebuildSugarExpr(E); 18611 } 18612 18613 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18614 const PointerType *Ptr = DestType->getAs<PointerType>(); 18615 if (!Ptr) { 18616 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18617 << E->getSourceRange(); 18618 return ExprError(); 18619 } 18620 18621 if (isa<CallExpr>(E->getSubExpr())) { 18622 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18623 << E->getSourceRange(); 18624 return ExprError(); 18625 } 18626 18627 assert(E->getValueKind() == VK_RValue); 18628 assert(E->getObjectKind() == OK_Ordinary); 18629 E->setType(DestType); 18630 18631 // Build the sub-expression as if it were an object of the pointee type. 18632 DestType = Ptr->getPointeeType(); 18633 ExprResult SubResult = Visit(E->getSubExpr()); 18634 if (SubResult.isInvalid()) return ExprError(); 18635 E->setSubExpr(SubResult.get()); 18636 return E; 18637 } 18638 18639 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18640 18641 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18642 18643 ExprResult VisitMemberExpr(MemberExpr *E) { 18644 return resolveDecl(E, E->getMemberDecl()); 18645 } 18646 18647 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18648 return resolveDecl(E, E->getDecl()); 18649 } 18650 }; 18651 } 18652 18653 /// Rebuilds a call expression which yielded __unknown_anytype. 18654 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18655 Expr *CalleeExpr = E->getCallee(); 18656 18657 enum FnKind { 18658 FK_MemberFunction, 18659 FK_FunctionPointer, 18660 FK_BlockPointer 18661 }; 18662 18663 FnKind Kind; 18664 QualType CalleeType = CalleeExpr->getType(); 18665 if (CalleeType == S.Context.BoundMemberTy) { 18666 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18667 Kind = FK_MemberFunction; 18668 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18669 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18670 CalleeType = Ptr->getPointeeType(); 18671 Kind = FK_FunctionPointer; 18672 } else { 18673 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18674 Kind = FK_BlockPointer; 18675 } 18676 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18677 18678 // Verify that this is a legal result type of a function. 18679 if (DestType->isArrayType() || DestType->isFunctionType()) { 18680 unsigned diagID = diag::err_func_returning_array_function; 18681 if (Kind == FK_BlockPointer) 18682 diagID = diag::err_block_returning_array_function; 18683 18684 S.Diag(E->getExprLoc(), diagID) 18685 << DestType->isFunctionType() << DestType; 18686 return ExprError(); 18687 } 18688 18689 // Otherwise, go ahead and set DestType as the call's result. 18690 E->setType(DestType.getNonLValueExprType(S.Context)); 18691 E->setValueKind(Expr::getValueKindForType(DestType)); 18692 assert(E->getObjectKind() == OK_Ordinary); 18693 18694 // Rebuild the function type, replacing the result type with DestType. 18695 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18696 if (Proto) { 18697 // __unknown_anytype(...) is a special case used by the debugger when 18698 // it has no idea what a function's signature is. 18699 // 18700 // We want to build this call essentially under the K&R 18701 // unprototyped rules, but making a FunctionNoProtoType in C++ 18702 // would foul up all sorts of assumptions. However, we cannot 18703 // simply pass all arguments as variadic arguments, nor can we 18704 // portably just call the function under a non-variadic type; see 18705 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18706 // However, it turns out that in practice it is generally safe to 18707 // call a function declared as "A foo(B,C,D);" under the prototype 18708 // "A foo(B,C,D,...);". The only known exception is with the 18709 // Windows ABI, where any variadic function is implicitly cdecl 18710 // regardless of its normal CC. Therefore we change the parameter 18711 // types to match the types of the arguments. 18712 // 18713 // This is a hack, but it is far superior to moving the 18714 // corresponding target-specific code from IR-gen to Sema/AST. 18715 18716 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18717 SmallVector<QualType, 8> ArgTypes; 18718 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18719 ArgTypes.reserve(E->getNumArgs()); 18720 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18721 Expr *Arg = E->getArg(i); 18722 QualType ArgType = Arg->getType(); 18723 if (E->isLValue()) { 18724 ArgType = S.Context.getLValueReferenceType(ArgType); 18725 } else if (E->isXValue()) { 18726 ArgType = S.Context.getRValueReferenceType(ArgType); 18727 } 18728 ArgTypes.push_back(ArgType); 18729 } 18730 ParamTypes = ArgTypes; 18731 } 18732 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18733 Proto->getExtProtoInfo()); 18734 } else { 18735 DestType = S.Context.getFunctionNoProtoType(DestType, 18736 FnType->getExtInfo()); 18737 } 18738 18739 // Rebuild the appropriate pointer-to-function type. 18740 switch (Kind) { 18741 case FK_MemberFunction: 18742 // Nothing to do. 18743 break; 18744 18745 case FK_FunctionPointer: 18746 DestType = S.Context.getPointerType(DestType); 18747 break; 18748 18749 case FK_BlockPointer: 18750 DestType = S.Context.getBlockPointerType(DestType); 18751 break; 18752 } 18753 18754 // Finally, we can recurse. 18755 ExprResult CalleeResult = Visit(CalleeExpr); 18756 if (!CalleeResult.isUsable()) return ExprError(); 18757 E->setCallee(CalleeResult.get()); 18758 18759 // Bind a temporary if necessary. 18760 return S.MaybeBindToTemporary(E); 18761 } 18762 18763 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18764 // Verify that this is a legal result type of a call. 18765 if (DestType->isArrayType() || DestType->isFunctionType()) { 18766 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18767 << DestType->isFunctionType() << DestType; 18768 return ExprError(); 18769 } 18770 18771 // Rewrite the method result type if available. 18772 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18773 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18774 Method->setReturnType(DestType); 18775 } 18776 18777 // Change the type of the message. 18778 E->setType(DestType.getNonReferenceType()); 18779 E->setValueKind(Expr::getValueKindForType(DestType)); 18780 18781 return S.MaybeBindToTemporary(E); 18782 } 18783 18784 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18785 // The only case we should ever see here is a function-to-pointer decay. 18786 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18787 assert(E->getValueKind() == VK_RValue); 18788 assert(E->getObjectKind() == OK_Ordinary); 18789 18790 E->setType(DestType); 18791 18792 // Rebuild the sub-expression as the pointee (function) type. 18793 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18794 18795 ExprResult Result = Visit(E->getSubExpr()); 18796 if (!Result.isUsable()) return ExprError(); 18797 18798 E->setSubExpr(Result.get()); 18799 return E; 18800 } else if (E->getCastKind() == CK_LValueToRValue) { 18801 assert(E->getValueKind() == VK_RValue); 18802 assert(E->getObjectKind() == OK_Ordinary); 18803 18804 assert(isa<BlockPointerType>(E->getType())); 18805 18806 E->setType(DestType); 18807 18808 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18809 DestType = S.Context.getLValueReferenceType(DestType); 18810 18811 ExprResult Result = Visit(E->getSubExpr()); 18812 if (!Result.isUsable()) return ExprError(); 18813 18814 E->setSubExpr(Result.get()); 18815 return E; 18816 } else { 18817 llvm_unreachable("Unhandled cast type!"); 18818 } 18819 } 18820 18821 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18822 ExprValueKind ValueKind = VK_LValue; 18823 QualType Type = DestType; 18824 18825 // We know how to make this work for certain kinds of decls: 18826 18827 // - functions 18828 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18829 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18830 DestType = Ptr->getPointeeType(); 18831 ExprResult Result = resolveDecl(E, VD); 18832 if (Result.isInvalid()) return ExprError(); 18833 return S.ImpCastExprToType(Result.get(), Type, 18834 CK_FunctionToPointerDecay, VK_RValue); 18835 } 18836 18837 if (!Type->isFunctionType()) { 18838 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18839 << VD << E->getSourceRange(); 18840 return ExprError(); 18841 } 18842 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18843 // We must match the FunctionDecl's type to the hack introduced in 18844 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18845 // type. See the lengthy commentary in that routine. 18846 QualType FDT = FD->getType(); 18847 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18848 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18849 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18850 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18851 SourceLocation Loc = FD->getLocation(); 18852 FunctionDecl *NewFD = FunctionDecl::Create( 18853 S.Context, FD->getDeclContext(), Loc, Loc, 18854 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18855 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18856 /*ConstexprKind*/ CSK_unspecified); 18857 18858 if (FD->getQualifier()) 18859 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18860 18861 SmallVector<ParmVarDecl*, 16> Params; 18862 for (const auto &AI : FT->param_types()) { 18863 ParmVarDecl *Param = 18864 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18865 Param->setScopeInfo(0, Params.size()); 18866 Params.push_back(Param); 18867 } 18868 NewFD->setParams(Params); 18869 DRE->setDecl(NewFD); 18870 VD = DRE->getDecl(); 18871 } 18872 } 18873 18874 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18875 if (MD->isInstance()) { 18876 ValueKind = VK_RValue; 18877 Type = S.Context.BoundMemberTy; 18878 } 18879 18880 // Function references aren't l-values in C. 18881 if (!S.getLangOpts().CPlusPlus) 18882 ValueKind = VK_RValue; 18883 18884 // - variables 18885 } else if (isa<VarDecl>(VD)) { 18886 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18887 Type = RefTy->getPointeeType(); 18888 } else if (Type->isFunctionType()) { 18889 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18890 << VD << E->getSourceRange(); 18891 return ExprError(); 18892 } 18893 18894 // - nothing else 18895 } else { 18896 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18897 << VD << E->getSourceRange(); 18898 return ExprError(); 18899 } 18900 18901 // Modifying the declaration like this is friendly to IR-gen but 18902 // also really dangerous. 18903 VD->setType(DestType); 18904 E->setType(Type); 18905 E->setValueKind(ValueKind); 18906 return E; 18907 } 18908 18909 /// Check a cast of an unknown-any type. We intentionally only 18910 /// trigger this for C-style casts. 18911 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18912 Expr *CastExpr, CastKind &CastKind, 18913 ExprValueKind &VK, CXXCastPath &Path) { 18914 // The type we're casting to must be either void or complete. 18915 if (!CastType->isVoidType() && 18916 RequireCompleteType(TypeRange.getBegin(), CastType, 18917 diag::err_typecheck_cast_to_incomplete)) 18918 return ExprError(); 18919 18920 // Rewrite the casted expression from scratch. 18921 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18922 if (!result.isUsable()) return ExprError(); 18923 18924 CastExpr = result.get(); 18925 VK = CastExpr->getValueKind(); 18926 CastKind = CK_NoOp; 18927 18928 return CastExpr; 18929 } 18930 18931 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18932 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18933 } 18934 18935 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18936 Expr *arg, QualType ¶mType) { 18937 // If the syntactic form of the argument is not an explicit cast of 18938 // any sort, just do default argument promotion. 18939 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18940 if (!castArg) { 18941 ExprResult result = DefaultArgumentPromotion(arg); 18942 if (result.isInvalid()) return ExprError(); 18943 paramType = result.get()->getType(); 18944 return result; 18945 } 18946 18947 // Otherwise, use the type that was written in the explicit cast. 18948 assert(!arg->hasPlaceholderType()); 18949 paramType = castArg->getTypeAsWritten(); 18950 18951 // Copy-initialize a parameter of that type. 18952 InitializedEntity entity = 18953 InitializedEntity::InitializeParameter(Context, paramType, 18954 /*consumed*/ false); 18955 return PerformCopyInitialization(entity, callLoc, arg); 18956 } 18957 18958 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18959 Expr *orig = E; 18960 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18961 while (true) { 18962 E = E->IgnoreParenImpCasts(); 18963 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18964 E = call->getCallee(); 18965 diagID = diag::err_uncasted_call_of_unknown_any; 18966 } else { 18967 break; 18968 } 18969 } 18970 18971 SourceLocation loc; 18972 NamedDecl *d; 18973 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18974 loc = ref->getLocation(); 18975 d = ref->getDecl(); 18976 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18977 loc = mem->getMemberLoc(); 18978 d = mem->getMemberDecl(); 18979 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18980 diagID = diag::err_uncasted_call_of_unknown_any; 18981 loc = msg->getSelectorStartLoc(); 18982 d = msg->getMethodDecl(); 18983 if (!d) { 18984 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18985 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18986 << orig->getSourceRange(); 18987 return ExprError(); 18988 } 18989 } else { 18990 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18991 << E->getSourceRange(); 18992 return ExprError(); 18993 } 18994 18995 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18996 18997 // Never recoverable. 18998 return ExprError(); 18999 } 19000 19001 /// Check for operands with placeholder types and complain if found. 19002 /// Returns ExprError() if there was an error and no recovery was possible. 19003 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19004 if (!getLangOpts().CPlusPlus) { 19005 // C cannot handle TypoExpr nodes on either side of a binop because it 19006 // doesn't handle dependent types properly, so make sure any TypoExprs have 19007 // been dealt with before checking the operands. 19008 ExprResult Result = CorrectDelayedTyposInExpr(E); 19009 if (!Result.isUsable()) return ExprError(); 19010 E = Result.get(); 19011 } 19012 19013 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19014 if (!placeholderType) return E; 19015 19016 switch (placeholderType->getKind()) { 19017 19018 // Overloaded expressions. 19019 case BuiltinType::Overload: { 19020 // Try to resolve a single function template specialization. 19021 // This is obligatory. 19022 ExprResult Result = E; 19023 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19024 return Result; 19025 19026 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19027 // leaves Result unchanged on failure. 19028 Result = E; 19029 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19030 return Result; 19031 19032 // If that failed, try to recover with a call. 19033 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19034 /*complain*/ true); 19035 return Result; 19036 } 19037 19038 // Bound member functions. 19039 case BuiltinType::BoundMember: { 19040 ExprResult result = E; 19041 const Expr *BME = E->IgnoreParens(); 19042 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19043 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19044 if (isa<CXXPseudoDestructorExpr>(BME)) { 19045 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19046 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19047 if (ME->getMemberNameInfo().getName().getNameKind() == 19048 DeclarationName::CXXDestructorName) 19049 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19050 } 19051 tryToRecoverWithCall(result, PD, 19052 /*complain*/ true); 19053 return result; 19054 } 19055 19056 // ARC unbridged casts. 19057 case BuiltinType::ARCUnbridgedCast: { 19058 Expr *realCast = stripARCUnbridgedCast(E); 19059 diagnoseARCUnbridgedCast(realCast); 19060 return realCast; 19061 } 19062 19063 // Expressions of unknown type. 19064 case BuiltinType::UnknownAny: 19065 return diagnoseUnknownAnyExpr(*this, E); 19066 19067 // Pseudo-objects. 19068 case BuiltinType::PseudoObject: 19069 return checkPseudoObjectRValue(E); 19070 19071 case BuiltinType::BuiltinFn: { 19072 // Accept __noop without parens by implicitly converting it to a call expr. 19073 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19074 if (DRE) { 19075 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19076 if (FD->getBuiltinID() == Builtin::BI__noop) { 19077 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19078 CK_BuiltinFnToFnPtr) 19079 .get(); 19080 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19081 VK_RValue, SourceLocation()); 19082 } 19083 } 19084 19085 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19086 return ExprError(); 19087 } 19088 19089 case BuiltinType::IncompleteMatrixIdx: 19090 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19091 ->getRowIdx() 19092 ->getBeginLoc(), 19093 diag::err_matrix_incomplete_index); 19094 return ExprError(); 19095 19096 // Expressions of unknown type. 19097 case BuiltinType::OMPArraySection: 19098 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19099 return ExprError(); 19100 19101 // Expressions of unknown type. 19102 case BuiltinType::OMPArrayShaping: 19103 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19104 19105 case BuiltinType::OMPIterator: 19106 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19107 19108 // Everything else should be impossible. 19109 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19110 case BuiltinType::Id: 19111 #include "clang/Basic/OpenCLImageTypes.def" 19112 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19113 case BuiltinType::Id: 19114 #include "clang/Basic/OpenCLExtensionTypes.def" 19115 #define SVE_TYPE(Name, Id, SingletonId) \ 19116 case BuiltinType::Id: 19117 #include "clang/Basic/AArch64SVEACLETypes.def" 19118 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19119 #define PLACEHOLDER_TYPE(Id, SingletonId) 19120 #include "clang/AST/BuiltinTypes.def" 19121 break; 19122 } 19123 19124 llvm_unreachable("invalid placeholder type!"); 19125 } 19126 19127 bool Sema::CheckCaseExpression(Expr *E) { 19128 if (E->isTypeDependent()) 19129 return true; 19130 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19131 return E->getType()->isIntegralOrEnumerationType(); 19132 return false; 19133 } 19134 19135 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19136 ExprResult 19137 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19138 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19139 "Unknown Objective-C Boolean value!"); 19140 QualType BoolT = Context.ObjCBuiltinBoolTy; 19141 if (!Context.getBOOLDecl()) { 19142 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19143 Sema::LookupOrdinaryName); 19144 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19145 NamedDecl *ND = Result.getFoundDecl(); 19146 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19147 Context.setBOOLDecl(TD); 19148 } 19149 } 19150 if (Context.getBOOLDecl()) 19151 BoolT = Context.getBOOLType(); 19152 return new (Context) 19153 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19154 } 19155 19156 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19157 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19158 SourceLocation RParen) { 19159 19160 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19161 19162 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19163 return Spec.getPlatform() == Platform; 19164 }); 19165 19166 VersionTuple Version; 19167 if (Spec != AvailSpecs.end()) 19168 Version = Spec->getVersion(); 19169 19170 // The use of `@available` in the enclosing function should be analyzed to 19171 // warn when it's used inappropriately (i.e. not if(@available)). 19172 if (getCurFunctionOrMethodDecl()) 19173 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19174 else if (getCurBlock() || getCurLambda()) 19175 getCurFunction()->HasPotentialAvailabilityViolations = true; 19176 19177 return new (Context) 19178 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19179 } 19180 19181 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19182 ArrayRef<Expr *> SubExprs, QualType T) { 19183 if (!Context.getLangOpts().RecoveryAST) 19184 return ExprError(); 19185 19186 if (isSFINAEContext()) 19187 return ExprError(); 19188 19189 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19190 // We don't know the concrete type, fallback to dependent type. 19191 T = Context.DependentTy; 19192 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19193 } 19194