1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.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/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 } 70 71 // See if this function is unavailable. 72 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 73 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 74 return false; 75 76 return true; 77 } 78 79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 80 // Warn if this is used but marked unused. 81 if (const auto *A = D->getAttr<UnusedAttr>()) { 82 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 83 // should diagnose them. 84 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 85 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 86 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 87 if (DC && !DC->hasAttr<UnusedAttr>()) 88 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 89 } 90 } 91 } 92 93 /// Emit a note explaining that this function is deleted. 94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 95 assert(Decl->isDeleted()); 96 97 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 98 99 if (Method && Method->isDeleted() && Method->isDefaulted()) { 100 // If the method was explicitly defaulted, point at that declaration. 101 if (!Method->isImplicit()) 102 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 103 104 // Try to diagnose why this special member function was implicitly 105 // deleted. This might fail, if that reason no longer applies. 106 CXXSpecialMember CSM = getSpecialMember(Method); 107 if (CSM != CXXInvalid) 108 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 109 110 return; 111 } 112 113 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 114 if (Ctor && Ctor->isInheritingConstructor()) 115 return NoteDeletedInheritingConstructor(Ctor); 116 117 Diag(Decl->getLocation(), diag::note_availability_specified_here) 118 << Decl << true; 119 } 120 121 /// Determine whether a FunctionDecl was ever declared with an 122 /// explicit storage class. 123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 124 for (auto I : D->redecls()) { 125 if (I->getStorageClass() != SC_None) 126 return true; 127 } 128 return false; 129 } 130 131 /// Check whether we're in an extern inline function and referring to a 132 /// variable or function with internal linkage (C11 6.7.4p3). 133 /// 134 /// This is only a warning because we used to silently accept this code, but 135 /// in many cases it will not behave correctly. This is not enabled in C++ mode 136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 137 /// and so while there may still be user mistakes, most of the time we can't 138 /// prove that there are errors. 139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 140 const NamedDecl *D, 141 SourceLocation Loc) { 142 // This is disabled under C++; there are too many ways for this to fire in 143 // contexts where the warning is a false positive, or where it is technically 144 // correct but benign. 145 if (S.getLangOpts().CPlusPlus) 146 return; 147 148 // Check if this is an inlined function or method. 149 FunctionDecl *Current = S.getCurFunctionDecl(); 150 if (!Current) 151 return; 152 if (!Current->isInlined()) 153 return; 154 if (!Current->isExternallyVisible()) 155 return; 156 157 // Check if the decl has internal linkage. 158 if (D->getFormalLinkage() != InternalLinkage) 159 return; 160 161 // Downgrade from ExtWarn to Extension if 162 // (1) the supposedly external inline function is in the main file, 163 // and probably won't be included anywhere else. 164 // (2) the thing we're referencing is a pure function. 165 // (3) the thing we're referencing is another inline function. 166 // This last can give us false negatives, but it's better than warning on 167 // wrappers for simple C library functions. 168 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 169 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 170 if (!DowngradeWarning && UsedFn) 171 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 172 173 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 174 : diag::ext_internal_in_extern_inline) 175 << /*IsVar=*/!UsedFn << D; 176 177 S.MaybeSuggestAddingStaticToDecl(Current); 178 179 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 180 << D; 181 } 182 183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 184 const FunctionDecl *First = Cur->getFirstDecl(); 185 186 // Suggest "static" on the function, if possible. 187 if (!hasAnyExplicitStorageClass(First)) { 188 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 189 Diag(DeclBegin, diag::note_convert_inline_to_static) 190 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 191 } 192 } 193 194 /// Determine whether the use of this declaration is valid, and 195 /// emit any corresponding diagnostics. 196 /// 197 /// This routine diagnoses various problems with referencing 198 /// declarations that can occur when using a declaration. For example, 199 /// it might warn if a deprecated or unavailable declaration is being 200 /// used, or produce an error (and return true) if a C++0x deleted 201 /// function is being used. 202 /// 203 /// \returns true if there was an error (this declaration cannot be 204 /// referenced), false otherwise. 205 /// 206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 207 const ObjCInterfaceDecl *UnknownObjCClass, 208 bool ObjCPropertyAccess, 209 bool AvoidPartialAvailabilityChecks, 210 ObjCInterfaceDecl *ClassReceiver) { 211 SourceLocation Loc = Locs.front(); 212 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 213 // If there were any diagnostics suppressed by template argument deduction, 214 // emit them now. 215 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 216 if (Pos != SuppressedDiagnostics.end()) { 217 for (const PartialDiagnosticAt &Suppressed : Pos->second) 218 Diag(Suppressed.first, Suppressed.second); 219 220 // Clear out the list of suppressed diagnostics, so that we don't emit 221 // them again for this specialization. However, we don't obsolete this 222 // entry from the table, because we want to avoid ever emitting these 223 // diagnostics again. 224 Pos->second.clear(); 225 } 226 227 // C++ [basic.start.main]p3: 228 // The function 'main' shall not be used within a program. 229 if (cast<FunctionDecl>(D)->isMain()) 230 Diag(Loc, diag::ext_main_used); 231 } 232 233 // See if this is an auto-typed variable whose initializer we are parsing. 234 if (ParsingInitForAutoVars.count(D)) { 235 if (isa<BindingDecl>(D)) { 236 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 237 << D->getDeclName(); 238 } else { 239 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 240 << D->getDeclName() << cast<VarDecl>(D)->getType(); 241 } 242 return true; 243 } 244 245 // See if this is a deleted function. 246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 247 if (FD->isDeleted()) { 248 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 249 if (Ctor && Ctor->isInheritingConstructor()) 250 Diag(Loc, diag::err_deleted_inherited_ctor_use) 251 << Ctor->getParent() 252 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 253 else 254 Diag(Loc, diag::err_deleted_function_use); 255 NoteDeletedFunction(FD); 256 return true; 257 } 258 259 // If the function has a deduced return type, and we can't deduce it, 260 // then we can't use it either. 261 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 262 DeduceReturnType(FD, Loc)) 263 return true; 264 265 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 266 return true; 267 } 268 269 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 270 // Lambdas are only default-constructible or assignable in C++2a onwards. 271 if (MD->getParent()->isLambda() && 272 ((isa<CXXConstructorDecl>(MD) && 273 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 274 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 275 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 276 << !isa<CXXConstructorDecl>(MD); 277 } 278 } 279 280 auto getReferencedObjCProp = [](const NamedDecl *D) -> 281 const ObjCPropertyDecl * { 282 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 283 return MD->findPropertyDecl(); 284 return nullptr; 285 }; 286 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 287 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 288 return true; 289 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 290 return true; 291 } 292 293 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 294 // Only the variables omp_in and omp_out are allowed in the combiner. 295 // Only the variables omp_priv and omp_orig are allowed in the 296 // initializer-clause. 297 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 298 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 299 isa<VarDecl>(D)) { 300 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 301 << getCurFunction()->HasOMPDeclareReductionCombiner; 302 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 303 return true; 304 } 305 306 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 307 AvoidPartialAvailabilityChecks, ClassReceiver); 308 309 DiagnoseUnusedOfDecl(*this, D, Loc); 310 311 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 312 313 return false; 314 } 315 316 /// Retrieve the message suffix that should be added to a 317 /// diagnostic complaining about the given function being deleted or 318 /// unavailable. 319 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 320 std::string Message; 321 if (FD->getAvailability(&Message)) 322 return ": " + Message; 323 324 return std::string(); 325 } 326 327 /// DiagnoseSentinelCalls - This routine checks whether a call or 328 /// message-send is to a declaration with the sentinel attribute, and 329 /// if so, it checks that the requirements of the sentinel are 330 /// satisfied. 331 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 332 ArrayRef<Expr *> Args) { 333 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 334 if (!attr) 335 return; 336 337 // The number of formal parameters of the declaration. 338 unsigned numFormalParams; 339 340 // The kind of declaration. This is also an index into a %select in 341 // the diagnostic. 342 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 343 344 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 345 numFormalParams = MD->param_size(); 346 calleeType = CT_Method; 347 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 348 numFormalParams = FD->param_size(); 349 calleeType = CT_Function; 350 } else if (isa<VarDecl>(D)) { 351 QualType type = cast<ValueDecl>(D)->getType(); 352 const FunctionType *fn = nullptr; 353 if (const PointerType *ptr = type->getAs<PointerType>()) { 354 fn = ptr->getPointeeType()->getAs<FunctionType>(); 355 if (!fn) return; 356 calleeType = CT_Function; 357 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 358 fn = ptr->getPointeeType()->castAs<FunctionType>(); 359 calleeType = CT_Block; 360 } else { 361 return; 362 } 363 364 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 365 numFormalParams = proto->getNumParams(); 366 } else { 367 numFormalParams = 0; 368 } 369 } else { 370 return; 371 } 372 373 // "nullPos" is the number of formal parameters at the end which 374 // effectively count as part of the variadic arguments. This is 375 // useful if you would prefer to not have *any* formal parameters, 376 // but the language forces you to have at least one. 377 unsigned nullPos = attr->getNullPos(); 378 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 379 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 380 381 // The number of arguments which should follow the sentinel. 382 unsigned numArgsAfterSentinel = attr->getSentinel(); 383 384 // If there aren't enough arguments for all the formal parameters, 385 // the sentinel, and the args after the sentinel, complain. 386 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 387 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 388 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 389 return; 390 } 391 392 // Otherwise, find the sentinel expression. 393 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 394 if (!sentinelExpr) return; 395 if (sentinelExpr->isValueDependent()) return; 396 if (Context.isSentinelNullExpr(sentinelExpr)) return; 397 398 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 399 // or 'NULL' if those are actually defined in the context. Only use 400 // 'nil' for ObjC methods, where it's much more likely that the 401 // variadic arguments form a list of object pointers. 402 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 403 std::string NullValue; 404 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 405 NullValue = "nil"; 406 else if (getLangOpts().CPlusPlus11) 407 NullValue = "nullptr"; 408 else if (PP.isMacroDefined("NULL")) 409 NullValue = "NULL"; 410 else 411 NullValue = "(void*) 0"; 412 413 if (MissingNilLoc.isInvalid()) 414 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 415 else 416 Diag(MissingNilLoc, diag::warn_missing_sentinel) 417 << int(calleeType) 418 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 419 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 420 } 421 422 SourceRange Sema::getExprRange(Expr *E) const { 423 return E ? E->getSourceRange() : SourceRange(); 424 } 425 426 //===----------------------------------------------------------------------===// 427 // Standard Promotions and Conversions 428 //===----------------------------------------------------------------------===// 429 430 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 431 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 432 // Handle any placeholder expressions which made it here. 433 if (E->getType()->isPlaceholderType()) { 434 ExprResult result = CheckPlaceholderExpr(E); 435 if (result.isInvalid()) return ExprError(); 436 E = result.get(); 437 } 438 439 QualType Ty = E->getType(); 440 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 441 442 if (Ty->isFunctionType()) { 443 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 444 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 445 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 446 return ExprError(); 447 448 E = ImpCastExprToType(E, Context.getPointerType(Ty), 449 CK_FunctionToPointerDecay).get(); 450 } else if (Ty->isArrayType()) { 451 // In C90 mode, arrays only promote to pointers if the array expression is 452 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 453 // type 'array of type' is converted to an expression that has type 'pointer 454 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 455 // that has type 'array of type' ...". The relevant change is "an lvalue" 456 // (C90) to "an expression" (C99). 457 // 458 // C++ 4.2p1: 459 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 460 // T" can be converted to an rvalue of type "pointer to T". 461 // 462 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 463 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 464 CK_ArrayToPointerDecay).get(); 465 } 466 return E; 467 } 468 469 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 470 // Check to see if we are dereferencing a null pointer. If so, 471 // and if not volatile-qualified, this is undefined behavior that the 472 // optimizer will delete, so warn about it. People sometimes try to use this 473 // to get a deterministic trap and are surprised by clang's behavior. This 474 // only handles the pattern "*null", which is a very syntactic check. 475 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 476 if (UO->getOpcode() == UO_Deref && 477 UO->getSubExpr()->IgnoreParenCasts()-> 478 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 479 !UO->getType().isVolatileQualified()) { 480 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 481 S.PDiag(diag::warn_indirection_through_null) 482 << UO->getSubExpr()->getSourceRange()); 483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 484 S.PDiag(diag::note_indirection_through_null)); 485 } 486 } 487 488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 489 SourceLocation AssignLoc, 490 const Expr* RHS) { 491 const ObjCIvarDecl *IV = OIRE->getDecl(); 492 if (!IV) 493 return; 494 495 DeclarationName MemberName = IV->getDeclName(); 496 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 497 if (!Member || !Member->isStr("isa")) 498 return; 499 500 const Expr *Base = OIRE->getBase(); 501 QualType BaseType = Base->getType(); 502 if (OIRE->isArrow()) 503 BaseType = BaseType->getPointeeType(); 504 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 505 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 506 ObjCInterfaceDecl *ClassDeclared = nullptr; 507 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 508 if (!ClassDeclared->getSuperClass() 509 && (*ClassDeclared->ivar_begin()) == IV) { 510 if (RHS) { 511 NamedDecl *ObjectSetClass = 512 S.LookupSingleName(S.TUScope, 513 &S.Context.Idents.get("object_setClass"), 514 SourceLocation(), S.LookupOrdinaryName); 515 if (ObjectSetClass) { 516 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 518 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 519 "object_setClass(") 520 << FixItHint::CreateReplacement( 521 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 522 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 523 } 524 else 525 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 526 } else { 527 NamedDecl *ObjectGetClass = 528 S.LookupSingleName(S.TUScope, 529 &S.Context.Idents.get("object_getClass"), 530 SourceLocation(), S.LookupOrdinaryName); 531 if (ObjectGetClass) 532 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 533 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 534 "object_getClass(") 535 << FixItHint::CreateReplacement( 536 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 537 else 538 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 539 } 540 S.Diag(IV->getLocation(), diag::note_ivar_decl); 541 } 542 } 543 } 544 545 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 546 // Handle any placeholder expressions which made it here. 547 if (E->getType()->isPlaceholderType()) { 548 ExprResult result = CheckPlaceholderExpr(E); 549 if (result.isInvalid()) return ExprError(); 550 E = result.get(); 551 } 552 553 // C++ [conv.lval]p1: 554 // A glvalue of a non-function, non-array type T can be 555 // converted to a prvalue. 556 if (!E->isGLValue()) return E; 557 558 QualType T = E->getType(); 559 assert(!T.isNull() && "r-value conversion on typeless expression?"); 560 561 // We don't want to throw lvalue-to-rvalue casts on top of 562 // expressions of certain types in C++. 563 if (getLangOpts().CPlusPlus && 564 (E->getType() == Context.OverloadTy || 565 T->isDependentType() || 566 T->isRecordType())) 567 return E; 568 569 // The C standard is actually really unclear on this point, and 570 // DR106 tells us what the result should be but not why. It's 571 // generally best to say that void types just doesn't undergo 572 // lvalue-to-rvalue at all. Note that expressions of unqualified 573 // 'void' type are never l-values, but qualified void can be. 574 if (T->isVoidType()) 575 return E; 576 577 // OpenCL usually rejects direct accesses to values of 'half' type. 578 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 579 T->isHalfType()) { 580 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 581 << 0 << T; 582 return ExprError(); 583 } 584 585 CheckForNullPointerDereference(*this, E); 586 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 587 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 588 &Context.Idents.get("object_getClass"), 589 SourceLocation(), LookupOrdinaryName); 590 if (ObjectGetClass) 591 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 592 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 593 << FixItHint::CreateReplacement( 594 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 595 else 596 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 597 } 598 else if (const ObjCIvarRefExpr *OIRE = 599 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 600 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 601 602 // C++ [conv.lval]p1: 603 // [...] If T is a non-class type, the type of the prvalue is the 604 // cv-unqualified version of T. Otherwise, the type of the 605 // rvalue is T. 606 // 607 // C99 6.3.2.1p2: 608 // If the lvalue has qualified type, the value has the unqualified 609 // version of the type of the lvalue; otherwise, the value has the 610 // type of the lvalue. 611 if (T.hasQualifiers()) 612 T = T.getUnqualifiedType(); 613 614 // Under the MS ABI, lock down the inheritance model now. 615 if (T->isMemberPointerType() && 616 Context.getTargetInfo().getCXXABI().isMicrosoft()) 617 (void)isCompleteType(E->getExprLoc(), T); 618 619 UpdateMarkingForLValueToRValue(E); 620 621 // Loading a __weak object implicitly retains the value, so we need a cleanup to 622 // balance that. 623 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 624 Cleanup.setExprNeedsCleanups(true); 625 626 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 627 nullptr, VK_RValue); 628 629 // C11 6.3.2.1p2: 630 // ... if the lvalue has atomic type, the value has the non-atomic version 631 // of the type of the lvalue ... 632 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 633 T = Atomic->getValueType().getUnqualifiedType(); 634 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 635 nullptr, VK_RValue); 636 } 637 638 return Res; 639 } 640 641 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 642 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 643 if (Res.isInvalid()) 644 return ExprError(); 645 Res = DefaultLvalueConversion(Res.get()); 646 if (Res.isInvalid()) 647 return ExprError(); 648 return Res; 649 } 650 651 /// CallExprUnaryConversions - a special case of an unary conversion 652 /// performed on a function designator of a call expression. 653 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 654 QualType Ty = E->getType(); 655 ExprResult Res = E; 656 // Only do implicit cast for a function type, but not for a pointer 657 // to function type. 658 if (Ty->isFunctionType()) { 659 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 660 CK_FunctionToPointerDecay).get(); 661 if (Res.isInvalid()) 662 return ExprError(); 663 } 664 Res = DefaultLvalueConversion(Res.get()); 665 if (Res.isInvalid()) 666 return ExprError(); 667 return Res.get(); 668 } 669 670 /// UsualUnaryConversions - Performs various conversions that are common to most 671 /// operators (C99 6.3). The conversions of array and function types are 672 /// sometimes suppressed. For example, the array->pointer conversion doesn't 673 /// apply if the array is an argument to the sizeof or address (&) operators. 674 /// In these instances, this routine should *not* be called. 675 ExprResult Sema::UsualUnaryConversions(Expr *E) { 676 // First, convert to an r-value. 677 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 678 if (Res.isInvalid()) 679 return ExprError(); 680 E = Res.get(); 681 682 QualType Ty = E->getType(); 683 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 684 685 // Half FP have to be promoted to float unless it is natively supported 686 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 687 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 688 689 // Try to perform integral promotions if the object has a theoretically 690 // promotable type. 691 if (Ty->isIntegralOrUnscopedEnumerationType()) { 692 // C99 6.3.1.1p2: 693 // 694 // The following may be used in an expression wherever an int or 695 // unsigned int may be used: 696 // - an object or expression with an integer type whose integer 697 // conversion rank is less than or equal to the rank of int 698 // and unsigned int. 699 // - A bit-field of type _Bool, int, signed int, or unsigned int. 700 // 701 // If an int can represent all values of the original type, the 702 // value is converted to an int; otherwise, it is converted to an 703 // unsigned int. These are called the integer promotions. All 704 // other types are unchanged by the integer promotions. 705 706 QualType PTy = Context.isPromotableBitField(E); 707 if (!PTy.isNull()) { 708 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 709 return E; 710 } 711 if (Ty->isPromotableIntegerType()) { 712 QualType PT = Context.getPromotedIntegerType(Ty); 713 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 714 return E; 715 } 716 } 717 return E; 718 } 719 720 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 721 /// do not have a prototype. Arguments that have type float or __fp16 722 /// are promoted to double. All other argument types are converted by 723 /// UsualUnaryConversions(). 724 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 725 QualType Ty = E->getType(); 726 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 727 728 ExprResult Res = UsualUnaryConversions(E); 729 if (Res.isInvalid()) 730 return ExprError(); 731 E = Res.get(); 732 733 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 734 // promote to double. 735 // Note that default argument promotion applies only to float (and 736 // half/fp16); it does not apply to _Float16. 737 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 738 if (BTy && (BTy->getKind() == BuiltinType::Half || 739 BTy->getKind() == BuiltinType::Float)) { 740 if (getLangOpts().OpenCL && 741 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 742 if (BTy->getKind() == BuiltinType::Half) { 743 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 744 } 745 } else { 746 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 747 } 748 } 749 750 // C++ performs lvalue-to-rvalue conversion as a default argument 751 // promotion, even on class types, but note: 752 // C++11 [conv.lval]p2: 753 // When an lvalue-to-rvalue conversion occurs in an unevaluated 754 // operand or a subexpression thereof the value contained in the 755 // referenced object is not accessed. Otherwise, if the glvalue 756 // has a class type, the conversion copy-initializes a temporary 757 // of type T from the glvalue and the result of the conversion 758 // is a prvalue for the temporary. 759 // FIXME: add some way to gate this entire thing for correctness in 760 // potentially potentially evaluated contexts. 761 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 762 ExprResult Temp = PerformCopyInitialization( 763 InitializedEntity::InitializeTemporary(E->getType()), 764 E->getExprLoc(), E); 765 if (Temp.isInvalid()) 766 return ExprError(); 767 E = Temp.get(); 768 } 769 770 return E; 771 } 772 773 /// Determine the degree of POD-ness for an expression. 774 /// Incomplete types are considered POD, since this check can be performed 775 /// when we're in an unevaluated context. 776 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 777 if (Ty->isIncompleteType()) { 778 // C++11 [expr.call]p7: 779 // After these conversions, if the argument does not have arithmetic, 780 // enumeration, pointer, pointer to member, or class type, the program 781 // is ill-formed. 782 // 783 // Since we've already performed array-to-pointer and function-to-pointer 784 // decay, the only such type in C++ is cv void. This also handles 785 // initializer lists as variadic arguments. 786 if (Ty->isVoidType()) 787 return VAK_Invalid; 788 789 if (Ty->isObjCObjectType()) 790 return VAK_Invalid; 791 return VAK_Valid; 792 } 793 794 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 795 return VAK_Invalid; 796 797 if (Ty.isCXX98PODType(Context)) 798 return VAK_Valid; 799 800 // C++11 [expr.call]p7: 801 // Passing a potentially-evaluated argument of class type (Clause 9) 802 // having a non-trivial copy constructor, a non-trivial move constructor, 803 // or a non-trivial destructor, with no corresponding parameter, 804 // is conditionally-supported with implementation-defined semantics. 805 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 806 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 807 if (!Record->hasNonTrivialCopyConstructor() && 808 !Record->hasNonTrivialMoveConstructor() && 809 !Record->hasNonTrivialDestructor()) 810 return VAK_ValidInCXX11; 811 812 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 813 return VAK_Valid; 814 815 if (Ty->isObjCObjectType()) 816 return VAK_Invalid; 817 818 if (getLangOpts().MSVCCompat) 819 return VAK_MSVCUndefined; 820 821 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 822 // permitted to reject them. We should consider doing so. 823 return VAK_Undefined; 824 } 825 826 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 827 // Don't allow one to pass an Objective-C interface to a vararg. 828 const QualType &Ty = E->getType(); 829 VarArgKind VAK = isValidVarArgType(Ty); 830 831 // Complain about passing non-POD types through varargs. 832 switch (VAK) { 833 case VAK_ValidInCXX11: 834 DiagRuntimeBehavior( 835 E->getBeginLoc(), nullptr, 836 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 837 LLVM_FALLTHROUGH; 838 case VAK_Valid: 839 if (Ty->isRecordType()) { 840 // This is unlikely to be what the user intended. If the class has a 841 // 'c_str' member function, the user probably meant to call that. 842 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 843 PDiag(diag::warn_pass_class_arg_to_vararg) 844 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 845 } 846 break; 847 848 case VAK_Undefined: 849 case VAK_MSVCUndefined: 850 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 851 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 852 << getLangOpts().CPlusPlus11 << Ty << CT); 853 break; 854 855 case VAK_Invalid: 856 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 857 Diag(E->getBeginLoc(), 858 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 859 << Ty << CT; 860 else if (Ty->isObjCObjectType()) 861 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 862 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 863 << Ty << CT); 864 else 865 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 866 << isa<InitListExpr>(E) << Ty << CT; 867 break; 868 } 869 } 870 871 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 872 /// will create a trap if the resulting type is not a POD type. 873 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 874 FunctionDecl *FDecl) { 875 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 876 // Strip the unbridged-cast placeholder expression off, if applicable. 877 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 878 (CT == VariadicMethod || 879 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 880 E = stripARCUnbridgedCast(E); 881 882 // Otherwise, do normal placeholder checking. 883 } else { 884 ExprResult ExprRes = CheckPlaceholderExpr(E); 885 if (ExprRes.isInvalid()) 886 return ExprError(); 887 E = ExprRes.get(); 888 } 889 } 890 891 ExprResult ExprRes = DefaultArgumentPromotion(E); 892 if (ExprRes.isInvalid()) 893 return ExprError(); 894 E = ExprRes.get(); 895 896 // Diagnostics regarding non-POD argument types are 897 // emitted along with format string checking in Sema::CheckFunctionCall(). 898 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 899 // Turn this into a trap. 900 CXXScopeSpec SS; 901 SourceLocation TemplateKWLoc; 902 UnqualifiedId Name; 903 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 904 E->getBeginLoc()); 905 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 906 Name, true, false); 907 if (TrapFn.isInvalid()) 908 return ExprError(); 909 910 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 911 None, E->getEndLoc()); 912 if (Call.isInvalid()) 913 return ExprError(); 914 915 ExprResult Comma = 916 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 917 if (Comma.isInvalid()) 918 return ExprError(); 919 return Comma.get(); 920 } 921 922 if (!getLangOpts().CPlusPlus && 923 RequireCompleteType(E->getExprLoc(), E->getType(), 924 diag::err_call_incomplete_argument)) 925 return ExprError(); 926 927 return E; 928 } 929 930 /// Converts an integer to complex float type. Helper function of 931 /// UsualArithmeticConversions() 932 /// 933 /// \return false if the integer expression is an integer type and is 934 /// successfully converted to the complex type. 935 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 936 ExprResult &ComplexExpr, 937 QualType IntTy, 938 QualType ComplexTy, 939 bool SkipCast) { 940 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 941 if (SkipCast) return false; 942 if (IntTy->isIntegerType()) { 943 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 944 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 945 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 946 CK_FloatingRealToComplex); 947 } else { 948 assert(IntTy->isComplexIntegerType()); 949 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 950 CK_IntegralComplexToFloatingComplex); 951 } 952 return false; 953 } 954 955 /// Handle arithmetic conversion with complex types. Helper function of 956 /// UsualArithmeticConversions() 957 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 958 ExprResult &RHS, QualType LHSType, 959 QualType RHSType, 960 bool IsCompAssign) { 961 // if we have an integer operand, the result is the complex type. 962 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 963 /*skipCast*/false)) 964 return LHSType; 965 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 966 /*skipCast*/IsCompAssign)) 967 return RHSType; 968 969 // This handles complex/complex, complex/float, or float/complex. 970 // When both operands are complex, the shorter operand is converted to the 971 // type of the longer, and that is the type of the result. This corresponds 972 // to what is done when combining two real floating-point operands. 973 // The fun begins when size promotion occur across type domains. 974 // From H&S 6.3.4: When one operand is complex and the other is a real 975 // floating-point type, the less precise type is converted, within it's 976 // real or complex domain, to the precision of the other type. For example, 977 // when combining a "long double" with a "double _Complex", the 978 // "double _Complex" is promoted to "long double _Complex". 979 980 // Compute the rank of the two types, regardless of whether they are complex. 981 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 982 983 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 984 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 985 QualType LHSElementType = 986 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 987 QualType RHSElementType = 988 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 989 990 QualType ResultType = S.Context.getComplexType(LHSElementType); 991 if (Order < 0) { 992 // Promote the precision of the LHS if not an assignment. 993 ResultType = S.Context.getComplexType(RHSElementType); 994 if (!IsCompAssign) { 995 if (LHSComplexType) 996 LHS = 997 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 998 else 999 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1000 } 1001 } else if (Order > 0) { 1002 // Promote the precision of the RHS. 1003 if (RHSComplexType) 1004 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1005 else 1006 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1007 } 1008 return ResultType; 1009 } 1010 1011 /// Handle arithmetic conversion from integer to float. Helper function 1012 /// of UsualArithmeticConversions() 1013 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1014 ExprResult &IntExpr, 1015 QualType FloatTy, QualType IntTy, 1016 bool ConvertFloat, bool ConvertInt) { 1017 if (IntTy->isIntegerType()) { 1018 if (ConvertInt) 1019 // Convert intExpr to the lhs floating point type. 1020 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1021 CK_IntegralToFloating); 1022 return FloatTy; 1023 } 1024 1025 // Convert both sides to the appropriate complex float. 1026 assert(IntTy->isComplexIntegerType()); 1027 QualType result = S.Context.getComplexType(FloatTy); 1028 1029 // _Complex int -> _Complex float 1030 if (ConvertInt) 1031 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1032 CK_IntegralComplexToFloatingComplex); 1033 1034 // float -> _Complex float 1035 if (ConvertFloat) 1036 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1037 CK_FloatingRealToComplex); 1038 1039 return result; 1040 } 1041 1042 /// Handle arithmethic conversion with floating point types. Helper 1043 /// function of UsualArithmeticConversions() 1044 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1045 ExprResult &RHS, QualType LHSType, 1046 QualType RHSType, bool IsCompAssign) { 1047 bool LHSFloat = LHSType->isRealFloatingType(); 1048 bool RHSFloat = RHSType->isRealFloatingType(); 1049 1050 // If we have two real floating types, convert the smaller operand 1051 // to the bigger result. 1052 if (LHSFloat && RHSFloat) { 1053 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1054 if (order > 0) { 1055 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1056 return LHSType; 1057 } 1058 1059 assert(order < 0 && "illegal float comparison"); 1060 if (!IsCompAssign) 1061 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1062 return RHSType; 1063 } 1064 1065 if (LHSFloat) { 1066 // Half FP has to be promoted to float unless it is natively supported 1067 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1068 LHSType = S.Context.FloatTy; 1069 1070 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1071 /*convertFloat=*/!IsCompAssign, 1072 /*convertInt=*/ true); 1073 } 1074 assert(RHSFloat); 1075 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1076 /*convertInt=*/ true, 1077 /*convertFloat=*/!IsCompAssign); 1078 } 1079 1080 /// Diagnose attempts to convert between __float128 and long double if 1081 /// there is no support for such conversion. Helper function of 1082 /// UsualArithmeticConversions(). 1083 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1084 QualType RHSType) { 1085 /* No issue converting if at least one of the types is not a floating point 1086 type or the two types have the same rank. 1087 */ 1088 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1089 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1090 return false; 1091 1092 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1093 "The remaining types must be floating point types."); 1094 1095 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1096 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1097 1098 QualType LHSElemType = LHSComplex ? 1099 LHSComplex->getElementType() : LHSType; 1100 QualType RHSElemType = RHSComplex ? 1101 RHSComplex->getElementType() : RHSType; 1102 1103 // No issue if the two types have the same representation 1104 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1105 &S.Context.getFloatTypeSemantics(RHSElemType)) 1106 return false; 1107 1108 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1109 RHSElemType == S.Context.LongDoubleTy); 1110 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1111 RHSElemType == S.Context.Float128Ty); 1112 1113 // We've handled the situation where __float128 and long double have the same 1114 // representation. We allow all conversions for all possible long double types 1115 // except PPC's double double. 1116 return Float128AndLongDouble && 1117 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1118 &llvm::APFloat::PPCDoubleDouble()); 1119 } 1120 1121 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1122 1123 namespace { 1124 /// These helper callbacks are placed in an anonymous namespace to 1125 /// permit their use as function template parameters. 1126 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1127 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1128 } 1129 1130 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1131 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1132 CK_IntegralComplexCast); 1133 } 1134 } 1135 1136 /// Handle integer arithmetic conversions. Helper function of 1137 /// UsualArithmeticConversions() 1138 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1139 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1140 ExprResult &RHS, QualType LHSType, 1141 QualType RHSType, bool IsCompAssign) { 1142 // The rules for this case are in C99 6.3.1.8 1143 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1144 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1145 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1146 if (LHSSigned == RHSSigned) { 1147 // Same signedness; use the higher-ranked type 1148 if (order >= 0) { 1149 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1150 return LHSType; 1151 } else if (!IsCompAssign) 1152 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1153 return RHSType; 1154 } else if (order != (LHSSigned ? 1 : -1)) { 1155 // The unsigned type has greater than or equal rank to the 1156 // signed type, so use the unsigned type 1157 if (RHSSigned) { 1158 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1159 return LHSType; 1160 } else if (!IsCompAssign) 1161 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1162 return RHSType; 1163 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1164 // The two types are different widths; if we are here, that 1165 // means the signed type is larger than the unsigned type, so 1166 // use the signed type. 1167 if (LHSSigned) { 1168 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1169 return LHSType; 1170 } else if (!IsCompAssign) 1171 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1172 return RHSType; 1173 } else { 1174 // The signed type is higher-ranked than the unsigned type, 1175 // but isn't actually any bigger (like unsigned int and long 1176 // on most 32-bit systems). Use the unsigned type corresponding 1177 // to the signed type. 1178 QualType result = 1179 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1180 RHS = (*doRHSCast)(S, RHS.get(), result); 1181 if (!IsCompAssign) 1182 LHS = (*doLHSCast)(S, LHS.get(), result); 1183 return result; 1184 } 1185 } 1186 1187 /// Handle conversions with GCC complex int extension. Helper function 1188 /// of UsualArithmeticConversions() 1189 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1190 ExprResult &RHS, QualType LHSType, 1191 QualType RHSType, 1192 bool IsCompAssign) { 1193 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1194 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1195 1196 if (LHSComplexInt && RHSComplexInt) { 1197 QualType LHSEltType = LHSComplexInt->getElementType(); 1198 QualType RHSEltType = RHSComplexInt->getElementType(); 1199 QualType ScalarType = 1200 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1201 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1202 1203 return S.Context.getComplexType(ScalarType); 1204 } 1205 1206 if (LHSComplexInt) { 1207 QualType LHSEltType = LHSComplexInt->getElementType(); 1208 QualType ScalarType = 1209 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1210 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1211 QualType ComplexType = S.Context.getComplexType(ScalarType); 1212 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1213 CK_IntegralRealToComplex); 1214 1215 return ComplexType; 1216 } 1217 1218 assert(RHSComplexInt); 1219 1220 QualType RHSEltType = RHSComplexInt->getElementType(); 1221 QualType ScalarType = 1222 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1223 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1224 QualType ComplexType = S.Context.getComplexType(ScalarType); 1225 1226 if (!IsCompAssign) 1227 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1228 CK_IntegralRealToComplex); 1229 return ComplexType; 1230 } 1231 1232 /// UsualArithmeticConversions - Performs various conversions that are common to 1233 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1234 /// routine returns the first non-arithmetic type found. The client is 1235 /// responsible for emitting appropriate error diagnostics. 1236 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1237 bool IsCompAssign) { 1238 if (!IsCompAssign) { 1239 LHS = UsualUnaryConversions(LHS.get()); 1240 if (LHS.isInvalid()) 1241 return QualType(); 1242 } 1243 1244 RHS = UsualUnaryConversions(RHS.get()); 1245 if (RHS.isInvalid()) 1246 return QualType(); 1247 1248 // For conversion purposes, we ignore any qualifiers. 1249 // For example, "const float" and "float" are equivalent. 1250 QualType LHSType = 1251 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1252 QualType RHSType = 1253 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1254 1255 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1256 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1257 LHSType = AtomicLHS->getValueType(); 1258 1259 // If both types are identical, no conversion is needed. 1260 if (LHSType == RHSType) 1261 return LHSType; 1262 1263 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1264 // The caller can deal with this (e.g. pointer + int). 1265 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1266 return QualType(); 1267 1268 // Apply unary and bitfield promotions to the LHS's type. 1269 QualType LHSUnpromotedType = LHSType; 1270 if (LHSType->isPromotableIntegerType()) 1271 LHSType = Context.getPromotedIntegerType(LHSType); 1272 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1273 if (!LHSBitfieldPromoteTy.isNull()) 1274 LHSType = LHSBitfieldPromoteTy; 1275 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1276 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1277 1278 // If both types are identical, no conversion is needed. 1279 if (LHSType == RHSType) 1280 return LHSType; 1281 1282 // At this point, we have two different arithmetic types. 1283 1284 // Diagnose attempts to convert between __float128 and long double where 1285 // such conversions currently can't be handled. 1286 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1287 return QualType(); 1288 1289 // Handle complex types first (C99 6.3.1.8p1). 1290 if (LHSType->isComplexType() || RHSType->isComplexType()) 1291 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1292 IsCompAssign); 1293 1294 // Now handle "real" floating types (i.e. float, double, long double). 1295 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1296 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1297 IsCompAssign); 1298 1299 // Handle GCC complex int extension. 1300 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1301 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1302 IsCompAssign); 1303 1304 // Finally, we have two differing integer types. 1305 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1306 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1307 } 1308 1309 1310 //===----------------------------------------------------------------------===// 1311 // Semantic Analysis for various Expression Types 1312 //===----------------------------------------------------------------------===// 1313 1314 1315 ExprResult 1316 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1317 SourceLocation DefaultLoc, 1318 SourceLocation RParenLoc, 1319 Expr *ControllingExpr, 1320 ArrayRef<ParsedType> ArgTypes, 1321 ArrayRef<Expr *> ArgExprs) { 1322 unsigned NumAssocs = ArgTypes.size(); 1323 assert(NumAssocs == ArgExprs.size()); 1324 1325 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1326 for (unsigned i = 0; i < NumAssocs; ++i) { 1327 if (ArgTypes[i]) 1328 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1329 else 1330 Types[i] = nullptr; 1331 } 1332 1333 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1334 ControllingExpr, 1335 llvm::makeArrayRef(Types, NumAssocs), 1336 ArgExprs); 1337 delete [] Types; 1338 return ER; 1339 } 1340 1341 ExprResult 1342 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1343 SourceLocation DefaultLoc, 1344 SourceLocation RParenLoc, 1345 Expr *ControllingExpr, 1346 ArrayRef<TypeSourceInfo *> Types, 1347 ArrayRef<Expr *> Exprs) { 1348 unsigned NumAssocs = Types.size(); 1349 assert(NumAssocs == Exprs.size()); 1350 1351 // Decay and strip qualifiers for the controlling expression type, and handle 1352 // placeholder type replacement. See committee discussion from WG14 DR423. 1353 { 1354 EnterExpressionEvaluationContext Unevaluated( 1355 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1356 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1357 if (R.isInvalid()) 1358 return ExprError(); 1359 ControllingExpr = R.get(); 1360 } 1361 1362 // The controlling expression is an unevaluated operand, so side effects are 1363 // likely unintended. 1364 if (!inTemplateInstantiation() && 1365 ControllingExpr->HasSideEffects(Context, false)) 1366 Diag(ControllingExpr->getExprLoc(), 1367 diag::warn_side_effects_unevaluated_context); 1368 1369 bool TypeErrorFound = false, 1370 IsResultDependent = ControllingExpr->isTypeDependent(), 1371 ContainsUnexpandedParameterPack 1372 = ControllingExpr->containsUnexpandedParameterPack(); 1373 1374 for (unsigned i = 0; i < NumAssocs; ++i) { 1375 if (Exprs[i]->containsUnexpandedParameterPack()) 1376 ContainsUnexpandedParameterPack = true; 1377 1378 if (Types[i]) { 1379 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1380 ContainsUnexpandedParameterPack = true; 1381 1382 if (Types[i]->getType()->isDependentType()) { 1383 IsResultDependent = true; 1384 } else { 1385 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1386 // complete object type other than a variably modified type." 1387 unsigned D = 0; 1388 if (Types[i]->getType()->isIncompleteType()) 1389 D = diag::err_assoc_type_incomplete; 1390 else if (!Types[i]->getType()->isObjectType()) 1391 D = diag::err_assoc_type_nonobject; 1392 else if (Types[i]->getType()->isVariablyModifiedType()) 1393 D = diag::err_assoc_type_variably_modified; 1394 1395 if (D != 0) { 1396 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1397 << Types[i]->getTypeLoc().getSourceRange() 1398 << Types[i]->getType(); 1399 TypeErrorFound = true; 1400 } 1401 1402 // C11 6.5.1.1p2 "No two generic associations in the same generic 1403 // selection shall specify compatible types." 1404 for (unsigned j = i+1; j < NumAssocs; ++j) 1405 if (Types[j] && !Types[j]->getType()->isDependentType() && 1406 Context.typesAreCompatible(Types[i]->getType(), 1407 Types[j]->getType())) { 1408 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1409 diag::err_assoc_compatible_types) 1410 << Types[j]->getTypeLoc().getSourceRange() 1411 << Types[j]->getType() 1412 << Types[i]->getType(); 1413 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1414 diag::note_compat_assoc) 1415 << Types[i]->getTypeLoc().getSourceRange() 1416 << Types[i]->getType(); 1417 TypeErrorFound = true; 1418 } 1419 } 1420 } 1421 } 1422 if (TypeErrorFound) 1423 return ExprError(); 1424 1425 // If we determined that the generic selection is result-dependent, don't 1426 // try to compute the result expression. 1427 if (IsResultDependent) 1428 return new (Context) GenericSelectionExpr( 1429 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1430 ContainsUnexpandedParameterPack); 1431 1432 SmallVector<unsigned, 1> CompatIndices; 1433 unsigned DefaultIndex = -1U; 1434 for (unsigned i = 0; i < NumAssocs; ++i) { 1435 if (!Types[i]) 1436 DefaultIndex = i; 1437 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1438 Types[i]->getType())) 1439 CompatIndices.push_back(i); 1440 } 1441 1442 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1443 // type compatible with at most one of the types named in its generic 1444 // association list." 1445 if (CompatIndices.size() > 1) { 1446 // We strip parens here because the controlling expression is typically 1447 // parenthesized in macro definitions. 1448 ControllingExpr = ControllingExpr->IgnoreParens(); 1449 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1450 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1451 << (unsigned)CompatIndices.size(); 1452 for (unsigned I : CompatIndices) { 1453 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1454 diag::note_compat_assoc) 1455 << Types[I]->getTypeLoc().getSourceRange() 1456 << Types[I]->getType(); 1457 } 1458 return ExprError(); 1459 } 1460 1461 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1462 // its controlling expression shall have type compatible with exactly one of 1463 // the types named in its generic association list." 1464 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1465 // We strip parens here because the controlling expression is typically 1466 // parenthesized in macro definitions. 1467 ControllingExpr = ControllingExpr->IgnoreParens(); 1468 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1469 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1470 return ExprError(); 1471 } 1472 1473 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1474 // type name that is compatible with the type of the controlling expression, 1475 // then the result expression of the generic selection is the expression 1476 // in that generic association. Otherwise, the result expression of the 1477 // generic selection is the expression in the default generic association." 1478 unsigned ResultIndex = 1479 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1480 1481 return new (Context) GenericSelectionExpr( 1482 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1483 ContainsUnexpandedParameterPack, ResultIndex); 1484 } 1485 1486 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1487 /// location of the token and the offset of the ud-suffix within it. 1488 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1489 unsigned Offset) { 1490 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1491 S.getLangOpts()); 1492 } 1493 1494 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1495 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1496 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1497 IdentifierInfo *UDSuffix, 1498 SourceLocation UDSuffixLoc, 1499 ArrayRef<Expr*> Args, 1500 SourceLocation LitEndLoc) { 1501 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1502 1503 QualType ArgTy[2]; 1504 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1505 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1506 if (ArgTy[ArgIdx]->isArrayType()) 1507 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1508 } 1509 1510 DeclarationName OpName = 1511 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1512 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1513 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1514 1515 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1516 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1517 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1518 /*AllowStringTemplate*/ false, 1519 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1520 return ExprError(); 1521 1522 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1523 } 1524 1525 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1526 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1527 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1528 /// multiple tokens. However, the common case is that StringToks points to one 1529 /// string. 1530 /// 1531 ExprResult 1532 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1533 assert(!StringToks.empty() && "Must have at least one string!"); 1534 1535 StringLiteralParser Literal(StringToks, PP); 1536 if (Literal.hadError) 1537 return ExprError(); 1538 1539 SmallVector<SourceLocation, 4> StringTokLocs; 1540 for (const Token &Tok : StringToks) 1541 StringTokLocs.push_back(Tok.getLocation()); 1542 1543 QualType CharTy = Context.CharTy; 1544 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1545 if (Literal.isWide()) { 1546 CharTy = Context.getWideCharType(); 1547 Kind = StringLiteral::Wide; 1548 } else if (Literal.isUTF8()) { 1549 if (getLangOpts().Char8) 1550 CharTy = Context.Char8Ty; 1551 Kind = StringLiteral::UTF8; 1552 } else if (Literal.isUTF16()) { 1553 CharTy = Context.Char16Ty; 1554 Kind = StringLiteral::UTF16; 1555 } else if (Literal.isUTF32()) { 1556 CharTy = Context.Char32Ty; 1557 Kind = StringLiteral::UTF32; 1558 } else if (Literal.isPascal()) { 1559 CharTy = Context.UnsignedCharTy; 1560 } 1561 1562 QualType CharTyConst = CharTy; 1563 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1564 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1565 CharTyConst.addConst(); 1566 1567 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1568 1569 // Get an array type for the string, according to C99 6.4.5. This includes 1570 // the nul terminator character as well as the string length for pascal 1571 // strings. 1572 QualType StrTy = Context.getConstantArrayType( 1573 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1574 ArrayType::Normal, 0); 1575 1576 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1577 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1578 Kind, Literal.Pascal, StrTy, 1579 &StringTokLocs[0], 1580 StringTokLocs.size()); 1581 if (Literal.getUDSuffix().empty()) 1582 return Lit; 1583 1584 // We're building a user-defined literal. 1585 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1586 SourceLocation UDSuffixLoc = 1587 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1588 Literal.getUDSuffixOffset()); 1589 1590 // Make sure we're allowed user-defined literals here. 1591 if (!UDLScope) 1592 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1593 1594 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1595 // operator "" X (str, len) 1596 QualType SizeType = Context.getSizeType(); 1597 1598 DeclarationName OpName = 1599 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1600 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1601 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1602 1603 QualType ArgTy[] = { 1604 Context.getArrayDecayedType(StrTy), SizeType 1605 }; 1606 1607 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1608 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1609 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1610 /*AllowStringTemplate*/ true, 1611 /*DiagnoseMissing*/ true)) { 1612 1613 case LOLR_Cooked: { 1614 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1615 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1616 StringTokLocs[0]); 1617 Expr *Args[] = { Lit, LenArg }; 1618 1619 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1620 } 1621 1622 case LOLR_StringTemplate: { 1623 TemplateArgumentListInfo ExplicitArgs; 1624 1625 unsigned CharBits = Context.getIntWidth(CharTy); 1626 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1627 llvm::APSInt Value(CharBits, CharIsUnsigned); 1628 1629 TemplateArgument TypeArg(CharTy); 1630 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1631 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1632 1633 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1634 Value = Lit->getCodeUnit(I); 1635 TemplateArgument Arg(Context, Value, CharTy); 1636 TemplateArgumentLocInfo ArgInfo; 1637 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1638 } 1639 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1640 &ExplicitArgs); 1641 } 1642 case LOLR_Raw: 1643 case LOLR_Template: 1644 case LOLR_ErrorNoDiagnostic: 1645 llvm_unreachable("unexpected literal operator lookup result"); 1646 case LOLR_Error: 1647 return ExprError(); 1648 } 1649 llvm_unreachable("unexpected literal operator lookup result"); 1650 } 1651 1652 ExprResult 1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1654 SourceLocation Loc, 1655 const CXXScopeSpec *SS) { 1656 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1657 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1658 } 1659 1660 /// BuildDeclRefExpr - Build an expression that references a 1661 /// declaration that does not require a closure capture. 1662 ExprResult 1663 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1664 const DeclarationNameInfo &NameInfo, 1665 const CXXScopeSpec *SS, NamedDecl *FoundD, 1666 const TemplateArgumentListInfo *TemplateArgs) { 1667 bool RefersToCapturedVariable = 1668 isa<VarDecl>(D) && 1669 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1670 1671 DeclRefExpr *E; 1672 if (isa<VarTemplateSpecializationDecl>(D)) { 1673 VarTemplateSpecializationDecl *VarSpec = 1674 cast<VarTemplateSpecializationDecl>(D); 1675 1676 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1677 : NestedNameSpecifierLoc(), 1678 VarSpec->getTemplateKeywordLoc(), D, 1679 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1680 FoundD, TemplateArgs); 1681 } else { 1682 assert(!TemplateArgs && "No template arguments for non-variable" 1683 " template specialization references"); 1684 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1685 : NestedNameSpecifierLoc(), 1686 SourceLocation(), D, RefersToCapturedVariable, 1687 NameInfo, Ty, VK, FoundD); 1688 } 1689 1690 MarkDeclRefReferenced(E); 1691 1692 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1693 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1694 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1695 getCurFunction()->recordUseOfWeak(E); 1696 1697 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1698 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1699 FD = IFD->getAnonField(); 1700 if (FD) { 1701 UnusedPrivateFields.remove(FD); 1702 // Just in case we're building an illegal pointer-to-member. 1703 if (FD->isBitField()) 1704 E->setObjectKind(OK_BitField); 1705 } 1706 1707 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1708 // designates a bit-field. 1709 if (auto *BD = dyn_cast<BindingDecl>(D)) 1710 if (auto *BE = BD->getBinding()) 1711 E->setObjectKind(BE->getObjectKind()); 1712 1713 return E; 1714 } 1715 1716 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1717 /// possibly a list of template arguments. 1718 /// 1719 /// If this produces template arguments, it is permitted to call 1720 /// DecomposeTemplateName. 1721 /// 1722 /// This actually loses a lot of source location information for 1723 /// non-standard name kinds; we should consider preserving that in 1724 /// some way. 1725 void 1726 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1727 TemplateArgumentListInfo &Buffer, 1728 DeclarationNameInfo &NameInfo, 1729 const TemplateArgumentListInfo *&TemplateArgs) { 1730 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1731 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1732 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1733 1734 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1735 Id.TemplateId->NumArgs); 1736 translateTemplateArguments(TemplateArgsPtr, Buffer); 1737 1738 TemplateName TName = Id.TemplateId->Template.get(); 1739 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1740 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1741 TemplateArgs = &Buffer; 1742 } else { 1743 NameInfo = GetNameFromUnqualifiedId(Id); 1744 TemplateArgs = nullptr; 1745 } 1746 } 1747 1748 static void emitEmptyLookupTypoDiagnostic( 1749 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1750 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1751 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1752 DeclContext *Ctx = 1753 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1754 if (!TC) { 1755 // Emit a special diagnostic for failed member lookups. 1756 // FIXME: computing the declaration context might fail here (?) 1757 if (Ctx) 1758 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1759 << SS.getRange(); 1760 else 1761 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1762 return; 1763 } 1764 1765 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1766 bool DroppedSpecifier = 1767 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1768 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1769 ? diag::note_implicit_param_decl 1770 : diag::note_previous_decl; 1771 if (!Ctx) 1772 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1773 SemaRef.PDiag(NoteID)); 1774 else 1775 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1776 << Typo << Ctx << DroppedSpecifier 1777 << SS.getRange(), 1778 SemaRef.PDiag(NoteID)); 1779 } 1780 1781 /// Diagnose an empty lookup. 1782 /// 1783 /// \return false if new lookup candidates were found 1784 bool 1785 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1786 std::unique_ptr<CorrectionCandidateCallback> CCC, 1787 TemplateArgumentListInfo *ExplicitTemplateArgs, 1788 ArrayRef<Expr *> Args, TypoExpr **Out) { 1789 DeclarationName Name = R.getLookupName(); 1790 1791 unsigned diagnostic = diag::err_undeclared_var_use; 1792 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1793 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1794 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1795 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1796 diagnostic = diag::err_undeclared_use; 1797 diagnostic_suggest = diag::err_undeclared_use_suggest; 1798 } 1799 1800 // If the original lookup was an unqualified lookup, fake an 1801 // unqualified lookup. This is useful when (for example) the 1802 // original lookup would not have found something because it was a 1803 // dependent name. 1804 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1805 while (DC) { 1806 if (isa<CXXRecordDecl>(DC)) { 1807 LookupQualifiedName(R, DC); 1808 1809 if (!R.empty()) { 1810 // Don't give errors about ambiguities in this lookup. 1811 R.suppressDiagnostics(); 1812 1813 // During a default argument instantiation the CurContext points 1814 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1815 // function parameter list, hence add an explicit check. 1816 bool isDefaultArgument = 1817 !CodeSynthesisContexts.empty() && 1818 CodeSynthesisContexts.back().Kind == 1819 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1820 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1821 bool isInstance = CurMethod && 1822 CurMethod->isInstance() && 1823 DC == CurMethod->getParent() && !isDefaultArgument; 1824 1825 // Give a code modification hint to insert 'this->'. 1826 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1827 // Actually quite difficult! 1828 if (getLangOpts().MSVCCompat) 1829 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1830 if (isInstance) { 1831 Diag(R.getNameLoc(), diagnostic) << Name 1832 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1833 CheckCXXThisCapture(R.getNameLoc()); 1834 } else { 1835 Diag(R.getNameLoc(), diagnostic) << Name; 1836 } 1837 1838 // Do we really want to note all of these? 1839 for (NamedDecl *D : R) 1840 Diag(D->getLocation(), diag::note_dependent_var_use); 1841 1842 // Return true if we are inside a default argument instantiation 1843 // and the found name refers to an instance member function, otherwise 1844 // the function calling DiagnoseEmptyLookup will try to create an 1845 // implicit member call and this is wrong for default argument. 1846 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1847 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1848 return true; 1849 } 1850 1851 // Tell the callee to try to recover. 1852 return false; 1853 } 1854 1855 R.clear(); 1856 } 1857 1858 // In Microsoft mode, if we are performing lookup from within a friend 1859 // function definition declared at class scope then we must set 1860 // DC to the lexical parent to be able to search into the parent 1861 // class. 1862 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1863 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1864 DC->getLexicalParent()->isRecord()) 1865 DC = DC->getLexicalParent(); 1866 else 1867 DC = DC->getParent(); 1868 } 1869 1870 // We didn't find anything, so try to correct for a typo. 1871 TypoCorrection Corrected; 1872 if (S && Out) { 1873 SourceLocation TypoLoc = R.getNameLoc(); 1874 assert(!ExplicitTemplateArgs && 1875 "Diagnosing an empty lookup with explicit template args!"); 1876 *Out = CorrectTypoDelayed( 1877 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1878 [=](const TypoCorrection &TC) { 1879 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1880 diagnostic, diagnostic_suggest); 1881 }, 1882 nullptr, CTK_ErrorRecovery); 1883 if (*Out) 1884 return true; 1885 } else if (S && (Corrected = 1886 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1887 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1888 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1889 bool DroppedSpecifier = 1890 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1891 R.setLookupName(Corrected.getCorrection()); 1892 1893 bool AcceptableWithRecovery = false; 1894 bool AcceptableWithoutRecovery = false; 1895 NamedDecl *ND = Corrected.getFoundDecl(); 1896 if (ND) { 1897 if (Corrected.isOverloaded()) { 1898 OverloadCandidateSet OCS(R.getNameLoc(), 1899 OverloadCandidateSet::CSK_Normal); 1900 OverloadCandidateSet::iterator Best; 1901 for (NamedDecl *CD : Corrected) { 1902 if (FunctionTemplateDecl *FTD = 1903 dyn_cast<FunctionTemplateDecl>(CD)) 1904 AddTemplateOverloadCandidate( 1905 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1906 Args, OCS); 1907 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1908 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1909 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1910 Args, OCS); 1911 } 1912 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1913 case OR_Success: 1914 ND = Best->FoundDecl; 1915 Corrected.setCorrectionDecl(ND); 1916 break; 1917 default: 1918 // FIXME: Arbitrarily pick the first declaration for the note. 1919 Corrected.setCorrectionDecl(ND); 1920 break; 1921 } 1922 } 1923 R.addDecl(ND); 1924 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1925 CXXRecordDecl *Record = nullptr; 1926 if (Corrected.getCorrectionSpecifier()) { 1927 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1928 Record = Ty->getAsCXXRecordDecl(); 1929 } 1930 if (!Record) 1931 Record = cast<CXXRecordDecl>( 1932 ND->getDeclContext()->getRedeclContext()); 1933 R.setNamingClass(Record); 1934 } 1935 1936 auto *UnderlyingND = ND->getUnderlyingDecl(); 1937 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1938 isa<FunctionTemplateDecl>(UnderlyingND); 1939 // FIXME: If we ended up with a typo for a type name or 1940 // Objective-C class name, we're in trouble because the parser 1941 // is in the wrong place to recover. Suggest the typo 1942 // correction, but don't make it a fix-it since we're not going 1943 // to recover well anyway. 1944 AcceptableWithoutRecovery = 1945 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1946 } else { 1947 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1948 // because we aren't able to recover. 1949 AcceptableWithoutRecovery = true; 1950 } 1951 1952 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1953 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1954 ? diag::note_implicit_param_decl 1955 : diag::note_previous_decl; 1956 if (SS.isEmpty()) 1957 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1958 PDiag(NoteID), AcceptableWithRecovery); 1959 else 1960 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1961 << Name << computeDeclContext(SS, false) 1962 << DroppedSpecifier << SS.getRange(), 1963 PDiag(NoteID), AcceptableWithRecovery); 1964 1965 // Tell the callee whether to try to recover. 1966 return !AcceptableWithRecovery; 1967 } 1968 } 1969 R.clear(); 1970 1971 // Emit a special diagnostic for failed member lookups. 1972 // FIXME: computing the declaration context might fail here (?) 1973 if (!SS.isEmpty()) { 1974 Diag(R.getNameLoc(), diag::err_no_member) 1975 << Name << computeDeclContext(SS, false) 1976 << SS.getRange(); 1977 return true; 1978 } 1979 1980 // Give up, we can't recover. 1981 Diag(R.getNameLoc(), diagnostic) << Name; 1982 return true; 1983 } 1984 1985 /// In Microsoft mode, if we are inside a template class whose parent class has 1986 /// dependent base classes, and we can't resolve an unqualified identifier, then 1987 /// assume the identifier is a member of a dependent base class. We can only 1988 /// recover successfully in static methods, instance methods, and other contexts 1989 /// where 'this' is available. This doesn't precisely match MSVC's 1990 /// instantiation model, but it's close enough. 1991 static Expr * 1992 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1993 DeclarationNameInfo &NameInfo, 1994 SourceLocation TemplateKWLoc, 1995 const TemplateArgumentListInfo *TemplateArgs) { 1996 // Only try to recover from lookup into dependent bases in static methods or 1997 // contexts where 'this' is available. 1998 QualType ThisType = S.getCurrentThisType(); 1999 const CXXRecordDecl *RD = nullptr; 2000 if (!ThisType.isNull()) 2001 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2002 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2003 RD = MD->getParent(); 2004 if (!RD || !RD->hasAnyDependentBases()) 2005 return nullptr; 2006 2007 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2008 // is available, suggest inserting 'this->' as a fixit. 2009 SourceLocation Loc = NameInfo.getLoc(); 2010 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2011 DB << NameInfo.getName() << RD; 2012 2013 if (!ThisType.isNull()) { 2014 DB << FixItHint::CreateInsertion(Loc, "this->"); 2015 return CXXDependentScopeMemberExpr::Create( 2016 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2017 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2018 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2019 } 2020 2021 // Synthesize a fake NNS that points to the derived class. This will 2022 // perform name lookup during template instantiation. 2023 CXXScopeSpec SS; 2024 auto *NNS = 2025 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2026 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2027 return DependentScopeDeclRefExpr::Create( 2028 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2029 TemplateArgs); 2030 } 2031 2032 ExprResult 2033 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2034 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2035 bool HasTrailingLParen, bool IsAddressOfOperand, 2036 std::unique_ptr<CorrectionCandidateCallback> CCC, 2037 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2038 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2039 "cannot be direct & operand and have a trailing lparen"); 2040 if (SS.isInvalid()) 2041 return ExprError(); 2042 2043 TemplateArgumentListInfo TemplateArgsBuffer; 2044 2045 // Decompose the UnqualifiedId into the following data. 2046 DeclarationNameInfo NameInfo; 2047 const TemplateArgumentListInfo *TemplateArgs; 2048 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2049 2050 DeclarationName Name = NameInfo.getName(); 2051 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2052 SourceLocation NameLoc = NameInfo.getLoc(); 2053 2054 if (II && II->isEditorPlaceholder()) { 2055 // FIXME: When typed placeholders are supported we can create a typed 2056 // placeholder expression node. 2057 return ExprError(); 2058 } 2059 2060 // C++ [temp.dep.expr]p3: 2061 // An id-expression is type-dependent if it contains: 2062 // -- an identifier that was declared with a dependent type, 2063 // (note: handled after lookup) 2064 // -- a template-id that is dependent, 2065 // (note: handled in BuildTemplateIdExpr) 2066 // -- a conversion-function-id that specifies a dependent type, 2067 // -- a nested-name-specifier that contains a class-name that 2068 // names a dependent type. 2069 // Determine whether this is a member of an unknown specialization; 2070 // we need to handle these differently. 2071 bool DependentID = false; 2072 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2073 Name.getCXXNameType()->isDependentType()) { 2074 DependentID = true; 2075 } else if (SS.isSet()) { 2076 if (DeclContext *DC = computeDeclContext(SS, false)) { 2077 if (RequireCompleteDeclContext(SS, DC)) 2078 return ExprError(); 2079 } else { 2080 DependentID = true; 2081 } 2082 } 2083 2084 if (DependentID) 2085 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2086 IsAddressOfOperand, TemplateArgs); 2087 2088 // Perform the required lookup. 2089 LookupResult R(*this, NameInfo, 2090 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2091 ? LookupObjCImplicitSelfParam 2092 : LookupOrdinaryName); 2093 if (TemplateKWLoc.isValid() || TemplateArgs) { 2094 // Lookup the template name again to correctly establish the context in 2095 // which it was found. This is really unfortunate as we already did the 2096 // lookup to determine that it was a template name in the first place. If 2097 // this becomes a performance hit, we can work harder to preserve those 2098 // results until we get here but it's likely not worth it. 2099 bool MemberOfUnknownSpecialization; 2100 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2101 MemberOfUnknownSpecialization, TemplateKWLoc)) 2102 return ExprError(); 2103 2104 if (MemberOfUnknownSpecialization || 2105 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2106 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2107 IsAddressOfOperand, TemplateArgs); 2108 } else { 2109 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2110 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2111 2112 // If the result might be in a dependent base class, this is a dependent 2113 // id-expression. 2114 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2115 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2116 IsAddressOfOperand, TemplateArgs); 2117 2118 // If this reference is in an Objective-C method, then we need to do 2119 // some special Objective-C lookup, too. 2120 if (IvarLookupFollowUp) { 2121 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2122 if (E.isInvalid()) 2123 return ExprError(); 2124 2125 if (Expr *Ex = E.getAs<Expr>()) 2126 return Ex; 2127 } 2128 } 2129 2130 if (R.isAmbiguous()) 2131 return ExprError(); 2132 2133 // This could be an implicitly declared function reference (legal in C90, 2134 // extension in C99, forbidden in C++). 2135 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2136 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2137 if (D) R.addDecl(D); 2138 } 2139 2140 // Determine whether this name might be a candidate for 2141 // argument-dependent lookup. 2142 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2143 2144 if (R.empty() && !ADL) { 2145 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2146 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2147 TemplateKWLoc, TemplateArgs)) 2148 return E; 2149 } 2150 2151 // Don't diagnose an empty lookup for inline assembly. 2152 if (IsInlineAsmIdentifier) 2153 return ExprError(); 2154 2155 // If this name wasn't predeclared and if this is not a function 2156 // call, diagnose the problem. 2157 TypoExpr *TE = nullptr; 2158 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2159 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2160 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2161 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2162 "Typo correction callback misconfigured"); 2163 if (CCC) { 2164 // Make sure the callback knows what the typo being diagnosed is. 2165 CCC->setTypoName(II); 2166 if (SS.isValid()) 2167 CCC->setTypoNNS(SS.getScopeRep()); 2168 } 2169 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2170 // a template name, but we happen to have always already looked up the name 2171 // before we get here if it must be a template name. 2172 if (DiagnoseEmptyLookup(S, SS, R, 2173 CCC ? std::move(CCC) : std::move(DefaultValidator), 2174 nullptr, None, &TE)) { 2175 if (TE && KeywordReplacement) { 2176 auto &State = getTypoExprState(TE); 2177 auto BestTC = State.Consumer->getNextCorrection(); 2178 if (BestTC.isKeyword()) { 2179 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2180 if (State.DiagHandler) 2181 State.DiagHandler(BestTC); 2182 KeywordReplacement->startToken(); 2183 KeywordReplacement->setKind(II->getTokenID()); 2184 KeywordReplacement->setIdentifierInfo(II); 2185 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2186 // Clean up the state associated with the TypoExpr, since it has 2187 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2188 clearDelayedTypo(TE); 2189 // Signal that a correction to a keyword was performed by returning a 2190 // valid-but-null ExprResult. 2191 return (Expr*)nullptr; 2192 } 2193 State.Consumer->resetCorrectionStream(); 2194 } 2195 return TE ? TE : ExprError(); 2196 } 2197 2198 assert(!R.empty() && 2199 "DiagnoseEmptyLookup returned false but added no results"); 2200 2201 // If we found an Objective-C instance variable, let 2202 // LookupInObjCMethod build the appropriate expression to 2203 // reference the ivar. 2204 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2205 R.clear(); 2206 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2207 // In a hopelessly buggy code, Objective-C instance variable 2208 // lookup fails and no expression will be built to reference it. 2209 if (!E.isInvalid() && !E.get()) 2210 return ExprError(); 2211 return E; 2212 } 2213 } 2214 2215 // This is guaranteed from this point on. 2216 assert(!R.empty() || ADL); 2217 2218 // Check whether this might be a C++ implicit instance member access. 2219 // C++ [class.mfct.non-static]p3: 2220 // When an id-expression that is not part of a class member access 2221 // syntax and not used to form a pointer to member is used in the 2222 // body of a non-static member function of class X, if name lookup 2223 // resolves the name in the id-expression to a non-static non-type 2224 // member of some class C, the id-expression is transformed into a 2225 // class member access expression using (*this) as the 2226 // postfix-expression to the left of the . operator. 2227 // 2228 // But we don't actually need to do this for '&' operands if R 2229 // resolved to a function or overloaded function set, because the 2230 // expression is ill-formed if it actually works out to be a 2231 // non-static member function: 2232 // 2233 // C++ [expr.ref]p4: 2234 // Otherwise, if E1.E2 refers to a non-static member function. . . 2235 // [t]he expression can be used only as the left-hand operand of a 2236 // member function call. 2237 // 2238 // There are other safeguards against such uses, but it's important 2239 // to get this right here so that we don't end up making a 2240 // spuriously dependent expression if we're inside a dependent 2241 // instance method. 2242 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2243 bool MightBeImplicitMember; 2244 if (!IsAddressOfOperand) 2245 MightBeImplicitMember = true; 2246 else if (!SS.isEmpty()) 2247 MightBeImplicitMember = false; 2248 else if (R.isOverloadedResult()) 2249 MightBeImplicitMember = false; 2250 else if (R.isUnresolvableResult()) 2251 MightBeImplicitMember = true; 2252 else 2253 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2254 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2255 isa<MSPropertyDecl>(R.getFoundDecl()); 2256 2257 if (MightBeImplicitMember) 2258 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2259 R, TemplateArgs, S); 2260 } 2261 2262 if (TemplateArgs || TemplateKWLoc.isValid()) { 2263 2264 // In C++1y, if this is a variable template id, then check it 2265 // in BuildTemplateIdExpr(). 2266 // The single lookup result must be a variable template declaration. 2267 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2268 Id.TemplateId->Kind == TNK_Var_template) { 2269 assert(R.getAsSingle<VarTemplateDecl>() && 2270 "There should only be one declaration found."); 2271 } 2272 2273 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2274 } 2275 2276 return BuildDeclarationNameExpr(SS, R, ADL); 2277 } 2278 2279 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2280 /// declaration name, generally during template instantiation. 2281 /// There's a large number of things which don't need to be done along 2282 /// this path. 2283 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2284 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2285 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2286 DeclContext *DC = computeDeclContext(SS, false); 2287 if (!DC) 2288 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2289 NameInfo, /*TemplateArgs=*/nullptr); 2290 2291 if (RequireCompleteDeclContext(SS, DC)) 2292 return ExprError(); 2293 2294 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2295 LookupQualifiedName(R, DC); 2296 2297 if (R.isAmbiguous()) 2298 return ExprError(); 2299 2300 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2301 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2302 NameInfo, /*TemplateArgs=*/nullptr); 2303 2304 if (R.empty()) { 2305 Diag(NameInfo.getLoc(), diag::err_no_member) 2306 << NameInfo.getName() << DC << SS.getRange(); 2307 return ExprError(); 2308 } 2309 2310 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2311 // Diagnose a missing typename if this resolved unambiguously to a type in 2312 // a dependent context. If we can recover with a type, downgrade this to 2313 // a warning in Microsoft compatibility mode. 2314 unsigned DiagID = diag::err_typename_missing; 2315 if (RecoveryTSI && getLangOpts().MSVCCompat) 2316 DiagID = diag::ext_typename_missing; 2317 SourceLocation Loc = SS.getBeginLoc(); 2318 auto D = Diag(Loc, DiagID); 2319 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2320 << SourceRange(Loc, NameInfo.getEndLoc()); 2321 2322 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2323 // context. 2324 if (!RecoveryTSI) 2325 return ExprError(); 2326 2327 // Only issue the fixit if we're prepared to recover. 2328 D << FixItHint::CreateInsertion(Loc, "typename "); 2329 2330 // Recover by pretending this was an elaborated type. 2331 QualType Ty = Context.getTypeDeclType(TD); 2332 TypeLocBuilder TLB; 2333 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2334 2335 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2336 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2337 QTL.setElaboratedKeywordLoc(SourceLocation()); 2338 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2339 2340 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2341 2342 return ExprEmpty(); 2343 } 2344 2345 // Defend against this resolving to an implicit member access. We usually 2346 // won't get here if this might be a legitimate a class member (we end up in 2347 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2348 // a pointer-to-member or in an unevaluated context in C++11. 2349 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2350 return BuildPossibleImplicitMemberExpr(SS, 2351 /*TemplateKWLoc=*/SourceLocation(), 2352 R, /*TemplateArgs=*/nullptr, S); 2353 2354 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2355 } 2356 2357 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2358 /// detected that we're currently inside an ObjC method. Perform some 2359 /// additional lookup. 2360 /// 2361 /// Ideally, most of this would be done by lookup, but there's 2362 /// actually quite a lot of extra work involved. 2363 /// 2364 /// Returns a null sentinel to indicate trivial success. 2365 ExprResult 2366 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2367 IdentifierInfo *II, bool AllowBuiltinCreation) { 2368 SourceLocation Loc = Lookup.getNameLoc(); 2369 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2370 2371 // Check for error condition which is already reported. 2372 if (!CurMethod) 2373 return ExprError(); 2374 2375 // There are two cases to handle here. 1) scoped lookup could have failed, 2376 // in which case we should look for an ivar. 2) scoped lookup could have 2377 // found a decl, but that decl is outside the current instance method (i.e. 2378 // a global variable). In these two cases, we do a lookup for an ivar with 2379 // this name, if the lookup sucedes, we replace it our current decl. 2380 2381 // If we're in a class method, we don't normally want to look for 2382 // ivars. But if we don't find anything else, and there's an 2383 // ivar, that's an error. 2384 bool IsClassMethod = CurMethod->isClassMethod(); 2385 2386 bool LookForIvars; 2387 if (Lookup.empty()) 2388 LookForIvars = true; 2389 else if (IsClassMethod) 2390 LookForIvars = false; 2391 else 2392 LookForIvars = (Lookup.isSingleResult() && 2393 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2394 ObjCInterfaceDecl *IFace = nullptr; 2395 if (LookForIvars) { 2396 IFace = CurMethod->getClassInterface(); 2397 ObjCInterfaceDecl *ClassDeclared; 2398 ObjCIvarDecl *IV = nullptr; 2399 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2400 // Diagnose using an ivar in a class method. 2401 if (IsClassMethod) 2402 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2403 << IV->getDeclName()); 2404 2405 // If we're referencing an invalid decl, just return this as a silent 2406 // error node. The error diagnostic was already emitted on the decl. 2407 if (IV->isInvalidDecl()) 2408 return ExprError(); 2409 2410 // Check if referencing a field with __attribute__((deprecated)). 2411 if (DiagnoseUseOfDecl(IV, Loc)) 2412 return ExprError(); 2413 2414 // Diagnose the use of an ivar outside of the declaring class. 2415 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2416 !declaresSameEntity(ClassDeclared, IFace) && 2417 !getLangOpts().DebuggerSupport) 2418 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2419 2420 // FIXME: This should use a new expr for a direct reference, don't 2421 // turn this into Self->ivar, just return a BareIVarExpr or something. 2422 IdentifierInfo &II = Context.Idents.get("self"); 2423 UnqualifiedId SelfName; 2424 SelfName.setIdentifier(&II, SourceLocation()); 2425 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2426 CXXScopeSpec SelfScopeSpec; 2427 SourceLocation TemplateKWLoc; 2428 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2429 SelfName, false, false); 2430 if (SelfExpr.isInvalid()) 2431 return ExprError(); 2432 2433 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2434 if (SelfExpr.isInvalid()) 2435 return ExprError(); 2436 2437 MarkAnyDeclReferenced(Loc, IV, true); 2438 2439 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2440 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2441 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2442 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2443 2444 ObjCIvarRefExpr *Result = new (Context) 2445 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2446 IV->getLocation(), SelfExpr.get(), true, true); 2447 2448 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2449 if (!isUnevaluatedContext() && 2450 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2451 getCurFunction()->recordUseOfWeak(Result); 2452 } 2453 if (getLangOpts().ObjCAutoRefCount) { 2454 if (CurContext->isClosure()) 2455 Diag(Loc, diag::warn_implicitly_retains_self) 2456 << FixItHint::CreateInsertion(Loc, "self->"); 2457 } 2458 2459 return Result; 2460 } 2461 } else if (CurMethod->isInstanceMethod()) { 2462 // We should warn if a local variable hides an ivar. 2463 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2464 ObjCInterfaceDecl *ClassDeclared; 2465 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2466 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2467 declaresSameEntity(IFace, ClassDeclared)) 2468 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2469 } 2470 } 2471 } else if (Lookup.isSingleResult() && 2472 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2473 // If accessing a stand-alone ivar in a class method, this is an error. 2474 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2475 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2476 << IV->getDeclName()); 2477 } 2478 2479 if (Lookup.empty() && II && AllowBuiltinCreation) { 2480 // FIXME. Consolidate this with similar code in LookupName. 2481 if (unsigned BuiltinID = II->getBuiltinID()) { 2482 if (!(getLangOpts().CPlusPlus && 2483 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2484 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2485 S, Lookup.isForRedeclaration(), 2486 Lookup.getNameLoc()); 2487 if (D) Lookup.addDecl(D); 2488 } 2489 } 2490 } 2491 // Sentinel value saying that we didn't do anything special. 2492 return ExprResult((Expr *)nullptr); 2493 } 2494 2495 /// Cast a base object to a member's actual type. 2496 /// 2497 /// Logically this happens in three phases: 2498 /// 2499 /// * First we cast from the base type to the naming class. 2500 /// The naming class is the class into which we were looking 2501 /// when we found the member; it's the qualifier type if a 2502 /// qualifier was provided, and otherwise it's the base type. 2503 /// 2504 /// * Next we cast from the naming class to the declaring class. 2505 /// If the member we found was brought into a class's scope by 2506 /// a using declaration, this is that class; otherwise it's 2507 /// the class declaring the member. 2508 /// 2509 /// * Finally we cast from the declaring class to the "true" 2510 /// declaring class of the member. This conversion does not 2511 /// obey access control. 2512 ExprResult 2513 Sema::PerformObjectMemberConversion(Expr *From, 2514 NestedNameSpecifier *Qualifier, 2515 NamedDecl *FoundDecl, 2516 NamedDecl *Member) { 2517 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2518 if (!RD) 2519 return From; 2520 2521 QualType DestRecordType; 2522 QualType DestType; 2523 QualType FromRecordType; 2524 QualType FromType = From->getType(); 2525 bool PointerConversions = false; 2526 if (isa<FieldDecl>(Member)) { 2527 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2528 2529 if (FromType->getAs<PointerType>()) { 2530 DestType = Context.getPointerType(DestRecordType); 2531 FromRecordType = FromType->getPointeeType(); 2532 PointerConversions = true; 2533 } else { 2534 DestType = DestRecordType; 2535 FromRecordType = FromType; 2536 } 2537 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2538 if (Method->isStatic()) 2539 return From; 2540 2541 DestType = Method->getThisType(Context); 2542 DestRecordType = DestType->getPointeeType(); 2543 2544 if (FromType->getAs<PointerType>()) { 2545 FromRecordType = FromType->getPointeeType(); 2546 PointerConversions = true; 2547 } else { 2548 FromRecordType = FromType; 2549 DestType = DestRecordType; 2550 } 2551 } else { 2552 // No conversion necessary. 2553 return From; 2554 } 2555 2556 if (DestType->isDependentType() || FromType->isDependentType()) 2557 return From; 2558 2559 // If the unqualified types are the same, no conversion is necessary. 2560 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2561 return From; 2562 2563 SourceRange FromRange = From->getSourceRange(); 2564 SourceLocation FromLoc = FromRange.getBegin(); 2565 2566 ExprValueKind VK = From->getValueKind(); 2567 2568 // C++ [class.member.lookup]p8: 2569 // [...] Ambiguities can often be resolved by qualifying a name with its 2570 // class name. 2571 // 2572 // If the member was a qualified name and the qualified referred to a 2573 // specific base subobject type, we'll cast to that intermediate type 2574 // first and then to the object in which the member is declared. That allows 2575 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2576 // 2577 // class Base { public: int x; }; 2578 // class Derived1 : public Base { }; 2579 // class Derived2 : public Base { }; 2580 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2581 // 2582 // void VeryDerived::f() { 2583 // x = 17; // error: ambiguous base subobjects 2584 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2585 // } 2586 if (Qualifier && Qualifier->getAsType()) { 2587 QualType QType = QualType(Qualifier->getAsType(), 0); 2588 assert(QType->isRecordType() && "lookup done with non-record type"); 2589 2590 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2591 2592 // In C++98, the qualifier type doesn't actually have to be a base 2593 // type of the object type, in which case we just ignore it. 2594 // Otherwise build the appropriate casts. 2595 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2596 CXXCastPath BasePath; 2597 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2598 FromLoc, FromRange, &BasePath)) 2599 return ExprError(); 2600 2601 if (PointerConversions) 2602 QType = Context.getPointerType(QType); 2603 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2604 VK, &BasePath).get(); 2605 2606 FromType = QType; 2607 FromRecordType = QRecordType; 2608 2609 // If the qualifier type was the same as the destination type, 2610 // we're done. 2611 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2612 return From; 2613 } 2614 } 2615 2616 bool IgnoreAccess = false; 2617 2618 // If we actually found the member through a using declaration, cast 2619 // down to the using declaration's type. 2620 // 2621 // Pointer equality is fine here because only one declaration of a 2622 // class ever has member declarations. 2623 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2624 assert(isa<UsingShadowDecl>(FoundDecl)); 2625 QualType URecordType = Context.getTypeDeclType( 2626 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2627 2628 // We only need to do this if the naming-class to declaring-class 2629 // conversion is non-trivial. 2630 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2631 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2632 CXXCastPath BasePath; 2633 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2634 FromLoc, FromRange, &BasePath)) 2635 return ExprError(); 2636 2637 QualType UType = URecordType; 2638 if (PointerConversions) 2639 UType = Context.getPointerType(UType); 2640 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2641 VK, &BasePath).get(); 2642 FromType = UType; 2643 FromRecordType = URecordType; 2644 } 2645 2646 // We don't do access control for the conversion from the 2647 // declaring class to the true declaring class. 2648 IgnoreAccess = true; 2649 } 2650 2651 CXXCastPath BasePath; 2652 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2653 FromLoc, FromRange, &BasePath, 2654 IgnoreAccess)) 2655 return ExprError(); 2656 2657 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2658 VK, &BasePath); 2659 } 2660 2661 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2662 const LookupResult &R, 2663 bool HasTrailingLParen) { 2664 // Only when used directly as the postfix-expression of a call. 2665 if (!HasTrailingLParen) 2666 return false; 2667 2668 // Never if a scope specifier was provided. 2669 if (SS.isSet()) 2670 return false; 2671 2672 // Only in C++ or ObjC++. 2673 if (!getLangOpts().CPlusPlus) 2674 return false; 2675 2676 // Turn off ADL when we find certain kinds of declarations during 2677 // normal lookup: 2678 for (NamedDecl *D : R) { 2679 // C++0x [basic.lookup.argdep]p3: 2680 // -- a declaration of a class member 2681 // Since using decls preserve this property, we check this on the 2682 // original decl. 2683 if (D->isCXXClassMember()) 2684 return false; 2685 2686 // C++0x [basic.lookup.argdep]p3: 2687 // -- a block-scope function declaration that is not a 2688 // using-declaration 2689 // NOTE: we also trigger this for function templates (in fact, we 2690 // don't check the decl type at all, since all other decl types 2691 // turn off ADL anyway). 2692 if (isa<UsingShadowDecl>(D)) 2693 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2694 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2695 return false; 2696 2697 // C++0x [basic.lookup.argdep]p3: 2698 // -- a declaration that is neither a function or a function 2699 // template 2700 // And also for builtin functions. 2701 if (isa<FunctionDecl>(D)) { 2702 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2703 2704 // But also builtin functions. 2705 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2706 return false; 2707 } else if (!isa<FunctionTemplateDecl>(D)) 2708 return false; 2709 } 2710 2711 return true; 2712 } 2713 2714 2715 /// Diagnoses obvious problems with the use of the given declaration 2716 /// as an expression. This is only actually called for lookups that 2717 /// were not overloaded, and it doesn't promise that the declaration 2718 /// will in fact be used. 2719 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2720 if (D->isInvalidDecl()) 2721 return true; 2722 2723 if (isa<TypedefNameDecl>(D)) { 2724 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2725 return true; 2726 } 2727 2728 if (isa<ObjCInterfaceDecl>(D)) { 2729 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2730 return true; 2731 } 2732 2733 if (isa<NamespaceDecl>(D)) { 2734 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2735 return true; 2736 } 2737 2738 return false; 2739 } 2740 2741 // Certain multiversion types should be treated as overloaded even when there is 2742 // only one result. 2743 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2744 assert(R.isSingleResult() && "Expected only a single result"); 2745 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2746 return FD && 2747 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2748 } 2749 2750 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2751 LookupResult &R, bool NeedsADL, 2752 bool AcceptInvalidDecl) { 2753 // If this is a single, fully-resolved result and we don't need ADL, 2754 // just build an ordinary singleton decl ref. 2755 if (!NeedsADL && R.isSingleResult() && 2756 !R.getAsSingle<FunctionTemplateDecl>() && 2757 !ShouldLookupResultBeMultiVersionOverload(R)) 2758 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2759 R.getRepresentativeDecl(), nullptr, 2760 AcceptInvalidDecl); 2761 2762 // We only need to check the declaration if there's exactly one 2763 // result, because in the overloaded case the results can only be 2764 // functions and function templates. 2765 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2766 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2767 return ExprError(); 2768 2769 // Otherwise, just build an unresolved lookup expression. Suppress 2770 // any lookup-related diagnostics; we'll hash these out later, when 2771 // we've picked a target. 2772 R.suppressDiagnostics(); 2773 2774 UnresolvedLookupExpr *ULE 2775 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2776 SS.getWithLocInContext(Context), 2777 R.getLookupNameInfo(), 2778 NeedsADL, R.isOverloadedResult(), 2779 R.begin(), R.end()); 2780 2781 return ULE; 2782 } 2783 2784 static void 2785 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2786 ValueDecl *var, DeclContext *DC); 2787 2788 /// Complete semantic analysis for a reference to the given declaration. 2789 ExprResult Sema::BuildDeclarationNameExpr( 2790 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2791 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2792 bool AcceptInvalidDecl) { 2793 assert(D && "Cannot refer to a NULL declaration"); 2794 assert(!isa<FunctionTemplateDecl>(D) && 2795 "Cannot refer unambiguously to a function template"); 2796 2797 SourceLocation Loc = NameInfo.getLoc(); 2798 if (CheckDeclInExpr(*this, Loc, D)) 2799 return ExprError(); 2800 2801 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2802 // Specifically diagnose references to class templates that are missing 2803 // a template argument list. 2804 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2805 return ExprError(); 2806 } 2807 2808 // Make sure that we're referring to a value. 2809 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2810 if (!VD) { 2811 Diag(Loc, diag::err_ref_non_value) 2812 << D << SS.getRange(); 2813 Diag(D->getLocation(), diag::note_declared_at); 2814 return ExprError(); 2815 } 2816 2817 // Check whether this declaration can be used. Note that we suppress 2818 // this check when we're going to perform argument-dependent lookup 2819 // on this function name, because this might not be the function 2820 // that overload resolution actually selects. 2821 if (DiagnoseUseOfDecl(VD, Loc)) 2822 return ExprError(); 2823 2824 // Only create DeclRefExpr's for valid Decl's. 2825 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2826 return ExprError(); 2827 2828 // Handle members of anonymous structs and unions. If we got here, 2829 // and the reference is to a class member indirect field, then this 2830 // must be the subject of a pointer-to-member expression. 2831 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2832 if (!indirectField->isCXXClassMember()) 2833 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2834 indirectField); 2835 2836 { 2837 QualType type = VD->getType(); 2838 if (type.isNull()) 2839 return ExprError(); 2840 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2841 // C++ [except.spec]p17: 2842 // An exception-specification is considered to be needed when: 2843 // - in an expression, the function is the unique lookup result or 2844 // the selected member of a set of overloaded functions. 2845 ResolveExceptionSpec(Loc, FPT); 2846 type = VD->getType(); 2847 } 2848 ExprValueKind valueKind = VK_RValue; 2849 2850 switch (D->getKind()) { 2851 // Ignore all the non-ValueDecl kinds. 2852 #define ABSTRACT_DECL(kind) 2853 #define VALUE(type, base) 2854 #define DECL(type, base) \ 2855 case Decl::type: 2856 #include "clang/AST/DeclNodes.inc" 2857 llvm_unreachable("invalid value decl kind"); 2858 2859 // These shouldn't make it here. 2860 case Decl::ObjCAtDefsField: 2861 case Decl::ObjCIvar: 2862 llvm_unreachable("forming non-member reference to ivar?"); 2863 2864 // Enum constants are always r-values and never references. 2865 // Unresolved using declarations are dependent. 2866 case Decl::EnumConstant: 2867 case Decl::UnresolvedUsingValue: 2868 case Decl::OMPDeclareReduction: 2869 valueKind = VK_RValue; 2870 break; 2871 2872 // Fields and indirect fields that got here must be for 2873 // pointer-to-member expressions; we just call them l-values for 2874 // internal consistency, because this subexpression doesn't really 2875 // exist in the high-level semantics. 2876 case Decl::Field: 2877 case Decl::IndirectField: 2878 assert(getLangOpts().CPlusPlus && 2879 "building reference to field in C?"); 2880 2881 // These can't have reference type in well-formed programs, but 2882 // for internal consistency we do this anyway. 2883 type = type.getNonReferenceType(); 2884 valueKind = VK_LValue; 2885 break; 2886 2887 // Non-type template parameters are either l-values or r-values 2888 // depending on the type. 2889 case Decl::NonTypeTemplateParm: { 2890 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2891 type = reftype->getPointeeType(); 2892 valueKind = VK_LValue; // even if the parameter is an r-value reference 2893 break; 2894 } 2895 2896 // For non-references, we need to strip qualifiers just in case 2897 // the template parameter was declared as 'const int' or whatever. 2898 valueKind = VK_RValue; 2899 type = type.getUnqualifiedType(); 2900 break; 2901 } 2902 2903 case Decl::Var: 2904 case Decl::VarTemplateSpecialization: 2905 case Decl::VarTemplatePartialSpecialization: 2906 case Decl::Decomposition: 2907 case Decl::OMPCapturedExpr: 2908 // In C, "extern void blah;" is valid and is an r-value. 2909 if (!getLangOpts().CPlusPlus && 2910 !type.hasQualifiers() && 2911 type->isVoidType()) { 2912 valueKind = VK_RValue; 2913 break; 2914 } 2915 LLVM_FALLTHROUGH; 2916 2917 case Decl::ImplicitParam: 2918 case Decl::ParmVar: { 2919 // These are always l-values. 2920 valueKind = VK_LValue; 2921 type = type.getNonReferenceType(); 2922 2923 // FIXME: Does the addition of const really only apply in 2924 // potentially-evaluated contexts? Since the variable isn't actually 2925 // captured in an unevaluated context, it seems that the answer is no. 2926 if (!isUnevaluatedContext()) { 2927 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2928 if (!CapturedType.isNull()) 2929 type = CapturedType; 2930 } 2931 2932 break; 2933 } 2934 2935 case Decl::Binding: { 2936 // These are always lvalues. 2937 valueKind = VK_LValue; 2938 type = type.getNonReferenceType(); 2939 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2940 // decides how that's supposed to work. 2941 auto *BD = cast<BindingDecl>(VD); 2942 if (BD->getDeclContext()->isFunctionOrMethod() && 2943 BD->getDeclContext() != CurContext) 2944 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2945 break; 2946 } 2947 2948 case Decl::Function: { 2949 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2950 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2951 type = Context.BuiltinFnTy; 2952 valueKind = VK_RValue; 2953 break; 2954 } 2955 } 2956 2957 const FunctionType *fty = type->castAs<FunctionType>(); 2958 2959 // If we're referring to a function with an __unknown_anytype 2960 // result type, make the entire expression __unknown_anytype. 2961 if (fty->getReturnType() == Context.UnknownAnyTy) { 2962 type = Context.UnknownAnyTy; 2963 valueKind = VK_RValue; 2964 break; 2965 } 2966 2967 // Functions are l-values in C++. 2968 if (getLangOpts().CPlusPlus) { 2969 valueKind = VK_LValue; 2970 break; 2971 } 2972 2973 // C99 DR 316 says that, if a function type comes from a 2974 // function definition (without a prototype), that type is only 2975 // used for checking compatibility. Therefore, when referencing 2976 // the function, we pretend that we don't have the full function 2977 // type. 2978 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2979 isa<FunctionProtoType>(fty)) 2980 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2981 fty->getExtInfo()); 2982 2983 // Functions are r-values in C. 2984 valueKind = VK_RValue; 2985 break; 2986 } 2987 2988 case Decl::CXXDeductionGuide: 2989 llvm_unreachable("building reference to deduction guide"); 2990 2991 case Decl::MSProperty: 2992 valueKind = VK_LValue; 2993 break; 2994 2995 case Decl::CXXMethod: 2996 // If we're referring to a method with an __unknown_anytype 2997 // result type, make the entire expression __unknown_anytype. 2998 // This should only be possible with a type written directly. 2999 if (const FunctionProtoType *proto 3000 = dyn_cast<FunctionProtoType>(VD->getType())) 3001 if (proto->getReturnType() == Context.UnknownAnyTy) { 3002 type = Context.UnknownAnyTy; 3003 valueKind = VK_RValue; 3004 break; 3005 } 3006 3007 // C++ methods are l-values if static, r-values if non-static. 3008 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3009 valueKind = VK_LValue; 3010 break; 3011 } 3012 LLVM_FALLTHROUGH; 3013 3014 case Decl::CXXConversion: 3015 case Decl::CXXDestructor: 3016 case Decl::CXXConstructor: 3017 valueKind = VK_RValue; 3018 break; 3019 } 3020 3021 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3022 TemplateArgs); 3023 } 3024 } 3025 3026 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3027 SmallString<32> &Target) { 3028 Target.resize(CharByteWidth * (Source.size() + 1)); 3029 char *ResultPtr = &Target[0]; 3030 const llvm::UTF8 *ErrorPtr; 3031 bool success = 3032 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3033 (void)success; 3034 assert(success); 3035 Target.resize(ResultPtr - &Target[0]); 3036 } 3037 3038 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3039 PredefinedExpr::IdentType IT) { 3040 // Pick the current block, lambda, captured statement or function. 3041 Decl *currentDecl = nullptr; 3042 if (const BlockScopeInfo *BSI = getCurBlock()) 3043 currentDecl = BSI->TheDecl; 3044 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3045 currentDecl = LSI->CallOperator; 3046 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3047 currentDecl = CSI->TheCapturedDecl; 3048 else 3049 currentDecl = getCurFunctionOrMethodDecl(); 3050 3051 if (!currentDecl) { 3052 Diag(Loc, diag::ext_predef_outside_function); 3053 currentDecl = Context.getTranslationUnitDecl(); 3054 } 3055 3056 QualType ResTy; 3057 StringLiteral *SL = nullptr; 3058 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3059 ResTy = Context.DependentTy; 3060 else { 3061 // Pre-defined identifiers are of type char[x], where x is the length of 3062 // the string. 3063 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3064 unsigned Length = Str.length(); 3065 3066 llvm::APInt LengthI(32, Length + 1); 3067 if (IT == PredefinedExpr::LFunction || IT == PredefinedExpr::LFuncSig) { 3068 ResTy = 3069 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3070 SmallString<32> RawChars; 3071 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3072 Str, RawChars); 3073 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3074 /*IndexTypeQuals*/ 0); 3075 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3076 /*Pascal*/ false, ResTy, Loc); 3077 } else { 3078 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3079 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3080 /*IndexTypeQuals*/ 0); 3081 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3082 /*Pascal*/ false, ResTy, Loc); 3083 } 3084 } 3085 3086 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3087 } 3088 3089 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3090 PredefinedExpr::IdentType IT; 3091 3092 switch (Kind) { 3093 default: llvm_unreachable("Unknown simple primary expr!"); 3094 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3095 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3096 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3097 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3098 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; // [MS] 3099 case tok::kw_L__FUNCSIG__: IT = PredefinedExpr::LFuncSig; break; // [MS] 3100 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3101 } 3102 3103 return BuildPredefinedExpr(Loc, IT); 3104 } 3105 3106 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3107 SmallString<16> CharBuffer; 3108 bool Invalid = false; 3109 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3110 if (Invalid) 3111 return ExprError(); 3112 3113 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3114 PP, Tok.getKind()); 3115 if (Literal.hadError()) 3116 return ExprError(); 3117 3118 QualType Ty; 3119 if (Literal.isWide()) 3120 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3121 else if (Literal.isUTF8() && getLangOpts().Char8) 3122 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3123 else if (Literal.isUTF16()) 3124 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3125 else if (Literal.isUTF32()) 3126 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3127 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3128 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3129 else 3130 Ty = Context.CharTy; // 'x' -> char in C++ 3131 3132 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3133 if (Literal.isWide()) 3134 Kind = CharacterLiteral::Wide; 3135 else if (Literal.isUTF16()) 3136 Kind = CharacterLiteral::UTF16; 3137 else if (Literal.isUTF32()) 3138 Kind = CharacterLiteral::UTF32; 3139 else if (Literal.isUTF8()) 3140 Kind = CharacterLiteral::UTF8; 3141 3142 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3143 Tok.getLocation()); 3144 3145 if (Literal.getUDSuffix().empty()) 3146 return Lit; 3147 3148 // We're building a user-defined literal. 3149 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3150 SourceLocation UDSuffixLoc = 3151 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3152 3153 // Make sure we're allowed user-defined literals here. 3154 if (!UDLScope) 3155 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3156 3157 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3158 // operator "" X (ch) 3159 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3160 Lit, Tok.getLocation()); 3161 } 3162 3163 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3164 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3165 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3166 Context.IntTy, Loc); 3167 } 3168 3169 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3170 QualType Ty, SourceLocation Loc) { 3171 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3172 3173 using llvm::APFloat; 3174 APFloat Val(Format); 3175 3176 APFloat::opStatus result = Literal.GetFloatValue(Val); 3177 3178 // Overflow is always an error, but underflow is only an error if 3179 // we underflowed to zero (APFloat reports denormals as underflow). 3180 if ((result & APFloat::opOverflow) || 3181 ((result & APFloat::opUnderflow) && Val.isZero())) { 3182 unsigned diagnostic; 3183 SmallString<20> buffer; 3184 if (result & APFloat::opOverflow) { 3185 diagnostic = diag::warn_float_overflow; 3186 APFloat::getLargest(Format).toString(buffer); 3187 } else { 3188 diagnostic = diag::warn_float_underflow; 3189 APFloat::getSmallest(Format).toString(buffer); 3190 } 3191 3192 S.Diag(Loc, diagnostic) 3193 << Ty 3194 << StringRef(buffer.data(), buffer.size()); 3195 } 3196 3197 bool isExact = (result == APFloat::opOK); 3198 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3199 } 3200 3201 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3202 assert(E && "Invalid expression"); 3203 3204 if (E->isValueDependent()) 3205 return false; 3206 3207 QualType QT = E->getType(); 3208 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3209 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3210 return true; 3211 } 3212 3213 llvm::APSInt ValueAPS; 3214 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3215 3216 if (R.isInvalid()) 3217 return true; 3218 3219 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3220 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3221 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3222 << ValueAPS.toString(10) << ValueIsPositive; 3223 return true; 3224 } 3225 3226 return false; 3227 } 3228 3229 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3230 // Fast path for a single digit (which is quite common). A single digit 3231 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3232 if (Tok.getLength() == 1) { 3233 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3234 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3235 } 3236 3237 SmallString<128> SpellingBuffer; 3238 // NumericLiteralParser wants to overread by one character. Add padding to 3239 // the buffer in case the token is copied to the buffer. If getSpelling() 3240 // returns a StringRef to the memory buffer, it should have a null char at 3241 // the EOF, so it is also safe. 3242 SpellingBuffer.resize(Tok.getLength() + 1); 3243 3244 // Get the spelling of the token, which eliminates trigraphs, etc. 3245 bool Invalid = false; 3246 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3247 if (Invalid) 3248 return ExprError(); 3249 3250 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3251 if (Literal.hadError) 3252 return ExprError(); 3253 3254 if (Literal.hasUDSuffix()) { 3255 // We're building a user-defined literal. 3256 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3257 SourceLocation UDSuffixLoc = 3258 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3259 3260 // Make sure we're allowed user-defined literals here. 3261 if (!UDLScope) 3262 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3263 3264 QualType CookedTy; 3265 if (Literal.isFloatingLiteral()) { 3266 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3267 // long double, the literal is treated as a call of the form 3268 // operator "" X (f L) 3269 CookedTy = Context.LongDoubleTy; 3270 } else { 3271 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3272 // unsigned long long, the literal is treated as a call of the form 3273 // operator "" X (n ULL) 3274 CookedTy = Context.UnsignedLongLongTy; 3275 } 3276 3277 DeclarationName OpName = 3278 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3279 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3280 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3281 3282 SourceLocation TokLoc = Tok.getLocation(); 3283 3284 // Perform literal operator lookup to determine if we're building a raw 3285 // literal or a cooked one. 3286 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3287 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3288 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3289 /*AllowStringTemplate*/ false, 3290 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3291 case LOLR_ErrorNoDiagnostic: 3292 // Lookup failure for imaginary constants isn't fatal, there's still the 3293 // GNU extension producing _Complex types. 3294 break; 3295 case LOLR_Error: 3296 return ExprError(); 3297 case LOLR_Cooked: { 3298 Expr *Lit; 3299 if (Literal.isFloatingLiteral()) { 3300 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3301 } else { 3302 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3303 if (Literal.GetIntegerValue(ResultVal)) 3304 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3305 << /* Unsigned */ 1; 3306 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3307 Tok.getLocation()); 3308 } 3309 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3310 } 3311 3312 case LOLR_Raw: { 3313 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3314 // literal is treated as a call of the form 3315 // operator "" X ("n") 3316 unsigned Length = Literal.getUDSuffixOffset(); 3317 QualType StrTy = Context.getConstantArrayType( 3318 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3319 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3320 Expr *Lit = StringLiteral::Create( 3321 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3322 /*Pascal*/false, StrTy, &TokLoc, 1); 3323 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3324 } 3325 3326 case LOLR_Template: { 3327 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3328 // template), L is treated as a call fo the form 3329 // operator "" X <'c1', 'c2', ... 'ck'>() 3330 // where n is the source character sequence c1 c2 ... ck. 3331 TemplateArgumentListInfo ExplicitArgs; 3332 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3333 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3334 llvm::APSInt Value(CharBits, CharIsUnsigned); 3335 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3336 Value = TokSpelling[I]; 3337 TemplateArgument Arg(Context, Value, Context.CharTy); 3338 TemplateArgumentLocInfo ArgInfo; 3339 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3340 } 3341 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3342 &ExplicitArgs); 3343 } 3344 case LOLR_StringTemplate: 3345 llvm_unreachable("unexpected literal operator lookup result"); 3346 } 3347 } 3348 3349 Expr *Res; 3350 3351 if (Literal.isFixedPointLiteral()) { 3352 QualType Ty; 3353 3354 if (Literal.isAccum) { 3355 if (Literal.isHalf) { 3356 Ty = Context.ShortAccumTy; 3357 } else if (Literal.isLong) { 3358 Ty = Context.LongAccumTy; 3359 } else { 3360 Ty = Context.AccumTy; 3361 } 3362 } else if (Literal.isFract) { 3363 if (Literal.isHalf) { 3364 Ty = Context.ShortFractTy; 3365 } else if (Literal.isLong) { 3366 Ty = Context.LongFractTy; 3367 } else { 3368 Ty = Context.FractTy; 3369 } 3370 } 3371 3372 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3373 3374 bool isSigned = !Literal.isUnsigned; 3375 unsigned scale = Context.getFixedPointScale(Ty); 3376 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3377 3378 llvm::APInt Val(bit_width, 0, isSigned); 3379 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3380 bool ValIsZero = Val.isNullValue() && !Overflowed; 3381 3382 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3383 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3384 // Clause 6.4.4 - The value of a constant shall be in the range of 3385 // representable values for its type, with exception for constants of a 3386 // fract type with a value of exactly 1; such a constant shall denote 3387 // the maximal value for the type. 3388 --Val; 3389 else if (Val.ugt(MaxVal) || Overflowed) 3390 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3391 3392 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3393 Tok.getLocation(), scale); 3394 } else if (Literal.isFloatingLiteral()) { 3395 QualType Ty; 3396 if (Literal.isHalf){ 3397 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3398 Ty = Context.HalfTy; 3399 else { 3400 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3401 return ExprError(); 3402 } 3403 } else if (Literal.isFloat) 3404 Ty = Context.FloatTy; 3405 else if (Literal.isLong) 3406 Ty = Context.LongDoubleTy; 3407 else if (Literal.isFloat16) 3408 Ty = Context.Float16Ty; 3409 else if (Literal.isFloat128) 3410 Ty = Context.Float128Ty; 3411 else 3412 Ty = Context.DoubleTy; 3413 3414 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3415 3416 if (Ty == Context.DoubleTy) { 3417 if (getLangOpts().SinglePrecisionConstants) { 3418 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3419 if (BTy->getKind() != BuiltinType::Float) { 3420 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3421 } 3422 } else if (getLangOpts().OpenCL && 3423 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3424 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3425 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3426 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3427 } 3428 } 3429 } else if (!Literal.isIntegerLiteral()) { 3430 return ExprError(); 3431 } else { 3432 QualType Ty; 3433 3434 // 'long long' is a C99 or C++11 feature. 3435 if (!getLangOpts().C99 && Literal.isLongLong) { 3436 if (getLangOpts().CPlusPlus) 3437 Diag(Tok.getLocation(), 3438 getLangOpts().CPlusPlus11 ? 3439 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3440 else 3441 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3442 } 3443 3444 // Get the value in the widest-possible width. 3445 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3446 llvm::APInt ResultVal(MaxWidth, 0); 3447 3448 if (Literal.GetIntegerValue(ResultVal)) { 3449 // If this value didn't fit into uintmax_t, error and force to ull. 3450 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3451 << /* Unsigned */ 1; 3452 Ty = Context.UnsignedLongLongTy; 3453 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3454 "long long is not intmax_t?"); 3455 } else { 3456 // If this value fits into a ULL, try to figure out what else it fits into 3457 // according to the rules of C99 6.4.4.1p5. 3458 3459 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3460 // be an unsigned int. 3461 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3462 3463 // Check from smallest to largest, picking the smallest type we can. 3464 unsigned Width = 0; 3465 3466 // Microsoft specific integer suffixes are explicitly sized. 3467 if (Literal.MicrosoftInteger) { 3468 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3469 Width = 8; 3470 Ty = Context.CharTy; 3471 } else { 3472 Width = Literal.MicrosoftInteger; 3473 Ty = Context.getIntTypeForBitwidth(Width, 3474 /*Signed=*/!Literal.isUnsigned); 3475 } 3476 } 3477 3478 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3479 // Are int/unsigned possibilities? 3480 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3481 3482 // Does it fit in a unsigned int? 3483 if (ResultVal.isIntN(IntSize)) { 3484 // Does it fit in a signed int? 3485 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3486 Ty = Context.IntTy; 3487 else if (AllowUnsigned) 3488 Ty = Context.UnsignedIntTy; 3489 Width = IntSize; 3490 } 3491 } 3492 3493 // Are long/unsigned long possibilities? 3494 if (Ty.isNull() && !Literal.isLongLong) { 3495 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3496 3497 // Does it fit in a unsigned long? 3498 if (ResultVal.isIntN(LongSize)) { 3499 // Does it fit in a signed long? 3500 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3501 Ty = Context.LongTy; 3502 else if (AllowUnsigned) 3503 Ty = Context.UnsignedLongTy; 3504 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3505 // is compatible. 3506 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3507 const unsigned LongLongSize = 3508 Context.getTargetInfo().getLongLongWidth(); 3509 Diag(Tok.getLocation(), 3510 getLangOpts().CPlusPlus 3511 ? Literal.isLong 3512 ? diag::warn_old_implicitly_unsigned_long_cxx 3513 : /*C++98 UB*/ diag:: 3514 ext_old_implicitly_unsigned_long_cxx 3515 : diag::warn_old_implicitly_unsigned_long) 3516 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3517 : /*will be ill-formed*/ 1); 3518 Ty = Context.UnsignedLongTy; 3519 } 3520 Width = LongSize; 3521 } 3522 } 3523 3524 // Check long long if needed. 3525 if (Ty.isNull()) { 3526 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3527 3528 // Does it fit in a unsigned long long? 3529 if (ResultVal.isIntN(LongLongSize)) { 3530 // Does it fit in a signed long long? 3531 // To be compatible with MSVC, hex integer literals ending with the 3532 // LL or i64 suffix are always signed in Microsoft mode. 3533 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3534 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3535 Ty = Context.LongLongTy; 3536 else if (AllowUnsigned) 3537 Ty = Context.UnsignedLongLongTy; 3538 Width = LongLongSize; 3539 } 3540 } 3541 3542 // If we still couldn't decide a type, we probably have something that 3543 // does not fit in a signed long long, but has no U suffix. 3544 if (Ty.isNull()) { 3545 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3546 Ty = Context.UnsignedLongLongTy; 3547 Width = Context.getTargetInfo().getLongLongWidth(); 3548 } 3549 3550 if (ResultVal.getBitWidth() != Width) 3551 ResultVal = ResultVal.trunc(Width); 3552 } 3553 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3554 } 3555 3556 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3557 if (Literal.isImaginary) { 3558 Res = new (Context) ImaginaryLiteral(Res, 3559 Context.getComplexType(Res->getType())); 3560 3561 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3562 } 3563 return Res; 3564 } 3565 3566 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3567 assert(E && "ActOnParenExpr() missing expr"); 3568 return new (Context) ParenExpr(L, R, E); 3569 } 3570 3571 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3572 SourceLocation Loc, 3573 SourceRange ArgRange) { 3574 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3575 // scalar or vector data type argument..." 3576 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3577 // type (C99 6.2.5p18) or void. 3578 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3579 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3580 << T << ArgRange; 3581 return true; 3582 } 3583 3584 assert((T->isVoidType() || !T->isIncompleteType()) && 3585 "Scalar types should always be complete"); 3586 return false; 3587 } 3588 3589 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3590 SourceLocation Loc, 3591 SourceRange ArgRange, 3592 UnaryExprOrTypeTrait TraitKind) { 3593 // Invalid types must be hard errors for SFINAE in C++. 3594 if (S.LangOpts.CPlusPlus) 3595 return true; 3596 3597 // C99 6.5.3.4p1: 3598 if (T->isFunctionType() && 3599 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3600 TraitKind == UETT_PreferredAlignOf)) { 3601 // sizeof(function)/alignof(function) is allowed as an extension. 3602 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3603 << TraitKind << ArgRange; 3604 return false; 3605 } 3606 3607 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3608 // this is an error (OpenCL v1.1 s6.3.k) 3609 if (T->isVoidType()) { 3610 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3611 : diag::ext_sizeof_alignof_void_type; 3612 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3613 return false; 3614 } 3615 3616 return true; 3617 } 3618 3619 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3620 SourceLocation Loc, 3621 SourceRange ArgRange, 3622 UnaryExprOrTypeTrait TraitKind) { 3623 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3624 // runtime doesn't allow it. 3625 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3626 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3627 << T << (TraitKind == UETT_SizeOf) 3628 << ArgRange; 3629 return true; 3630 } 3631 3632 return false; 3633 } 3634 3635 /// Check whether E is a pointer from a decayed array type (the decayed 3636 /// pointer type is equal to T) and emit a warning if it is. 3637 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3638 Expr *E) { 3639 // Don't warn if the operation changed the type. 3640 if (T != E->getType()) 3641 return; 3642 3643 // Now look for array decays. 3644 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3645 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3646 return; 3647 3648 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3649 << ICE->getType() 3650 << ICE->getSubExpr()->getType(); 3651 } 3652 3653 /// Check the constraints on expression operands to unary type expression 3654 /// and type traits. 3655 /// 3656 /// Completes any types necessary and validates the constraints on the operand 3657 /// expression. The logic mostly mirrors the type-based overload, but may modify 3658 /// the expression as it completes the type for that expression through template 3659 /// instantiation, etc. 3660 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3661 UnaryExprOrTypeTrait ExprKind) { 3662 QualType ExprTy = E->getType(); 3663 assert(!ExprTy->isReferenceType()); 3664 3665 if (ExprKind == UETT_VecStep) 3666 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3667 E->getSourceRange()); 3668 3669 // Whitelist some types as extensions 3670 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3671 E->getSourceRange(), ExprKind)) 3672 return false; 3673 3674 // 'alignof' applied to an expression only requires the base element type of 3675 // the expression to be complete. 'sizeof' requires the expression's type to 3676 // be complete (and will attempt to complete it if it's an array of unknown 3677 // bound). 3678 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3679 if (RequireCompleteType(E->getExprLoc(), 3680 Context.getBaseElementType(E->getType()), 3681 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3682 E->getSourceRange())) 3683 return true; 3684 } else { 3685 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3686 ExprKind, E->getSourceRange())) 3687 return true; 3688 } 3689 3690 // Completing the expression's type may have changed it. 3691 ExprTy = E->getType(); 3692 assert(!ExprTy->isReferenceType()); 3693 3694 if (ExprTy->isFunctionType()) { 3695 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3696 << ExprKind << E->getSourceRange(); 3697 return true; 3698 } 3699 3700 // The operand for sizeof and alignof is in an unevaluated expression context, 3701 // so side effects could result in unintended consequences. 3702 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3703 ExprKind == UETT_PreferredAlignOf) && 3704 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3705 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3706 3707 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3708 E->getSourceRange(), ExprKind)) 3709 return true; 3710 3711 if (ExprKind == UETT_SizeOf) { 3712 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3713 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3714 QualType OType = PVD->getOriginalType(); 3715 QualType Type = PVD->getType(); 3716 if (Type->isPointerType() && OType->isArrayType()) { 3717 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3718 << Type << OType; 3719 Diag(PVD->getLocation(), diag::note_declared_at); 3720 } 3721 } 3722 } 3723 3724 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3725 // decays into a pointer and returns an unintended result. This is most 3726 // likely a typo for "sizeof(array) op x". 3727 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3728 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3729 BO->getLHS()); 3730 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3731 BO->getRHS()); 3732 } 3733 } 3734 3735 return false; 3736 } 3737 3738 /// Check the constraints on operands to unary expression and type 3739 /// traits. 3740 /// 3741 /// This will complete any types necessary, and validate the various constraints 3742 /// on those operands. 3743 /// 3744 /// The UsualUnaryConversions() function is *not* called by this routine. 3745 /// C99 6.3.2.1p[2-4] all state: 3746 /// Except when it is the operand of the sizeof operator ... 3747 /// 3748 /// C++ [expr.sizeof]p4 3749 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3750 /// standard conversions are not applied to the operand of sizeof. 3751 /// 3752 /// This policy is followed for all of the unary trait expressions. 3753 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3754 SourceLocation OpLoc, 3755 SourceRange ExprRange, 3756 UnaryExprOrTypeTrait ExprKind) { 3757 if (ExprType->isDependentType()) 3758 return false; 3759 3760 // C++ [expr.sizeof]p2: 3761 // When applied to a reference or a reference type, the result 3762 // is the size of the referenced type. 3763 // C++11 [expr.alignof]p3: 3764 // When alignof is applied to a reference type, the result 3765 // shall be the alignment of the referenced type. 3766 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3767 ExprType = Ref->getPointeeType(); 3768 3769 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3770 // When alignof or _Alignof is applied to an array type, the result 3771 // is the alignment of the element type. 3772 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3773 ExprKind == UETT_OpenMPRequiredSimdAlign) 3774 ExprType = Context.getBaseElementType(ExprType); 3775 3776 if (ExprKind == UETT_VecStep) 3777 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3778 3779 // Whitelist some types as extensions 3780 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3781 ExprKind)) 3782 return false; 3783 3784 if (RequireCompleteType(OpLoc, ExprType, 3785 diag::err_sizeof_alignof_incomplete_type, 3786 ExprKind, ExprRange)) 3787 return true; 3788 3789 if (ExprType->isFunctionType()) { 3790 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3791 << ExprKind << ExprRange; 3792 return true; 3793 } 3794 3795 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3796 ExprKind)) 3797 return true; 3798 3799 return false; 3800 } 3801 3802 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3803 E = E->IgnoreParens(); 3804 3805 // Cannot know anything else if the expression is dependent. 3806 if (E->isTypeDependent()) 3807 return false; 3808 3809 if (E->getObjectKind() == OK_BitField) { 3810 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3811 << 1 << E->getSourceRange(); 3812 return true; 3813 } 3814 3815 ValueDecl *D = nullptr; 3816 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3817 D = DRE->getDecl(); 3818 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3819 D = ME->getMemberDecl(); 3820 } 3821 3822 // If it's a field, require the containing struct to have a 3823 // complete definition so that we can compute the layout. 3824 // 3825 // This can happen in C++11 onwards, either by naming the member 3826 // in a way that is not transformed into a member access expression 3827 // (in an unevaluated operand, for instance), or by naming the member 3828 // in a trailing-return-type. 3829 // 3830 // For the record, since __alignof__ on expressions is a GCC 3831 // extension, GCC seems to permit this but always gives the 3832 // nonsensical answer 0. 3833 // 3834 // We don't really need the layout here --- we could instead just 3835 // directly check for all the appropriate alignment-lowing 3836 // attributes --- but that would require duplicating a lot of 3837 // logic that just isn't worth duplicating for such a marginal 3838 // use-case. 3839 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3840 // Fast path this check, since we at least know the record has a 3841 // definition if we can find a member of it. 3842 if (!FD->getParent()->isCompleteDefinition()) { 3843 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3844 << E->getSourceRange(); 3845 return true; 3846 } 3847 3848 // Otherwise, if it's a field, and the field doesn't have 3849 // reference type, then it must have a complete type (or be a 3850 // flexible array member, which we explicitly want to 3851 // white-list anyway), which makes the following checks trivial. 3852 if (!FD->getType()->isReferenceType()) 3853 return false; 3854 } 3855 3856 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3857 } 3858 3859 bool Sema::CheckVecStepExpr(Expr *E) { 3860 E = E->IgnoreParens(); 3861 3862 // Cannot know anything else if the expression is dependent. 3863 if (E->isTypeDependent()) 3864 return false; 3865 3866 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3867 } 3868 3869 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3870 CapturingScopeInfo *CSI) { 3871 assert(T->isVariablyModifiedType()); 3872 assert(CSI != nullptr); 3873 3874 // We're going to walk down into the type and look for VLA expressions. 3875 do { 3876 const Type *Ty = T.getTypePtr(); 3877 switch (Ty->getTypeClass()) { 3878 #define TYPE(Class, Base) 3879 #define ABSTRACT_TYPE(Class, Base) 3880 #define NON_CANONICAL_TYPE(Class, Base) 3881 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3882 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3883 #include "clang/AST/TypeNodes.def" 3884 T = QualType(); 3885 break; 3886 // These types are never variably-modified. 3887 case Type::Builtin: 3888 case Type::Complex: 3889 case Type::Vector: 3890 case Type::ExtVector: 3891 case Type::Record: 3892 case Type::Enum: 3893 case Type::Elaborated: 3894 case Type::TemplateSpecialization: 3895 case Type::ObjCObject: 3896 case Type::ObjCInterface: 3897 case Type::ObjCObjectPointer: 3898 case Type::ObjCTypeParam: 3899 case Type::Pipe: 3900 llvm_unreachable("type class is never variably-modified!"); 3901 case Type::Adjusted: 3902 T = cast<AdjustedType>(Ty)->getOriginalType(); 3903 break; 3904 case Type::Decayed: 3905 T = cast<DecayedType>(Ty)->getPointeeType(); 3906 break; 3907 case Type::Pointer: 3908 T = cast<PointerType>(Ty)->getPointeeType(); 3909 break; 3910 case Type::BlockPointer: 3911 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3912 break; 3913 case Type::LValueReference: 3914 case Type::RValueReference: 3915 T = cast<ReferenceType>(Ty)->getPointeeType(); 3916 break; 3917 case Type::MemberPointer: 3918 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3919 break; 3920 case Type::ConstantArray: 3921 case Type::IncompleteArray: 3922 // Losing element qualification here is fine. 3923 T = cast<ArrayType>(Ty)->getElementType(); 3924 break; 3925 case Type::VariableArray: { 3926 // Losing element qualification here is fine. 3927 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3928 3929 // Unknown size indication requires no size computation. 3930 // Otherwise, evaluate and record it. 3931 if (auto Size = VAT->getSizeExpr()) { 3932 if (!CSI->isVLATypeCaptured(VAT)) { 3933 RecordDecl *CapRecord = nullptr; 3934 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3935 CapRecord = LSI->Lambda; 3936 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3937 CapRecord = CRSI->TheRecordDecl; 3938 } 3939 if (CapRecord) { 3940 auto ExprLoc = Size->getExprLoc(); 3941 auto SizeType = Context.getSizeType(); 3942 // Build the non-static data member. 3943 auto Field = 3944 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3945 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3946 /*BW*/ nullptr, /*Mutable*/ false, 3947 /*InitStyle*/ ICIS_NoInit); 3948 Field->setImplicit(true); 3949 Field->setAccess(AS_private); 3950 Field->setCapturedVLAType(VAT); 3951 CapRecord->addDecl(Field); 3952 3953 CSI->addVLATypeCapture(ExprLoc, SizeType); 3954 } 3955 } 3956 } 3957 T = VAT->getElementType(); 3958 break; 3959 } 3960 case Type::FunctionProto: 3961 case Type::FunctionNoProto: 3962 T = cast<FunctionType>(Ty)->getReturnType(); 3963 break; 3964 case Type::Paren: 3965 case Type::TypeOf: 3966 case Type::UnaryTransform: 3967 case Type::Attributed: 3968 case Type::SubstTemplateTypeParm: 3969 case Type::PackExpansion: 3970 // Keep walking after single level desugaring. 3971 T = T.getSingleStepDesugaredType(Context); 3972 break; 3973 case Type::Typedef: 3974 T = cast<TypedefType>(Ty)->desugar(); 3975 break; 3976 case Type::Decltype: 3977 T = cast<DecltypeType>(Ty)->desugar(); 3978 break; 3979 case Type::Auto: 3980 case Type::DeducedTemplateSpecialization: 3981 T = cast<DeducedType>(Ty)->getDeducedType(); 3982 break; 3983 case Type::TypeOfExpr: 3984 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3985 break; 3986 case Type::Atomic: 3987 T = cast<AtomicType>(Ty)->getValueType(); 3988 break; 3989 } 3990 } while (!T.isNull() && T->isVariablyModifiedType()); 3991 } 3992 3993 /// Build a sizeof or alignof expression given a type operand. 3994 ExprResult 3995 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3996 SourceLocation OpLoc, 3997 UnaryExprOrTypeTrait ExprKind, 3998 SourceRange R) { 3999 if (!TInfo) 4000 return ExprError(); 4001 4002 QualType T = TInfo->getType(); 4003 4004 if (!T->isDependentType() && 4005 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4006 return ExprError(); 4007 4008 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4009 if (auto *TT = T->getAs<TypedefType>()) { 4010 for (auto I = FunctionScopes.rbegin(), 4011 E = std::prev(FunctionScopes.rend()); 4012 I != E; ++I) { 4013 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4014 if (CSI == nullptr) 4015 break; 4016 DeclContext *DC = nullptr; 4017 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4018 DC = LSI->CallOperator; 4019 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4020 DC = CRSI->TheCapturedDecl; 4021 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4022 DC = BSI->TheDecl; 4023 if (DC) { 4024 if (DC->containsDecl(TT->getDecl())) 4025 break; 4026 captureVariablyModifiedType(Context, T, CSI); 4027 } 4028 } 4029 } 4030 } 4031 4032 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4033 return new (Context) UnaryExprOrTypeTraitExpr( 4034 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4035 } 4036 4037 /// Build a sizeof or alignof expression given an expression 4038 /// operand. 4039 ExprResult 4040 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4041 UnaryExprOrTypeTrait ExprKind) { 4042 ExprResult PE = CheckPlaceholderExpr(E); 4043 if (PE.isInvalid()) 4044 return ExprError(); 4045 4046 E = PE.get(); 4047 4048 // Verify that the operand is valid. 4049 bool isInvalid = false; 4050 if (E->isTypeDependent()) { 4051 // Delay type-checking for type-dependent expressions. 4052 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4053 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4054 } else if (ExprKind == UETT_VecStep) { 4055 isInvalid = CheckVecStepExpr(E); 4056 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4057 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4058 isInvalid = true; 4059 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4060 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4061 isInvalid = true; 4062 } else { 4063 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4064 } 4065 4066 if (isInvalid) 4067 return ExprError(); 4068 4069 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4070 PE = TransformToPotentiallyEvaluated(E); 4071 if (PE.isInvalid()) return ExprError(); 4072 E = PE.get(); 4073 } 4074 4075 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4076 return new (Context) UnaryExprOrTypeTraitExpr( 4077 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4078 } 4079 4080 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4081 /// expr and the same for @c alignof and @c __alignof 4082 /// Note that the ArgRange is invalid if isType is false. 4083 ExprResult 4084 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4085 UnaryExprOrTypeTrait ExprKind, bool IsType, 4086 void *TyOrEx, SourceRange ArgRange) { 4087 // If error parsing type, ignore. 4088 if (!TyOrEx) return ExprError(); 4089 4090 if (IsType) { 4091 TypeSourceInfo *TInfo; 4092 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4093 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4094 } 4095 4096 Expr *ArgEx = (Expr *)TyOrEx; 4097 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4098 return Result; 4099 } 4100 4101 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4102 bool IsReal) { 4103 if (V.get()->isTypeDependent()) 4104 return S.Context.DependentTy; 4105 4106 // _Real and _Imag are only l-values for normal l-values. 4107 if (V.get()->getObjectKind() != OK_Ordinary) { 4108 V = S.DefaultLvalueConversion(V.get()); 4109 if (V.isInvalid()) 4110 return QualType(); 4111 } 4112 4113 // These operators return the element type of a complex type. 4114 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4115 return CT->getElementType(); 4116 4117 // Otherwise they pass through real integer and floating point types here. 4118 if (V.get()->getType()->isArithmeticType()) 4119 return V.get()->getType(); 4120 4121 // Test for placeholders. 4122 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4123 if (PR.isInvalid()) return QualType(); 4124 if (PR.get() != V.get()) { 4125 V = PR; 4126 return CheckRealImagOperand(S, V, Loc, IsReal); 4127 } 4128 4129 // Reject anything else. 4130 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4131 << (IsReal ? "__real" : "__imag"); 4132 return QualType(); 4133 } 4134 4135 4136 4137 ExprResult 4138 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4139 tok::TokenKind Kind, Expr *Input) { 4140 UnaryOperatorKind Opc; 4141 switch (Kind) { 4142 default: llvm_unreachable("Unknown unary op!"); 4143 case tok::plusplus: Opc = UO_PostInc; break; 4144 case tok::minusminus: Opc = UO_PostDec; break; 4145 } 4146 4147 // Since this might is a postfix expression, get rid of ParenListExprs. 4148 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4149 if (Result.isInvalid()) return ExprError(); 4150 Input = Result.get(); 4151 4152 return BuildUnaryOp(S, OpLoc, Opc, Input); 4153 } 4154 4155 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4156 /// 4157 /// \return true on error 4158 static bool checkArithmeticOnObjCPointer(Sema &S, 4159 SourceLocation opLoc, 4160 Expr *op) { 4161 assert(op->getType()->isObjCObjectPointerType()); 4162 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4163 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4164 return false; 4165 4166 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4167 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4168 << op->getSourceRange(); 4169 return true; 4170 } 4171 4172 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4173 auto *BaseNoParens = Base->IgnoreParens(); 4174 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4175 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4176 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4177 } 4178 4179 ExprResult 4180 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4181 Expr *idx, SourceLocation rbLoc) { 4182 if (base && !base->getType().isNull() && 4183 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4184 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4185 /*Length=*/nullptr, rbLoc); 4186 4187 // Since this might be a postfix expression, get rid of ParenListExprs. 4188 if (isa<ParenListExpr>(base)) { 4189 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4190 if (result.isInvalid()) return ExprError(); 4191 base = result.get(); 4192 } 4193 4194 // Handle any non-overload placeholder types in the base and index 4195 // expressions. We can't handle overloads here because the other 4196 // operand might be an overloadable type, in which case the overload 4197 // resolution for the operator overload should get the first crack 4198 // at the overload. 4199 bool IsMSPropertySubscript = false; 4200 if (base->getType()->isNonOverloadPlaceholderType()) { 4201 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4202 if (!IsMSPropertySubscript) { 4203 ExprResult result = CheckPlaceholderExpr(base); 4204 if (result.isInvalid()) 4205 return ExprError(); 4206 base = result.get(); 4207 } 4208 } 4209 if (idx->getType()->isNonOverloadPlaceholderType()) { 4210 ExprResult result = CheckPlaceholderExpr(idx); 4211 if (result.isInvalid()) return ExprError(); 4212 idx = result.get(); 4213 } 4214 4215 // Build an unanalyzed expression if either operand is type-dependent. 4216 if (getLangOpts().CPlusPlus && 4217 (base->isTypeDependent() || idx->isTypeDependent())) { 4218 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4219 VK_LValue, OK_Ordinary, rbLoc); 4220 } 4221 4222 // MSDN, property (C++) 4223 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4224 // This attribute can also be used in the declaration of an empty array in a 4225 // class or structure definition. For example: 4226 // __declspec(property(get=GetX, put=PutX)) int x[]; 4227 // The above statement indicates that x[] can be used with one or more array 4228 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4229 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4230 if (IsMSPropertySubscript) { 4231 // Build MS property subscript expression if base is MS property reference 4232 // or MS property subscript. 4233 return new (Context) MSPropertySubscriptExpr( 4234 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4235 } 4236 4237 // Use C++ overloaded-operator rules if either operand has record 4238 // type. The spec says to do this if either type is *overloadable*, 4239 // but enum types can't declare subscript operators or conversion 4240 // operators, so there's nothing interesting for overload resolution 4241 // to do if there aren't any record types involved. 4242 // 4243 // ObjC pointers have their own subscripting logic that is not tied 4244 // to overload resolution and so should not take this path. 4245 if (getLangOpts().CPlusPlus && 4246 (base->getType()->isRecordType() || 4247 (!base->getType()->isObjCObjectPointerType() && 4248 idx->getType()->isRecordType()))) { 4249 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4250 } 4251 4252 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4253 } 4254 4255 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4256 Expr *LowerBound, 4257 SourceLocation ColonLoc, Expr *Length, 4258 SourceLocation RBLoc) { 4259 if (Base->getType()->isPlaceholderType() && 4260 !Base->getType()->isSpecificPlaceholderType( 4261 BuiltinType::OMPArraySection)) { 4262 ExprResult Result = CheckPlaceholderExpr(Base); 4263 if (Result.isInvalid()) 4264 return ExprError(); 4265 Base = Result.get(); 4266 } 4267 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4268 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4269 if (Result.isInvalid()) 4270 return ExprError(); 4271 Result = DefaultLvalueConversion(Result.get()); 4272 if (Result.isInvalid()) 4273 return ExprError(); 4274 LowerBound = Result.get(); 4275 } 4276 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4277 ExprResult Result = CheckPlaceholderExpr(Length); 4278 if (Result.isInvalid()) 4279 return ExprError(); 4280 Result = DefaultLvalueConversion(Result.get()); 4281 if (Result.isInvalid()) 4282 return ExprError(); 4283 Length = Result.get(); 4284 } 4285 4286 // Build an unanalyzed expression if either operand is type-dependent. 4287 if (Base->isTypeDependent() || 4288 (LowerBound && 4289 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4290 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4291 return new (Context) 4292 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4293 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4294 } 4295 4296 // Perform default conversions. 4297 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4298 QualType ResultTy; 4299 if (OriginalTy->isAnyPointerType()) { 4300 ResultTy = OriginalTy->getPointeeType(); 4301 } else if (OriginalTy->isArrayType()) { 4302 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4303 } else { 4304 return ExprError( 4305 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4306 << Base->getSourceRange()); 4307 } 4308 // C99 6.5.2.1p1 4309 if (LowerBound) { 4310 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4311 LowerBound); 4312 if (Res.isInvalid()) 4313 return ExprError(Diag(LowerBound->getExprLoc(), 4314 diag::err_omp_typecheck_section_not_integer) 4315 << 0 << LowerBound->getSourceRange()); 4316 LowerBound = Res.get(); 4317 4318 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4319 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4320 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4321 << 0 << LowerBound->getSourceRange(); 4322 } 4323 if (Length) { 4324 auto Res = 4325 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4326 if (Res.isInvalid()) 4327 return ExprError(Diag(Length->getExprLoc(), 4328 diag::err_omp_typecheck_section_not_integer) 4329 << 1 << Length->getSourceRange()); 4330 Length = Res.get(); 4331 4332 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4333 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4334 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4335 << 1 << Length->getSourceRange(); 4336 } 4337 4338 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4339 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4340 // type. Note that functions are not objects, and that (in C99 parlance) 4341 // incomplete types are not object types. 4342 if (ResultTy->isFunctionType()) { 4343 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4344 << ResultTy << Base->getSourceRange(); 4345 return ExprError(); 4346 } 4347 4348 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4349 diag::err_omp_section_incomplete_type, Base)) 4350 return ExprError(); 4351 4352 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4353 llvm::APSInt LowerBoundValue; 4354 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4355 // OpenMP 4.5, [2.4 Array Sections] 4356 // The array section must be a subset of the original array. 4357 if (LowerBoundValue.isNegative()) { 4358 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4359 << LowerBound->getSourceRange(); 4360 return ExprError(); 4361 } 4362 } 4363 } 4364 4365 if (Length) { 4366 llvm::APSInt LengthValue; 4367 if (Length->EvaluateAsInt(LengthValue, Context)) { 4368 // OpenMP 4.5, [2.4 Array Sections] 4369 // The length must evaluate to non-negative integers. 4370 if (LengthValue.isNegative()) { 4371 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4372 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4373 << Length->getSourceRange(); 4374 return ExprError(); 4375 } 4376 } 4377 } else if (ColonLoc.isValid() && 4378 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4379 !OriginalTy->isVariableArrayType()))) { 4380 // OpenMP 4.5, [2.4 Array Sections] 4381 // When the size of the array dimension is not known, the length must be 4382 // specified explicitly. 4383 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4384 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4385 return ExprError(); 4386 } 4387 4388 if (!Base->getType()->isSpecificPlaceholderType( 4389 BuiltinType::OMPArraySection)) { 4390 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4391 if (Result.isInvalid()) 4392 return ExprError(); 4393 Base = Result.get(); 4394 } 4395 return new (Context) 4396 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4397 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4398 } 4399 4400 ExprResult 4401 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4402 Expr *Idx, SourceLocation RLoc) { 4403 Expr *LHSExp = Base; 4404 Expr *RHSExp = Idx; 4405 4406 ExprValueKind VK = VK_LValue; 4407 ExprObjectKind OK = OK_Ordinary; 4408 4409 // Per C++ core issue 1213, the result is an xvalue if either operand is 4410 // a non-lvalue array, and an lvalue otherwise. 4411 if (getLangOpts().CPlusPlus11) { 4412 for (auto *Op : {LHSExp, RHSExp}) { 4413 Op = Op->IgnoreImplicit(); 4414 if (Op->getType()->isArrayType() && !Op->isLValue()) 4415 VK = VK_XValue; 4416 } 4417 } 4418 4419 // Perform default conversions. 4420 if (!LHSExp->getType()->getAs<VectorType>()) { 4421 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4422 if (Result.isInvalid()) 4423 return ExprError(); 4424 LHSExp = Result.get(); 4425 } 4426 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4427 if (Result.isInvalid()) 4428 return ExprError(); 4429 RHSExp = Result.get(); 4430 4431 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4432 4433 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4434 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4435 // in the subscript position. As a result, we need to derive the array base 4436 // and index from the expression types. 4437 Expr *BaseExpr, *IndexExpr; 4438 QualType ResultType; 4439 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4440 BaseExpr = LHSExp; 4441 IndexExpr = RHSExp; 4442 ResultType = Context.DependentTy; 4443 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4444 BaseExpr = LHSExp; 4445 IndexExpr = RHSExp; 4446 ResultType = PTy->getPointeeType(); 4447 } else if (const ObjCObjectPointerType *PTy = 4448 LHSTy->getAs<ObjCObjectPointerType>()) { 4449 BaseExpr = LHSExp; 4450 IndexExpr = RHSExp; 4451 4452 // Use custom logic if this should be the pseudo-object subscript 4453 // expression. 4454 if (!LangOpts.isSubscriptPointerArithmetic()) 4455 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4456 nullptr); 4457 4458 ResultType = PTy->getPointeeType(); 4459 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4460 // Handle the uncommon case of "123[Ptr]". 4461 BaseExpr = RHSExp; 4462 IndexExpr = LHSExp; 4463 ResultType = PTy->getPointeeType(); 4464 } else if (const ObjCObjectPointerType *PTy = 4465 RHSTy->getAs<ObjCObjectPointerType>()) { 4466 // Handle the uncommon case of "123[Ptr]". 4467 BaseExpr = RHSExp; 4468 IndexExpr = LHSExp; 4469 ResultType = PTy->getPointeeType(); 4470 if (!LangOpts.isSubscriptPointerArithmetic()) { 4471 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4472 << ResultType << BaseExpr->getSourceRange(); 4473 return ExprError(); 4474 } 4475 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4476 BaseExpr = LHSExp; // vectors: V[123] 4477 IndexExpr = RHSExp; 4478 // We apply C++ DR1213 to vector subscripting too. 4479 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4480 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4481 if (Materialized.isInvalid()) 4482 return ExprError(); 4483 LHSExp = Materialized.get(); 4484 } 4485 VK = LHSExp->getValueKind(); 4486 if (VK != VK_RValue) 4487 OK = OK_VectorComponent; 4488 4489 ResultType = VTy->getElementType(); 4490 QualType BaseType = BaseExpr->getType(); 4491 Qualifiers BaseQuals = BaseType.getQualifiers(); 4492 Qualifiers MemberQuals = ResultType.getQualifiers(); 4493 Qualifiers Combined = BaseQuals + MemberQuals; 4494 if (Combined != MemberQuals) 4495 ResultType = Context.getQualifiedType(ResultType, Combined); 4496 } else if (LHSTy->isArrayType()) { 4497 // If we see an array that wasn't promoted by 4498 // DefaultFunctionArrayLvalueConversion, it must be an array that 4499 // wasn't promoted because of the C90 rule that doesn't 4500 // allow promoting non-lvalue arrays. Warn, then 4501 // force the promotion here. 4502 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4503 << LHSExp->getSourceRange(); 4504 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4505 CK_ArrayToPointerDecay).get(); 4506 LHSTy = LHSExp->getType(); 4507 4508 BaseExpr = LHSExp; 4509 IndexExpr = RHSExp; 4510 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4511 } else if (RHSTy->isArrayType()) { 4512 // Same as previous, except for 123[f().a] case 4513 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4514 << RHSExp->getSourceRange(); 4515 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4516 CK_ArrayToPointerDecay).get(); 4517 RHSTy = RHSExp->getType(); 4518 4519 BaseExpr = RHSExp; 4520 IndexExpr = LHSExp; 4521 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4522 } else { 4523 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4524 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4525 } 4526 // C99 6.5.2.1p1 4527 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4528 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4529 << IndexExpr->getSourceRange()); 4530 4531 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4532 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4533 && !IndexExpr->isTypeDependent()) 4534 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4535 4536 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4537 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4538 // type. Note that Functions are not objects, and that (in C99 parlance) 4539 // incomplete types are not object types. 4540 if (ResultType->isFunctionType()) { 4541 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4542 << ResultType << BaseExpr->getSourceRange(); 4543 return ExprError(); 4544 } 4545 4546 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4547 // GNU extension: subscripting on pointer to void 4548 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4549 << BaseExpr->getSourceRange(); 4550 4551 // C forbids expressions of unqualified void type from being l-values. 4552 // See IsCForbiddenLValueType. 4553 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4554 } else if (!ResultType->isDependentType() && 4555 RequireCompleteType(LLoc, ResultType, 4556 diag::err_subscript_incomplete_type, BaseExpr)) 4557 return ExprError(); 4558 4559 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4560 !ResultType.isCForbiddenLValueType()); 4561 4562 return new (Context) 4563 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4564 } 4565 4566 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4567 ParmVarDecl *Param) { 4568 if (Param->hasUnparsedDefaultArg()) { 4569 Diag(CallLoc, 4570 diag::err_use_of_default_argument_to_function_declared_later) << 4571 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4572 Diag(UnparsedDefaultArgLocs[Param], 4573 diag::note_default_argument_declared_here); 4574 return true; 4575 } 4576 4577 if (Param->hasUninstantiatedDefaultArg()) { 4578 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4579 4580 EnterExpressionEvaluationContext EvalContext( 4581 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4582 4583 // Instantiate the expression. 4584 // 4585 // FIXME: Pass in a correct Pattern argument, otherwise 4586 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4587 // 4588 // template<typename T> 4589 // struct A { 4590 // static int FooImpl(); 4591 // 4592 // template<typename Tp> 4593 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4594 // // template argument list [[T], [Tp]], should be [[Tp]]. 4595 // friend A<Tp> Foo(int a); 4596 // }; 4597 // 4598 // template<typename T> 4599 // A<T> Foo(int a = A<T>::FooImpl()); 4600 MultiLevelTemplateArgumentList MutiLevelArgList 4601 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4602 4603 InstantiatingTemplate Inst(*this, CallLoc, Param, 4604 MutiLevelArgList.getInnermost()); 4605 if (Inst.isInvalid()) 4606 return true; 4607 if (Inst.isAlreadyInstantiating()) { 4608 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4609 Param->setInvalidDecl(); 4610 return true; 4611 } 4612 4613 ExprResult Result; 4614 { 4615 // C++ [dcl.fct.default]p5: 4616 // The names in the [default argument] expression are bound, and 4617 // the semantic constraints are checked, at the point where the 4618 // default argument expression appears. 4619 ContextRAII SavedContext(*this, FD); 4620 LocalInstantiationScope Local(*this); 4621 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4622 /*DirectInit*/false); 4623 } 4624 if (Result.isInvalid()) 4625 return true; 4626 4627 // Check the expression as an initializer for the parameter. 4628 InitializedEntity Entity 4629 = InitializedEntity::InitializeParameter(Context, Param); 4630 InitializationKind Kind = InitializationKind::CreateCopy( 4631 Param->getLocation(), 4632 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4633 Expr *ResultE = Result.getAs<Expr>(); 4634 4635 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4636 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4637 if (Result.isInvalid()) 4638 return true; 4639 4640 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4641 Param->getOuterLocStart()); 4642 if (Result.isInvalid()) 4643 return true; 4644 4645 // Remember the instantiated default argument. 4646 Param->setDefaultArg(Result.getAs<Expr>()); 4647 if (ASTMutationListener *L = getASTMutationListener()) { 4648 L->DefaultArgumentInstantiated(Param); 4649 } 4650 } 4651 4652 // If the default argument expression is not set yet, we are building it now. 4653 if (!Param->hasInit()) { 4654 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4655 Param->setInvalidDecl(); 4656 return true; 4657 } 4658 4659 // If the default expression creates temporaries, we need to 4660 // push them to the current stack of expression temporaries so they'll 4661 // be properly destroyed. 4662 // FIXME: We should really be rebuilding the default argument with new 4663 // bound temporaries; see the comment in PR5810. 4664 // We don't need to do that with block decls, though, because 4665 // blocks in default argument expression can never capture anything. 4666 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4667 // Set the "needs cleanups" bit regardless of whether there are 4668 // any explicit objects. 4669 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4670 4671 // Append all the objects to the cleanup list. Right now, this 4672 // should always be a no-op, because blocks in default argument 4673 // expressions should never be able to capture anything. 4674 assert(!Init->getNumObjects() && 4675 "default argument expression has capturing blocks?"); 4676 } 4677 4678 // We already type-checked the argument, so we know it works. 4679 // Just mark all of the declarations in this potentially-evaluated expression 4680 // as being "referenced". 4681 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4682 /*SkipLocalVariables=*/true); 4683 return false; 4684 } 4685 4686 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4687 FunctionDecl *FD, ParmVarDecl *Param) { 4688 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4689 return ExprError(); 4690 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4691 } 4692 4693 Sema::VariadicCallType 4694 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4695 Expr *Fn) { 4696 if (Proto && Proto->isVariadic()) { 4697 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4698 return VariadicConstructor; 4699 else if (Fn && Fn->getType()->isBlockPointerType()) 4700 return VariadicBlock; 4701 else if (FDecl) { 4702 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4703 if (Method->isInstance()) 4704 return VariadicMethod; 4705 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4706 return VariadicMethod; 4707 return VariadicFunction; 4708 } 4709 return VariadicDoesNotApply; 4710 } 4711 4712 namespace { 4713 class FunctionCallCCC : public FunctionCallFilterCCC { 4714 public: 4715 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4716 unsigned NumArgs, MemberExpr *ME) 4717 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4718 FunctionName(FuncName) {} 4719 4720 bool ValidateCandidate(const TypoCorrection &candidate) override { 4721 if (!candidate.getCorrectionSpecifier() || 4722 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4723 return false; 4724 } 4725 4726 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4727 } 4728 4729 private: 4730 const IdentifierInfo *const FunctionName; 4731 }; 4732 } 4733 4734 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4735 FunctionDecl *FDecl, 4736 ArrayRef<Expr *> Args) { 4737 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4738 DeclarationName FuncName = FDecl->getDeclName(); 4739 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4740 4741 if (TypoCorrection Corrected = S.CorrectTypo( 4742 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4743 S.getScopeForContext(S.CurContext), nullptr, 4744 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4745 Args.size(), ME), 4746 Sema::CTK_ErrorRecovery)) { 4747 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4748 if (Corrected.isOverloaded()) { 4749 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4750 OverloadCandidateSet::iterator Best; 4751 for (NamedDecl *CD : Corrected) { 4752 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4753 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4754 OCS); 4755 } 4756 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4757 case OR_Success: 4758 ND = Best->FoundDecl; 4759 Corrected.setCorrectionDecl(ND); 4760 break; 4761 default: 4762 break; 4763 } 4764 } 4765 ND = ND->getUnderlyingDecl(); 4766 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4767 return Corrected; 4768 } 4769 } 4770 return TypoCorrection(); 4771 } 4772 4773 /// ConvertArgumentsForCall - Converts the arguments specified in 4774 /// Args/NumArgs to the parameter types of the function FDecl with 4775 /// function prototype Proto. Call is the call expression itself, and 4776 /// Fn is the function expression. For a C++ member function, this 4777 /// routine does not attempt to convert the object argument. Returns 4778 /// true if the call is ill-formed. 4779 bool 4780 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4781 FunctionDecl *FDecl, 4782 const FunctionProtoType *Proto, 4783 ArrayRef<Expr *> Args, 4784 SourceLocation RParenLoc, 4785 bool IsExecConfig) { 4786 // Bail out early if calling a builtin with custom typechecking. 4787 if (FDecl) 4788 if (unsigned ID = FDecl->getBuiltinID()) 4789 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4790 return false; 4791 4792 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4793 // assignment, to the types of the corresponding parameter, ... 4794 unsigned NumParams = Proto->getNumParams(); 4795 bool Invalid = false; 4796 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4797 unsigned FnKind = Fn->getType()->isBlockPointerType() 4798 ? 1 /* block */ 4799 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4800 : 0 /* function */); 4801 4802 // If too few arguments are available (and we don't have default 4803 // arguments for the remaining parameters), don't make the call. 4804 if (Args.size() < NumParams) { 4805 if (Args.size() < MinArgs) { 4806 TypoCorrection TC; 4807 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4808 unsigned diag_id = 4809 MinArgs == NumParams && !Proto->isVariadic() 4810 ? diag::err_typecheck_call_too_few_args_suggest 4811 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4812 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4813 << static_cast<unsigned>(Args.size()) 4814 << TC.getCorrectionRange()); 4815 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4816 Diag(RParenLoc, 4817 MinArgs == NumParams && !Proto->isVariadic() 4818 ? diag::err_typecheck_call_too_few_args_one 4819 : diag::err_typecheck_call_too_few_args_at_least_one) 4820 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4821 else 4822 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4823 ? diag::err_typecheck_call_too_few_args 4824 : diag::err_typecheck_call_too_few_args_at_least) 4825 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4826 << Fn->getSourceRange(); 4827 4828 // Emit the location of the prototype. 4829 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4830 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4831 4832 return true; 4833 } 4834 Call->setNumArgs(Context, NumParams); 4835 } 4836 4837 // If too many are passed and not variadic, error on the extras and drop 4838 // them. 4839 if (Args.size() > NumParams) { 4840 if (!Proto->isVariadic()) { 4841 TypoCorrection TC; 4842 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4843 unsigned diag_id = 4844 MinArgs == NumParams && !Proto->isVariadic() 4845 ? diag::err_typecheck_call_too_many_args_suggest 4846 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4847 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4848 << static_cast<unsigned>(Args.size()) 4849 << TC.getCorrectionRange()); 4850 } else if (NumParams == 1 && FDecl && 4851 FDecl->getParamDecl(0)->getDeclName()) 4852 Diag(Args[NumParams]->getBeginLoc(), 4853 MinArgs == NumParams 4854 ? diag::err_typecheck_call_too_many_args_one 4855 : diag::err_typecheck_call_too_many_args_at_most_one) 4856 << FnKind << FDecl->getParamDecl(0) 4857 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4858 << SourceRange(Args[NumParams]->getBeginLoc(), 4859 Args.back()->getEndLoc()); 4860 else 4861 Diag(Args[NumParams]->getBeginLoc(), 4862 MinArgs == NumParams 4863 ? diag::err_typecheck_call_too_many_args 4864 : diag::err_typecheck_call_too_many_args_at_most) 4865 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4866 << Fn->getSourceRange() 4867 << SourceRange(Args[NumParams]->getBeginLoc(), 4868 Args.back()->getEndLoc()); 4869 4870 // Emit the location of the prototype. 4871 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4872 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4873 4874 // This deletes the extra arguments. 4875 Call->setNumArgs(Context, NumParams); 4876 return true; 4877 } 4878 } 4879 SmallVector<Expr *, 8> AllArgs; 4880 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4881 4882 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4883 AllArgs, CallType); 4884 if (Invalid) 4885 return true; 4886 unsigned TotalNumArgs = AllArgs.size(); 4887 for (unsigned i = 0; i < TotalNumArgs; ++i) 4888 Call->setArg(i, AllArgs[i]); 4889 4890 return false; 4891 } 4892 4893 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4894 const FunctionProtoType *Proto, 4895 unsigned FirstParam, ArrayRef<Expr *> Args, 4896 SmallVectorImpl<Expr *> &AllArgs, 4897 VariadicCallType CallType, bool AllowExplicit, 4898 bool IsListInitialization) { 4899 unsigned NumParams = Proto->getNumParams(); 4900 bool Invalid = false; 4901 size_t ArgIx = 0; 4902 // Continue to check argument types (even if we have too few/many args). 4903 for (unsigned i = FirstParam; i < NumParams; i++) { 4904 QualType ProtoArgType = Proto->getParamType(i); 4905 4906 Expr *Arg; 4907 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4908 if (ArgIx < Args.size()) { 4909 Arg = Args[ArgIx++]; 4910 4911 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 4912 diag::err_call_incomplete_argument, Arg)) 4913 return true; 4914 4915 // Strip the unbridged-cast placeholder expression off, if applicable. 4916 bool CFAudited = false; 4917 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4918 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4919 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4920 Arg = stripARCUnbridgedCast(Arg); 4921 else if (getLangOpts().ObjCAutoRefCount && 4922 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4923 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4924 CFAudited = true; 4925 4926 if (Proto->getExtParameterInfo(i).isNoEscape()) 4927 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4928 BE->getBlockDecl()->setDoesNotEscape(); 4929 4930 InitializedEntity Entity = 4931 Param ? InitializedEntity::InitializeParameter(Context, Param, 4932 ProtoArgType) 4933 : InitializedEntity::InitializeParameter( 4934 Context, ProtoArgType, Proto->isParamConsumed(i)); 4935 4936 // Remember that parameter belongs to a CF audited API. 4937 if (CFAudited) 4938 Entity.setParameterCFAudited(); 4939 4940 ExprResult ArgE = PerformCopyInitialization( 4941 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4942 if (ArgE.isInvalid()) 4943 return true; 4944 4945 Arg = ArgE.getAs<Expr>(); 4946 } else { 4947 assert(Param && "can't use default arguments without a known callee"); 4948 4949 ExprResult ArgExpr = 4950 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4951 if (ArgExpr.isInvalid()) 4952 return true; 4953 4954 Arg = ArgExpr.getAs<Expr>(); 4955 } 4956 4957 // Check for array bounds violations for each argument to the call. This 4958 // check only triggers warnings when the argument isn't a more complex Expr 4959 // with its own checking, such as a BinaryOperator. 4960 CheckArrayAccess(Arg); 4961 4962 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4963 CheckStaticArrayArgument(CallLoc, Param, Arg); 4964 4965 AllArgs.push_back(Arg); 4966 } 4967 4968 // If this is a variadic call, handle args passed through "...". 4969 if (CallType != VariadicDoesNotApply) { 4970 // Assume that extern "C" functions with variadic arguments that 4971 // return __unknown_anytype aren't *really* variadic. 4972 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4973 FDecl->isExternC()) { 4974 for (Expr *A : Args.slice(ArgIx)) { 4975 QualType paramType; // ignored 4976 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4977 Invalid |= arg.isInvalid(); 4978 AllArgs.push_back(arg.get()); 4979 } 4980 4981 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4982 } else { 4983 for (Expr *A : Args.slice(ArgIx)) { 4984 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4985 Invalid |= Arg.isInvalid(); 4986 AllArgs.push_back(Arg.get()); 4987 } 4988 } 4989 4990 // Check for array bounds violations. 4991 for (Expr *A : Args.slice(ArgIx)) 4992 CheckArrayAccess(A); 4993 } 4994 return Invalid; 4995 } 4996 4997 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4998 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4999 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5000 TL = DTL.getOriginalLoc(); 5001 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5002 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5003 << ATL.getLocalSourceRange(); 5004 } 5005 5006 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5007 /// array parameter, check that it is non-null, and that if it is formed by 5008 /// array-to-pointer decay, the underlying array is sufficiently large. 5009 /// 5010 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5011 /// array type derivation, then for each call to the function, the value of the 5012 /// corresponding actual argument shall provide access to the first element of 5013 /// an array with at least as many elements as specified by the size expression. 5014 void 5015 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5016 ParmVarDecl *Param, 5017 const Expr *ArgExpr) { 5018 // Static array parameters are not supported in C++. 5019 if (!Param || getLangOpts().CPlusPlus) 5020 return; 5021 5022 QualType OrigTy = Param->getOriginalType(); 5023 5024 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5025 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5026 return; 5027 5028 if (ArgExpr->isNullPointerConstant(Context, 5029 Expr::NPC_NeverValueDependent)) { 5030 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5031 DiagnoseCalleeStaticArrayParam(*this, Param); 5032 return; 5033 } 5034 5035 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5036 if (!CAT) 5037 return; 5038 5039 const ConstantArrayType *ArgCAT = 5040 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5041 if (!ArgCAT) 5042 return; 5043 5044 if (ArgCAT->getSize().ult(CAT->getSize())) { 5045 Diag(CallLoc, diag::warn_static_array_too_small) 5046 << ArgExpr->getSourceRange() 5047 << (unsigned) ArgCAT->getSize().getZExtValue() 5048 << (unsigned) CAT->getSize().getZExtValue(); 5049 DiagnoseCalleeStaticArrayParam(*this, Param); 5050 } 5051 } 5052 5053 /// Given a function expression of unknown-any type, try to rebuild it 5054 /// to have a function type. 5055 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5056 5057 /// Is the given type a placeholder that we need to lower out 5058 /// immediately during argument processing? 5059 static bool isPlaceholderToRemoveAsArg(QualType type) { 5060 // Placeholders are never sugared. 5061 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5062 if (!placeholder) return false; 5063 5064 switch (placeholder->getKind()) { 5065 // Ignore all the non-placeholder types. 5066 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5067 case BuiltinType::Id: 5068 #include "clang/Basic/OpenCLImageTypes.def" 5069 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5070 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5071 #include "clang/AST/BuiltinTypes.def" 5072 return false; 5073 5074 // We cannot lower out overload sets; they might validly be resolved 5075 // by the call machinery. 5076 case BuiltinType::Overload: 5077 return false; 5078 5079 // Unbridged casts in ARC can be handled in some call positions and 5080 // should be left in place. 5081 case BuiltinType::ARCUnbridgedCast: 5082 return false; 5083 5084 // Pseudo-objects should be converted as soon as possible. 5085 case BuiltinType::PseudoObject: 5086 return true; 5087 5088 // The debugger mode could theoretically but currently does not try 5089 // to resolve unknown-typed arguments based on known parameter types. 5090 case BuiltinType::UnknownAny: 5091 return true; 5092 5093 // These are always invalid as call arguments and should be reported. 5094 case BuiltinType::BoundMember: 5095 case BuiltinType::BuiltinFn: 5096 case BuiltinType::OMPArraySection: 5097 return true; 5098 5099 } 5100 llvm_unreachable("bad builtin type kind"); 5101 } 5102 5103 /// Check an argument list for placeholders that we won't try to 5104 /// handle later. 5105 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5106 // Apply this processing to all the arguments at once instead of 5107 // dying at the first failure. 5108 bool hasInvalid = false; 5109 for (size_t i = 0, e = args.size(); i != e; i++) { 5110 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5111 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5112 if (result.isInvalid()) hasInvalid = true; 5113 else args[i] = result.get(); 5114 } else if (hasInvalid) { 5115 (void)S.CorrectDelayedTyposInExpr(args[i]); 5116 } 5117 } 5118 return hasInvalid; 5119 } 5120 5121 /// If a builtin function has a pointer argument with no explicit address 5122 /// space, then it should be able to accept a pointer to any address 5123 /// space as input. In order to do this, we need to replace the 5124 /// standard builtin declaration with one that uses the same address space 5125 /// as the call. 5126 /// 5127 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5128 /// it does not contain any pointer arguments without 5129 /// an address space qualifer. Otherwise the rewritten 5130 /// FunctionDecl is returned. 5131 /// TODO: Handle pointer return types. 5132 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5133 const FunctionDecl *FDecl, 5134 MultiExprArg ArgExprs) { 5135 5136 QualType DeclType = FDecl->getType(); 5137 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5138 5139 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5140 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5141 return nullptr; 5142 5143 bool NeedsNewDecl = false; 5144 unsigned i = 0; 5145 SmallVector<QualType, 8> OverloadParams; 5146 5147 for (QualType ParamType : FT->param_types()) { 5148 5149 // Convert array arguments to pointer to simplify type lookup. 5150 ExprResult ArgRes = 5151 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5152 if (ArgRes.isInvalid()) 5153 return nullptr; 5154 Expr *Arg = ArgRes.get(); 5155 QualType ArgType = Arg->getType(); 5156 if (!ParamType->isPointerType() || 5157 ParamType.getQualifiers().hasAddressSpace() || 5158 !ArgType->isPointerType() || 5159 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5160 OverloadParams.push_back(ParamType); 5161 continue; 5162 } 5163 5164 QualType PointeeType = ParamType->getPointeeType(); 5165 if (PointeeType.getQualifiers().hasAddressSpace()) 5166 continue; 5167 5168 NeedsNewDecl = true; 5169 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5170 5171 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5172 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5173 } 5174 5175 if (!NeedsNewDecl) 5176 return nullptr; 5177 5178 FunctionProtoType::ExtProtoInfo EPI; 5179 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5180 OverloadParams, EPI); 5181 DeclContext *Parent = Context.getTranslationUnitDecl(); 5182 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5183 FDecl->getLocation(), 5184 FDecl->getLocation(), 5185 FDecl->getIdentifier(), 5186 OverloadTy, 5187 /*TInfo=*/nullptr, 5188 SC_Extern, false, 5189 /*hasPrototype=*/true); 5190 SmallVector<ParmVarDecl*, 16> Params; 5191 FT = cast<FunctionProtoType>(OverloadTy); 5192 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5193 QualType ParamType = FT->getParamType(i); 5194 ParmVarDecl *Parm = 5195 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5196 SourceLocation(), nullptr, ParamType, 5197 /*TInfo=*/nullptr, SC_None, nullptr); 5198 Parm->setScopeInfo(0, i); 5199 Params.push_back(Parm); 5200 } 5201 OverloadDecl->setParams(Params); 5202 return OverloadDecl; 5203 } 5204 5205 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5206 FunctionDecl *Callee, 5207 MultiExprArg ArgExprs) { 5208 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5209 // similar attributes) really don't like it when functions are called with an 5210 // invalid number of args. 5211 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5212 /*PartialOverloading=*/false) && 5213 !Callee->isVariadic()) 5214 return; 5215 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5216 return; 5217 5218 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5219 S.Diag(Fn->getBeginLoc(), 5220 isa<CXXMethodDecl>(Callee) 5221 ? diag::err_ovl_no_viable_member_function_in_call 5222 : diag::err_ovl_no_viable_function_in_call) 5223 << Callee << Callee->getSourceRange(); 5224 S.Diag(Callee->getLocation(), 5225 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5226 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5227 return; 5228 } 5229 } 5230 5231 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5232 const UnresolvedMemberExpr *const UME, Sema &S) { 5233 5234 const auto GetFunctionLevelDCIfCXXClass = 5235 [](Sema &S) -> const CXXRecordDecl * { 5236 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5237 if (!DC || !DC->getParent()) 5238 return nullptr; 5239 5240 // If the call to some member function was made from within a member 5241 // function body 'M' return return 'M's parent. 5242 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5243 return MD->getParent()->getCanonicalDecl(); 5244 // else the call was made from within a default member initializer of a 5245 // class, so return the class. 5246 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5247 return RD->getCanonicalDecl(); 5248 return nullptr; 5249 }; 5250 // If our DeclContext is neither a member function nor a class (in the 5251 // case of a lambda in a default member initializer), we can't have an 5252 // enclosing 'this'. 5253 5254 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5255 if (!CurParentClass) 5256 return false; 5257 5258 // The naming class for implicit member functions call is the class in which 5259 // name lookup starts. 5260 const CXXRecordDecl *const NamingClass = 5261 UME->getNamingClass()->getCanonicalDecl(); 5262 assert(NamingClass && "Must have naming class even for implicit access"); 5263 5264 // If the unresolved member functions were found in a 'naming class' that is 5265 // related (either the same or derived from) to the class that contains the 5266 // member function that itself contained the implicit member access. 5267 5268 return CurParentClass == NamingClass || 5269 CurParentClass->isDerivedFrom(NamingClass); 5270 } 5271 5272 static void 5273 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5274 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5275 5276 if (!UME) 5277 return; 5278 5279 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5280 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5281 // already been captured, or if this is an implicit member function call (if 5282 // it isn't, an attempt to capture 'this' should already have been made). 5283 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5284 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5285 return; 5286 5287 // Check if the naming class in which the unresolved members were found is 5288 // related (same as or is a base of) to the enclosing class. 5289 5290 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5291 return; 5292 5293 5294 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5295 // If the enclosing function is not dependent, then this lambda is 5296 // capture ready, so if we can capture this, do so. 5297 if (!EnclosingFunctionCtx->isDependentContext()) { 5298 // If the current lambda and all enclosing lambdas can capture 'this' - 5299 // then go ahead and capture 'this' (since our unresolved overload set 5300 // contains at least one non-static member function). 5301 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5302 S.CheckCXXThisCapture(CallLoc); 5303 } else if (S.CurContext->isDependentContext()) { 5304 // ... since this is an implicit member reference, that might potentially 5305 // involve a 'this' capture, mark 'this' for potential capture in 5306 // enclosing lambdas. 5307 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5308 CurLSI->addPotentialThisCapture(CallLoc); 5309 } 5310 } 5311 5312 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5313 /// This provides the location of the left/right parens and a list of comma 5314 /// locations. 5315 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5316 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5317 Expr *ExecConfig, bool IsExecConfig) { 5318 // Since this might be a postfix expression, get rid of ParenListExprs. 5319 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5320 if (Result.isInvalid()) return ExprError(); 5321 Fn = Result.get(); 5322 5323 if (checkArgsForPlaceholders(*this, ArgExprs)) 5324 return ExprError(); 5325 5326 if (getLangOpts().CPlusPlus) { 5327 // If this is a pseudo-destructor expression, build the call immediately. 5328 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5329 if (!ArgExprs.empty()) { 5330 // Pseudo-destructor calls should not have any arguments. 5331 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5332 << FixItHint::CreateRemoval( 5333 SourceRange(ArgExprs.front()->getBeginLoc(), 5334 ArgExprs.back()->getEndLoc())); 5335 } 5336 5337 return new (Context) 5338 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5339 } 5340 if (Fn->getType() == Context.PseudoObjectTy) { 5341 ExprResult result = CheckPlaceholderExpr(Fn); 5342 if (result.isInvalid()) return ExprError(); 5343 Fn = result.get(); 5344 } 5345 5346 // Determine whether this is a dependent call inside a C++ template, 5347 // in which case we won't do any semantic analysis now. 5348 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5349 if (ExecConfig) { 5350 return new (Context) CUDAKernelCallExpr( 5351 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5352 Context.DependentTy, VK_RValue, RParenLoc); 5353 } else { 5354 5355 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5356 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5357 Fn->getBeginLoc()); 5358 5359 return new (Context) CallExpr( 5360 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5361 } 5362 } 5363 5364 // Determine whether this is a call to an object (C++ [over.call.object]). 5365 if (Fn->getType()->isRecordType()) 5366 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5367 RParenLoc); 5368 5369 if (Fn->getType() == Context.UnknownAnyTy) { 5370 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5371 if (result.isInvalid()) return ExprError(); 5372 Fn = result.get(); 5373 } 5374 5375 if (Fn->getType() == Context.BoundMemberTy) { 5376 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5377 RParenLoc); 5378 } 5379 } 5380 5381 // Check for overloaded calls. This can happen even in C due to extensions. 5382 if (Fn->getType() == Context.OverloadTy) { 5383 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5384 5385 // We aren't supposed to apply this logic if there's an '&' involved. 5386 if (!find.HasFormOfMemberPointer) { 5387 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5388 return new (Context) CallExpr( 5389 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5390 OverloadExpr *ovl = find.Expression; 5391 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5392 return BuildOverloadedCallExpr( 5393 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5394 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5395 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5396 RParenLoc); 5397 } 5398 } 5399 5400 // If we're directly calling a function, get the appropriate declaration. 5401 if (Fn->getType() == Context.UnknownAnyTy) { 5402 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5403 if (result.isInvalid()) return ExprError(); 5404 Fn = result.get(); 5405 } 5406 5407 Expr *NakedFn = Fn->IgnoreParens(); 5408 5409 bool CallingNDeclIndirectly = false; 5410 NamedDecl *NDecl = nullptr; 5411 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5412 if (UnOp->getOpcode() == UO_AddrOf) { 5413 CallingNDeclIndirectly = true; 5414 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5415 } 5416 } 5417 5418 if (isa<DeclRefExpr>(NakedFn)) { 5419 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5420 5421 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5422 if (FDecl && FDecl->getBuiltinID()) { 5423 // Rewrite the function decl for this builtin by replacing parameters 5424 // with no explicit address space with the address space of the arguments 5425 // in ArgExprs. 5426 if ((FDecl = 5427 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5428 NDecl = FDecl; 5429 Fn = DeclRefExpr::Create( 5430 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5431 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5432 } 5433 } 5434 } else if (isa<MemberExpr>(NakedFn)) 5435 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5436 5437 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5438 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5439 FD, /*Complain=*/true, Fn->getBeginLoc())) 5440 return ExprError(); 5441 5442 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5443 return ExprError(); 5444 5445 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5446 } 5447 5448 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5449 ExecConfig, IsExecConfig); 5450 } 5451 5452 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5453 /// 5454 /// __builtin_astype( value, dst type ) 5455 /// 5456 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5457 SourceLocation BuiltinLoc, 5458 SourceLocation RParenLoc) { 5459 ExprValueKind VK = VK_RValue; 5460 ExprObjectKind OK = OK_Ordinary; 5461 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5462 QualType SrcTy = E->getType(); 5463 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5464 return ExprError(Diag(BuiltinLoc, 5465 diag::err_invalid_astype_of_different_size) 5466 << DstTy 5467 << SrcTy 5468 << E->getSourceRange()); 5469 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5470 } 5471 5472 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5473 /// provided arguments. 5474 /// 5475 /// __builtin_convertvector( value, dst type ) 5476 /// 5477 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5478 SourceLocation BuiltinLoc, 5479 SourceLocation RParenLoc) { 5480 TypeSourceInfo *TInfo; 5481 GetTypeFromParser(ParsedDestTy, &TInfo); 5482 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5483 } 5484 5485 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5486 /// i.e. an expression not of \p OverloadTy. The expression should 5487 /// unary-convert to an expression of function-pointer or 5488 /// block-pointer type. 5489 /// 5490 /// \param NDecl the declaration being called, if available 5491 ExprResult 5492 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5493 SourceLocation LParenLoc, 5494 ArrayRef<Expr *> Args, 5495 SourceLocation RParenLoc, 5496 Expr *Config, bool IsExecConfig) { 5497 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5498 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5499 5500 // Functions with 'interrupt' attribute cannot be called directly. 5501 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5502 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5503 return ExprError(); 5504 } 5505 5506 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5507 // so there's some risk when calling out to non-interrupt handler functions 5508 // that the callee might not preserve them. This is easy to diagnose here, 5509 // but can be very challenging to debug. 5510 if (auto *Caller = getCurFunctionDecl()) 5511 if (Caller->hasAttr<ARMInterruptAttr>()) { 5512 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5513 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5514 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5515 } 5516 5517 // Promote the function operand. 5518 // We special-case function promotion here because we only allow promoting 5519 // builtin functions to function pointers in the callee of a call. 5520 ExprResult Result; 5521 if (BuiltinID && 5522 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5523 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5524 CK_BuiltinFnToFnPtr).get(); 5525 } else { 5526 Result = CallExprUnaryConversions(Fn); 5527 } 5528 if (Result.isInvalid()) 5529 return ExprError(); 5530 Fn = Result.get(); 5531 5532 // Make the call expr early, before semantic checks. This guarantees cleanup 5533 // of arguments and function on error. 5534 CallExpr *TheCall; 5535 if (Config) 5536 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5537 cast<CallExpr>(Config), Args, 5538 Context.BoolTy, VK_RValue, 5539 RParenLoc); 5540 else 5541 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5542 VK_RValue, RParenLoc); 5543 5544 if (!getLangOpts().CPlusPlus) { 5545 // C cannot always handle TypoExpr nodes in builtin calls and direct 5546 // function calls as their argument checking don't necessarily handle 5547 // dependent types properly, so make sure any TypoExprs have been 5548 // dealt with. 5549 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5550 if (!Result.isUsable()) return ExprError(); 5551 TheCall = dyn_cast<CallExpr>(Result.get()); 5552 if (!TheCall) return Result; 5553 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5554 } 5555 5556 // Bail out early if calling a builtin with custom typechecking. 5557 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5558 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5559 5560 retry: 5561 const FunctionType *FuncT; 5562 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5563 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5564 // have type pointer to function". 5565 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5566 if (!FuncT) 5567 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5568 << Fn->getType() << Fn->getSourceRange()); 5569 } else if (const BlockPointerType *BPT = 5570 Fn->getType()->getAs<BlockPointerType>()) { 5571 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5572 } else { 5573 // Handle calls to expressions of unknown-any type. 5574 if (Fn->getType() == Context.UnknownAnyTy) { 5575 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5576 if (rewrite.isInvalid()) return ExprError(); 5577 Fn = rewrite.get(); 5578 TheCall->setCallee(Fn); 5579 goto retry; 5580 } 5581 5582 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5583 << Fn->getType() << Fn->getSourceRange()); 5584 } 5585 5586 if (getLangOpts().CUDA) { 5587 if (Config) { 5588 // CUDA: Kernel calls must be to global functions 5589 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5590 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5591 << FDecl << Fn->getSourceRange()); 5592 5593 // CUDA: Kernel function must have 'void' return type 5594 if (!FuncT->getReturnType()->isVoidType()) 5595 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5596 << Fn->getType() << Fn->getSourceRange()); 5597 } else { 5598 // CUDA: Calls to global functions must be configured 5599 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5600 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5601 << FDecl << Fn->getSourceRange()); 5602 } 5603 } 5604 5605 // Check for a valid return type 5606 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5607 FDecl)) 5608 return ExprError(); 5609 5610 // We know the result type of the call, set it. 5611 TheCall->setType(FuncT->getCallResultType(Context)); 5612 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5613 5614 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5615 if (Proto) { 5616 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5617 IsExecConfig)) 5618 return ExprError(); 5619 } else { 5620 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5621 5622 if (FDecl) { 5623 // Check if we have too few/too many template arguments, based 5624 // on our knowledge of the function definition. 5625 const FunctionDecl *Def = nullptr; 5626 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5627 Proto = Def->getType()->getAs<FunctionProtoType>(); 5628 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5629 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5630 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5631 } 5632 5633 // If the function we're calling isn't a function prototype, but we have 5634 // a function prototype from a prior declaratiom, use that prototype. 5635 if (!FDecl->hasPrototype()) 5636 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5637 } 5638 5639 // Promote the arguments (C99 6.5.2.2p6). 5640 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5641 Expr *Arg = Args[i]; 5642 5643 if (Proto && i < Proto->getNumParams()) { 5644 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5645 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5646 ExprResult ArgE = 5647 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5648 if (ArgE.isInvalid()) 5649 return true; 5650 5651 Arg = ArgE.getAs<Expr>(); 5652 5653 } else { 5654 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5655 5656 if (ArgE.isInvalid()) 5657 return true; 5658 5659 Arg = ArgE.getAs<Expr>(); 5660 } 5661 5662 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5663 diag::err_call_incomplete_argument, Arg)) 5664 return ExprError(); 5665 5666 TheCall->setArg(i, Arg); 5667 } 5668 } 5669 5670 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5671 if (!Method->isStatic()) 5672 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5673 << Fn->getSourceRange()); 5674 5675 // Check for sentinels 5676 if (NDecl) 5677 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5678 5679 // Do special checking on direct calls to functions. 5680 if (FDecl) { 5681 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5682 return ExprError(); 5683 5684 if (BuiltinID) 5685 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5686 } else if (NDecl) { 5687 if (CheckPointerCall(NDecl, TheCall, Proto)) 5688 return ExprError(); 5689 } else { 5690 if (CheckOtherCall(TheCall, Proto)) 5691 return ExprError(); 5692 } 5693 5694 return MaybeBindToTemporary(TheCall); 5695 } 5696 5697 ExprResult 5698 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5699 SourceLocation RParenLoc, Expr *InitExpr) { 5700 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5701 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5702 5703 TypeSourceInfo *TInfo; 5704 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5705 if (!TInfo) 5706 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5707 5708 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5709 } 5710 5711 ExprResult 5712 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5713 SourceLocation RParenLoc, Expr *LiteralExpr) { 5714 QualType literalType = TInfo->getType(); 5715 5716 if (literalType->isArrayType()) { 5717 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5718 diag::err_illegal_decl_array_incomplete_type, 5719 SourceRange(LParenLoc, 5720 LiteralExpr->getSourceRange().getEnd()))) 5721 return ExprError(); 5722 if (literalType->isVariableArrayType()) 5723 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5724 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5725 } else if (!literalType->isDependentType() && 5726 RequireCompleteType(LParenLoc, literalType, 5727 diag::err_typecheck_decl_incomplete_type, 5728 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5729 return ExprError(); 5730 5731 InitializedEntity Entity 5732 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5733 InitializationKind Kind 5734 = InitializationKind::CreateCStyleCast(LParenLoc, 5735 SourceRange(LParenLoc, RParenLoc), 5736 /*InitList=*/true); 5737 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5738 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5739 &literalType); 5740 if (Result.isInvalid()) 5741 return ExprError(); 5742 LiteralExpr = Result.get(); 5743 5744 bool isFileScope = !CurContext->isFunctionOrMethod(); 5745 if (isFileScope) { 5746 if (!LiteralExpr->isTypeDependent() && 5747 !LiteralExpr->isValueDependent() && 5748 !literalType->isDependentType()) // C99 6.5.2.5p3 5749 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5750 return ExprError(); 5751 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 5752 literalType.getAddressSpace() != LangAS::Default) { 5753 // Embedded-C extensions to C99 6.5.2.5: 5754 // "If the compound literal occurs inside the body of a function, the 5755 // type name shall not be qualified by an address-space qualifier." 5756 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 5757 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 5758 return ExprError(); 5759 } 5760 5761 // In C, compound literals are l-values for some reason. 5762 // For GCC compatibility, in C++, file-scope array compound literals with 5763 // constant initializers are also l-values, and compound literals are 5764 // otherwise prvalues. 5765 // 5766 // (GCC also treats C++ list-initialized file-scope array prvalues with 5767 // constant initializers as l-values, but that's non-conforming, so we don't 5768 // follow it there.) 5769 // 5770 // FIXME: It would be better to handle the lvalue cases as materializing and 5771 // lifetime-extending a temporary object, but our materialized temporaries 5772 // representation only supports lifetime extension from a variable, not "out 5773 // of thin air". 5774 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5775 // is bound to the result of applying array-to-pointer decay to the compound 5776 // literal. 5777 // FIXME: GCC supports compound literals of reference type, which should 5778 // obviously have a value kind derived from the kind of reference involved. 5779 ExprValueKind VK = 5780 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5781 ? VK_RValue 5782 : VK_LValue; 5783 5784 return MaybeBindToTemporary( 5785 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5786 VK, LiteralExpr, isFileScope)); 5787 } 5788 5789 ExprResult 5790 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5791 SourceLocation RBraceLoc) { 5792 // Immediately handle non-overload placeholders. Overloads can be 5793 // resolved contextually, but everything else here can't. 5794 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5795 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5796 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5797 5798 // Ignore failures; dropping the entire initializer list because 5799 // of one failure would be terrible for indexing/etc. 5800 if (result.isInvalid()) continue; 5801 5802 InitArgList[I] = result.get(); 5803 } 5804 } 5805 5806 // Semantic analysis for initializers is done by ActOnDeclarator() and 5807 // CheckInitializer() - it requires knowledge of the object being initialized. 5808 5809 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5810 RBraceLoc); 5811 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5812 return E; 5813 } 5814 5815 /// Do an explicit extend of the given block pointer if we're in ARC. 5816 void Sema::maybeExtendBlockObject(ExprResult &E) { 5817 assert(E.get()->getType()->isBlockPointerType()); 5818 assert(E.get()->isRValue()); 5819 5820 // Only do this in an r-value context. 5821 if (!getLangOpts().ObjCAutoRefCount) return; 5822 5823 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5824 CK_ARCExtendBlockObject, E.get(), 5825 /*base path*/ nullptr, VK_RValue); 5826 Cleanup.setExprNeedsCleanups(true); 5827 } 5828 5829 /// Prepare a conversion of the given expression to an ObjC object 5830 /// pointer type. 5831 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5832 QualType type = E.get()->getType(); 5833 if (type->isObjCObjectPointerType()) { 5834 return CK_BitCast; 5835 } else if (type->isBlockPointerType()) { 5836 maybeExtendBlockObject(E); 5837 return CK_BlockPointerToObjCPointerCast; 5838 } else { 5839 assert(type->isPointerType()); 5840 return CK_CPointerToObjCPointerCast; 5841 } 5842 } 5843 5844 /// Prepares for a scalar cast, performing all the necessary stages 5845 /// except the final cast and returning the kind required. 5846 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5847 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5848 // Also, callers should have filtered out the invalid cases with 5849 // pointers. Everything else should be possible. 5850 5851 QualType SrcTy = Src.get()->getType(); 5852 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5853 return CK_NoOp; 5854 5855 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5856 case Type::STK_MemberPointer: 5857 llvm_unreachable("member pointer type in C"); 5858 5859 case Type::STK_CPointer: 5860 case Type::STK_BlockPointer: 5861 case Type::STK_ObjCObjectPointer: 5862 switch (DestTy->getScalarTypeKind()) { 5863 case Type::STK_CPointer: { 5864 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5865 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5866 if (SrcAS != DestAS) 5867 return CK_AddressSpaceConversion; 5868 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 5869 return CK_NoOp; 5870 return CK_BitCast; 5871 } 5872 case Type::STK_BlockPointer: 5873 return (SrcKind == Type::STK_BlockPointer 5874 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5875 case Type::STK_ObjCObjectPointer: 5876 if (SrcKind == Type::STK_ObjCObjectPointer) 5877 return CK_BitCast; 5878 if (SrcKind == Type::STK_CPointer) 5879 return CK_CPointerToObjCPointerCast; 5880 maybeExtendBlockObject(Src); 5881 return CK_BlockPointerToObjCPointerCast; 5882 case Type::STK_Bool: 5883 return CK_PointerToBoolean; 5884 case Type::STK_Integral: 5885 return CK_PointerToIntegral; 5886 case Type::STK_Floating: 5887 case Type::STK_FloatingComplex: 5888 case Type::STK_IntegralComplex: 5889 case Type::STK_MemberPointer: 5890 case Type::STK_FixedPoint: 5891 llvm_unreachable("illegal cast from pointer"); 5892 } 5893 llvm_unreachable("Should have returned before this"); 5894 5895 case Type::STK_FixedPoint: 5896 switch (DestTy->getScalarTypeKind()) { 5897 case Type::STK_FixedPoint: 5898 return CK_FixedPointCast; 5899 case Type::STK_Bool: 5900 return CK_FixedPointToBoolean; 5901 case Type::STK_Integral: 5902 case Type::STK_Floating: 5903 case Type::STK_IntegralComplex: 5904 case Type::STK_FloatingComplex: 5905 Diag(Src.get()->getExprLoc(), 5906 diag::err_unimplemented_conversion_with_fixed_point_type) 5907 << DestTy; 5908 return CK_IntegralCast; 5909 case Type::STK_CPointer: 5910 case Type::STK_ObjCObjectPointer: 5911 case Type::STK_BlockPointer: 5912 case Type::STK_MemberPointer: 5913 llvm_unreachable("illegal cast to pointer type"); 5914 } 5915 llvm_unreachable("Should have returned before this"); 5916 5917 case Type::STK_Bool: // casting from bool is like casting from an integer 5918 case Type::STK_Integral: 5919 switch (DestTy->getScalarTypeKind()) { 5920 case Type::STK_CPointer: 5921 case Type::STK_ObjCObjectPointer: 5922 case Type::STK_BlockPointer: 5923 if (Src.get()->isNullPointerConstant(Context, 5924 Expr::NPC_ValueDependentIsNull)) 5925 return CK_NullToPointer; 5926 return CK_IntegralToPointer; 5927 case Type::STK_Bool: 5928 return CK_IntegralToBoolean; 5929 case Type::STK_Integral: 5930 return CK_IntegralCast; 5931 case Type::STK_Floating: 5932 return CK_IntegralToFloating; 5933 case Type::STK_IntegralComplex: 5934 Src = ImpCastExprToType(Src.get(), 5935 DestTy->castAs<ComplexType>()->getElementType(), 5936 CK_IntegralCast); 5937 return CK_IntegralRealToComplex; 5938 case Type::STK_FloatingComplex: 5939 Src = ImpCastExprToType(Src.get(), 5940 DestTy->castAs<ComplexType>()->getElementType(), 5941 CK_IntegralToFloating); 5942 return CK_FloatingRealToComplex; 5943 case Type::STK_MemberPointer: 5944 llvm_unreachable("member pointer type in C"); 5945 case Type::STK_FixedPoint: 5946 Diag(Src.get()->getExprLoc(), 5947 diag::err_unimplemented_conversion_with_fixed_point_type) 5948 << SrcTy; 5949 return CK_IntegralCast; 5950 } 5951 llvm_unreachable("Should have returned before this"); 5952 5953 case Type::STK_Floating: 5954 switch (DestTy->getScalarTypeKind()) { 5955 case Type::STK_Floating: 5956 return CK_FloatingCast; 5957 case Type::STK_Bool: 5958 return CK_FloatingToBoolean; 5959 case Type::STK_Integral: 5960 return CK_FloatingToIntegral; 5961 case Type::STK_FloatingComplex: 5962 Src = ImpCastExprToType(Src.get(), 5963 DestTy->castAs<ComplexType>()->getElementType(), 5964 CK_FloatingCast); 5965 return CK_FloatingRealToComplex; 5966 case Type::STK_IntegralComplex: 5967 Src = ImpCastExprToType(Src.get(), 5968 DestTy->castAs<ComplexType>()->getElementType(), 5969 CK_FloatingToIntegral); 5970 return CK_IntegralRealToComplex; 5971 case Type::STK_CPointer: 5972 case Type::STK_ObjCObjectPointer: 5973 case Type::STK_BlockPointer: 5974 llvm_unreachable("valid float->pointer cast?"); 5975 case Type::STK_MemberPointer: 5976 llvm_unreachable("member pointer type in C"); 5977 case Type::STK_FixedPoint: 5978 Diag(Src.get()->getExprLoc(), 5979 diag::err_unimplemented_conversion_with_fixed_point_type) 5980 << SrcTy; 5981 return CK_IntegralCast; 5982 } 5983 llvm_unreachable("Should have returned before this"); 5984 5985 case Type::STK_FloatingComplex: 5986 switch (DestTy->getScalarTypeKind()) { 5987 case Type::STK_FloatingComplex: 5988 return CK_FloatingComplexCast; 5989 case Type::STK_IntegralComplex: 5990 return CK_FloatingComplexToIntegralComplex; 5991 case Type::STK_Floating: { 5992 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5993 if (Context.hasSameType(ET, DestTy)) 5994 return CK_FloatingComplexToReal; 5995 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5996 return CK_FloatingCast; 5997 } 5998 case Type::STK_Bool: 5999 return CK_FloatingComplexToBoolean; 6000 case Type::STK_Integral: 6001 Src = ImpCastExprToType(Src.get(), 6002 SrcTy->castAs<ComplexType>()->getElementType(), 6003 CK_FloatingComplexToReal); 6004 return CK_FloatingToIntegral; 6005 case Type::STK_CPointer: 6006 case Type::STK_ObjCObjectPointer: 6007 case Type::STK_BlockPointer: 6008 llvm_unreachable("valid complex float->pointer cast?"); 6009 case Type::STK_MemberPointer: 6010 llvm_unreachable("member pointer type in C"); 6011 case Type::STK_FixedPoint: 6012 Diag(Src.get()->getExprLoc(), 6013 diag::err_unimplemented_conversion_with_fixed_point_type) 6014 << SrcTy; 6015 return CK_IntegralCast; 6016 } 6017 llvm_unreachable("Should have returned before this"); 6018 6019 case Type::STK_IntegralComplex: 6020 switch (DestTy->getScalarTypeKind()) { 6021 case Type::STK_FloatingComplex: 6022 return CK_IntegralComplexToFloatingComplex; 6023 case Type::STK_IntegralComplex: 6024 return CK_IntegralComplexCast; 6025 case Type::STK_Integral: { 6026 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6027 if (Context.hasSameType(ET, DestTy)) 6028 return CK_IntegralComplexToReal; 6029 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6030 return CK_IntegralCast; 6031 } 6032 case Type::STK_Bool: 6033 return CK_IntegralComplexToBoolean; 6034 case Type::STK_Floating: 6035 Src = ImpCastExprToType(Src.get(), 6036 SrcTy->castAs<ComplexType>()->getElementType(), 6037 CK_IntegralComplexToReal); 6038 return CK_IntegralToFloating; 6039 case Type::STK_CPointer: 6040 case Type::STK_ObjCObjectPointer: 6041 case Type::STK_BlockPointer: 6042 llvm_unreachable("valid complex int->pointer cast?"); 6043 case Type::STK_MemberPointer: 6044 llvm_unreachable("member pointer type in C"); 6045 case Type::STK_FixedPoint: 6046 Diag(Src.get()->getExprLoc(), 6047 diag::err_unimplemented_conversion_with_fixed_point_type) 6048 << SrcTy; 6049 return CK_IntegralCast; 6050 } 6051 llvm_unreachable("Should have returned before this"); 6052 } 6053 6054 llvm_unreachable("Unhandled scalar cast"); 6055 } 6056 6057 static bool breakDownVectorType(QualType type, uint64_t &len, 6058 QualType &eltType) { 6059 // Vectors are simple. 6060 if (const VectorType *vecType = type->getAs<VectorType>()) { 6061 len = vecType->getNumElements(); 6062 eltType = vecType->getElementType(); 6063 assert(eltType->isScalarType()); 6064 return true; 6065 } 6066 6067 // We allow lax conversion to and from non-vector types, but only if 6068 // they're real types (i.e. non-complex, non-pointer scalar types). 6069 if (!type->isRealType()) return false; 6070 6071 len = 1; 6072 eltType = type; 6073 return true; 6074 } 6075 6076 /// Are the two types lax-compatible vector types? That is, given 6077 /// that one of them is a vector, do they have equal storage sizes, 6078 /// where the storage size is the number of elements times the element 6079 /// size? 6080 /// 6081 /// This will also return false if either of the types is neither a 6082 /// vector nor a real type. 6083 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6084 assert(destTy->isVectorType() || srcTy->isVectorType()); 6085 6086 // Disallow lax conversions between scalars and ExtVectors (these 6087 // conversions are allowed for other vector types because common headers 6088 // depend on them). Most scalar OP ExtVector cases are handled by the 6089 // splat path anyway, which does what we want (convert, not bitcast). 6090 // What this rules out for ExtVectors is crazy things like char4*float. 6091 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6092 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6093 6094 uint64_t srcLen, destLen; 6095 QualType srcEltTy, destEltTy; 6096 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6097 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6098 6099 // ASTContext::getTypeSize will return the size rounded up to a 6100 // power of 2, so instead of using that, we need to use the raw 6101 // element size multiplied by the element count. 6102 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6103 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6104 6105 return (srcLen * srcEltSize == destLen * destEltSize); 6106 } 6107 6108 /// Is this a legal conversion between two types, one of which is 6109 /// known to be a vector type? 6110 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6111 assert(destTy->isVectorType() || srcTy->isVectorType()); 6112 6113 if (!Context.getLangOpts().LaxVectorConversions) 6114 return false; 6115 return areLaxCompatibleVectorTypes(srcTy, destTy); 6116 } 6117 6118 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6119 CastKind &Kind) { 6120 assert(VectorTy->isVectorType() && "Not a vector type!"); 6121 6122 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6123 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6124 return Diag(R.getBegin(), 6125 Ty->isVectorType() ? 6126 diag::err_invalid_conversion_between_vectors : 6127 diag::err_invalid_conversion_between_vector_and_integer) 6128 << VectorTy << Ty << R; 6129 } else 6130 return Diag(R.getBegin(), 6131 diag::err_invalid_conversion_between_vector_and_scalar) 6132 << VectorTy << Ty << R; 6133 6134 Kind = CK_BitCast; 6135 return false; 6136 } 6137 6138 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6139 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6140 6141 if (DestElemTy == SplattedExpr->getType()) 6142 return SplattedExpr; 6143 6144 assert(DestElemTy->isFloatingType() || 6145 DestElemTy->isIntegralOrEnumerationType()); 6146 6147 CastKind CK; 6148 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6149 // OpenCL requires that we convert `true` boolean expressions to -1, but 6150 // only when splatting vectors. 6151 if (DestElemTy->isFloatingType()) { 6152 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6153 // in two steps: boolean to signed integral, then to floating. 6154 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6155 CK_BooleanToSignedIntegral); 6156 SplattedExpr = CastExprRes.get(); 6157 CK = CK_IntegralToFloating; 6158 } else { 6159 CK = CK_BooleanToSignedIntegral; 6160 } 6161 } else { 6162 ExprResult CastExprRes = SplattedExpr; 6163 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6164 if (CastExprRes.isInvalid()) 6165 return ExprError(); 6166 SplattedExpr = CastExprRes.get(); 6167 } 6168 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6169 } 6170 6171 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6172 Expr *CastExpr, CastKind &Kind) { 6173 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6174 6175 QualType SrcTy = CastExpr->getType(); 6176 6177 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6178 // an ExtVectorType. 6179 // In OpenCL, casts between vectors of different types are not allowed. 6180 // (See OpenCL 6.2). 6181 if (SrcTy->isVectorType()) { 6182 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6183 (getLangOpts().OpenCL && 6184 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6185 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6186 << DestTy << SrcTy << R; 6187 return ExprError(); 6188 } 6189 Kind = CK_BitCast; 6190 return CastExpr; 6191 } 6192 6193 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6194 // conversion will take place first from scalar to elt type, and then 6195 // splat from elt type to vector. 6196 if (SrcTy->isPointerType()) 6197 return Diag(R.getBegin(), 6198 diag::err_invalid_conversion_between_vector_and_scalar) 6199 << DestTy << SrcTy << R; 6200 6201 Kind = CK_VectorSplat; 6202 return prepareVectorSplat(DestTy, CastExpr); 6203 } 6204 6205 ExprResult 6206 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6207 Declarator &D, ParsedType &Ty, 6208 SourceLocation RParenLoc, Expr *CastExpr) { 6209 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6210 "ActOnCastExpr(): missing type or expr"); 6211 6212 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6213 if (D.isInvalidType()) 6214 return ExprError(); 6215 6216 if (getLangOpts().CPlusPlus) { 6217 // Check that there are no default arguments (C++ only). 6218 CheckExtraCXXDefaultArguments(D); 6219 } else { 6220 // Make sure any TypoExprs have been dealt with. 6221 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6222 if (!Res.isUsable()) 6223 return ExprError(); 6224 CastExpr = Res.get(); 6225 } 6226 6227 checkUnusedDeclAttributes(D); 6228 6229 QualType castType = castTInfo->getType(); 6230 Ty = CreateParsedType(castType, castTInfo); 6231 6232 bool isVectorLiteral = false; 6233 6234 // Check for an altivec or OpenCL literal, 6235 // i.e. all the elements are integer constants. 6236 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6237 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6238 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6239 && castType->isVectorType() && (PE || PLE)) { 6240 if (PLE && PLE->getNumExprs() == 0) { 6241 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6242 return ExprError(); 6243 } 6244 if (PE || PLE->getNumExprs() == 1) { 6245 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6246 if (!E->getType()->isVectorType()) 6247 isVectorLiteral = true; 6248 } 6249 else 6250 isVectorLiteral = true; 6251 } 6252 6253 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6254 // then handle it as such. 6255 if (isVectorLiteral) 6256 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6257 6258 // If the Expr being casted is a ParenListExpr, handle it specially. 6259 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6260 // sequence of BinOp comma operators. 6261 if (isa<ParenListExpr>(CastExpr)) { 6262 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6263 if (Result.isInvalid()) return ExprError(); 6264 CastExpr = Result.get(); 6265 } 6266 6267 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6268 !getSourceManager().isInSystemMacro(LParenLoc)) 6269 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6270 6271 CheckTollFreeBridgeCast(castType, CastExpr); 6272 6273 CheckObjCBridgeRelatedCast(castType, CastExpr); 6274 6275 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6276 6277 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6278 } 6279 6280 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6281 SourceLocation RParenLoc, Expr *E, 6282 TypeSourceInfo *TInfo) { 6283 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6284 "Expected paren or paren list expression"); 6285 6286 Expr **exprs; 6287 unsigned numExprs; 6288 Expr *subExpr; 6289 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6290 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6291 LiteralLParenLoc = PE->getLParenLoc(); 6292 LiteralRParenLoc = PE->getRParenLoc(); 6293 exprs = PE->getExprs(); 6294 numExprs = PE->getNumExprs(); 6295 } else { // isa<ParenExpr> by assertion at function entrance 6296 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6297 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6298 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6299 exprs = &subExpr; 6300 numExprs = 1; 6301 } 6302 6303 QualType Ty = TInfo->getType(); 6304 assert(Ty->isVectorType() && "Expected vector type"); 6305 6306 SmallVector<Expr *, 8> initExprs; 6307 const VectorType *VTy = Ty->getAs<VectorType>(); 6308 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6309 6310 // '(...)' form of vector initialization in AltiVec: the number of 6311 // initializers must be one or must match the size of the vector. 6312 // If a single value is specified in the initializer then it will be 6313 // replicated to all the components of the vector 6314 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6315 // The number of initializers must be one or must match the size of the 6316 // vector. If a single value is specified in the initializer then it will 6317 // be replicated to all the components of the vector 6318 if (numExprs == 1) { 6319 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6320 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6321 if (Literal.isInvalid()) 6322 return ExprError(); 6323 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6324 PrepareScalarCast(Literal, ElemTy)); 6325 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6326 } 6327 else if (numExprs < numElems) { 6328 Diag(E->getExprLoc(), 6329 diag::err_incorrect_number_of_vector_initializers); 6330 return ExprError(); 6331 } 6332 else 6333 initExprs.append(exprs, exprs + numExprs); 6334 } 6335 else { 6336 // For OpenCL, when the number of initializers is a single value, 6337 // it will be replicated to all components of the vector. 6338 if (getLangOpts().OpenCL && 6339 VTy->getVectorKind() == VectorType::GenericVector && 6340 numExprs == 1) { 6341 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6342 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6343 if (Literal.isInvalid()) 6344 return ExprError(); 6345 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6346 PrepareScalarCast(Literal, ElemTy)); 6347 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6348 } 6349 6350 initExprs.append(exprs, exprs + numExprs); 6351 } 6352 // FIXME: This means that pretty-printing the final AST will produce curly 6353 // braces instead of the original commas. 6354 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6355 initExprs, LiteralRParenLoc); 6356 initE->setType(Ty); 6357 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6358 } 6359 6360 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6361 /// the ParenListExpr into a sequence of comma binary operators. 6362 ExprResult 6363 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6364 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6365 if (!E) 6366 return OrigExpr; 6367 6368 ExprResult Result(E->getExpr(0)); 6369 6370 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6371 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6372 E->getExpr(i)); 6373 6374 if (Result.isInvalid()) return ExprError(); 6375 6376 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6377 } 6378 6379 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6380 SourceLocation R, 6381 MultiExprArg Val) { 6382 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6383 return expr; 6384 } 6385 6386 /// Emit a specialized diagnostic when one expression is a null pointer 6387 /// constant and the other is not a pointer. Returns true if a diagnostic is 6388 /// emitted. 6389 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6390 SourceLocation QuestionLoc) { 6391 Expr *NullExpr = LHSExpr; 6392 Expr *NonPointerExpr = RHSExpr; 6393 Expr::NullPointerConstantKind NullKind = 6394 NullExpr->isNullPointerConstant(Context, 6395 Expr::NPC_ValueDependentIsNotNull); 6396 6397 if (NullKind == Expr::NPCK_NotNull) { 6398 NullExpr = RHSExpr; 6399 NonPointerExpr = LHSExpr; 6400 NullKind = 6401 NullExpr->isNullPointerConstant(Context, 6402 Expr::NPC_ValueDependentIsNotNull); 6403 } 6404 6405 if (NullKind == Expr::NPCK_NotNull) 6406 return false; 6407 6408 if (NullKind == Expr::NPCK_ZeroExpression) 6409 return false; 6410 6411 if (NullKind == Expr::NPCK_ZeroLiteral) { 6412 // In this case, check to make sure that we got here from a "NULL" 6413 // string in the source code. 6414 NullExpr = NullExpr->IgnoreParenImpCasts(); 6415 SourceLocation loc = NullExpr->getExprLoc(); 6416 if (!findMacroSpelling(loc, "NULL")) 6417 return false; 6418 } 6419 6420 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6421 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6422 << NonPointerExpr->getType() << DiagType 6423 << NonPointerExpr->getSourceRange(); 6424 return true; 6425 } 6426 6427 /// Return false if the condition expression is valid, true otherwise. 6428 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6429 QualType CondTy = Cond->getType(); 6430 6431 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6432 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6433 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6434 << CondTy << Cond->getSourceRange(); 6435 return true; 6436 } 6437 6438 // C99 6.5.15p2 6439 if (CondTy->isScalarType()) return false; 6440 6441 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6442 << CondTy << Cond->getSourceRange(); 6443 return true; 6444 } 6445 6446 /// Handle when one or both operands are void type. 6447 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6448 ExprResult &RHS) { 6449 Expr *LHSExpr = LHS.get(); 6450 Expr *RHSExpr = RHS.get(); 6451 6452 if (!LHSExpr->getType()->isVoidType()) 6453 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6454 << RHSExpr->getSourceRange(); 6455 if (!RHSExpr->getType()->isVoidType()) 6456 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6457 << LHSExpr->getSourceRange(); 6458 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6459 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6460 return S.Context.VoidTy; 6461 } 6462 6463 /// Return false if the NullExpr can be promoted to PointerTy, 6464 /// true otherwise. 6465 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6466 QualType PointerTy) { 6467 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6468 !NullExpr.get()->isNullPointerConstant(S.Context, 6469 Expr::NPC_ValueDependentIsNull)) 6470 return true; 6471 6472 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6473 return false; 6474 } 6475 6476 /// Checks compatibility between two pointers and return the resulting 6477 /// type. 6478 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6479 ExprResult &RHS, 6480 SourceLocation Loc) { 6481 QualType LHSTy = LHS.get()->getType(); 6482 QualType RHSTy = RHS.get()->getType(); 6483 6484 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6485 // Two identical pointers types are always compatible. 6486 return LHSTy; 6487 } 6488 6489 QualType lhptee, rhptee; 6490 6491 // Get the pointee types. 6492 bool IsBlockPointer = false; 6493 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6494 lhptee = LHSBTy->getPointeeType(); 6495 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6496 IsBlockPointer = true; 6497 } else { 6498 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6499 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6500 } 6501 6502 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6503 // differently qualified versions of compatible types, the result type is 6504 // a pointer to an appropriately qualified version of the composite 6505 // type. 6506 6507 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6508 // clause doesn't make sense for our extensions. E.g. address space 2 should 6509 // be incompatible with address space 3: they may live on different devices or 6510 // anything. 6511 Qualifiers lhQual = lhptee.getQualifiers(); 6512 Qualifiers rhQual = rhptee.getQualifiers(); 6513 6514 LangAS ResultAddrSpace = LangAS::Default; 6515 LangAS LAddrSpace = lhQual.getAddressSpace(); 6516 LangAS RAddrSpace = rhQual.getAddressSpace(); 6517 6518 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6519 // spaces is disallowed. 6520 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6521 ResultAddrSpace = LAddrSpace; 6522 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6523 ResultAddrSpace = RAddrSpace; 6524 else { 6525 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6526 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6527 << RHS.get()->getSourceRange(); 6528 return QualType(); 6529 } 6530 6531 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6532 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6533 lhQual.removeCVRQualifiers(); 6534 rhQual.removeCVRQualifiers(); 6535 6536 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6537 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6538 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6539 // qual types are compatible iff 6540 // * corresponded types are compatible 6541 // * CVR qualifiers are equal 6542 // * address spaces are equal 6543 // Thus for conditional operator we merge CVR and address space unqualified 6544 // pointees and if there is a composite type we return a pointer to it with 6545 // merged qualifiers. 6546 LHSCastKind = 6547 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6548 RHSCastKind = 6549 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6550 lhQual.removeAddressSpace(); 6551 rhQual.removeAddressSpace(); 6552 6553 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6554 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6555 6556 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6557 6558 if (CompositeTy.isNull()) { 6559 // In this situation, we assume void* type. No especially good 6560 // reason, but this is what gcc does, and we do have to pick 6561 // to get a consistent AST. 6562 QualType incompatTy; 6563 incompatTy = S.Context.getPointerType( 6564 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6565 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6566 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6567 6568 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6569 // for casts between types with incompatible address space qualifiers. 6570 // For the following code the compiler produces casts between global and 6571 // local address spaces of the corresponded innermost pointees: 6572 // local int *global *a; 6573 // global int *global *b; 6574 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6575 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6576 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6577 << RHS.get()->getSourceRange(); 6578 6579 return incompatTy; 6580 } 6581 6582 // The pointer types are compatible. 6583 // In case of OpenCL ResultTy should have the address space qualifier 6584 // which is a superset of address spaces of both the 2nd and the 3rd 6585 // operands of the conditional operator. 6586 QualType ResultTy = [&, ResultAddrSpace]() { 6587 if (S.getLangOpts().OpenCL) { 6588 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6589 CompositeQuals.setAddressSpace(ResultAddrSpace); 6590 return S.Context 6591 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6592 .withCVRQualifiers(MergedCVRQual); 6593 } 6594 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6595 }(); 6596 if (IsBlockPointer) 6597 ResultTy = S.Context.getBlockPointerType(ResultTy); 6598 else 6599 ResultTy = S.Context.getPointerType(ResultTy); 6600 6601 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6602 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6603 return ResultTy; 6604 } 6605 6606 /// Return the resulting type when the operands are both block pointers. 6607 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6608 ExprResult &LHS, 6609 ExprResult &RHS, 6610 SourceLocation Loc) { 6611 QualType LHSTy = LHS.get()->getType(); 6612 QualType RHSTy = RHS.get()->getType(); 6613 6614 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6615 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6616 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6617 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6618 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6619 return destType; 6620 } 6621 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6622 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6623 << RHS.get()->getSourceRange(); 6624 return QualType(); 6625 } 6626 6627 // We have 2 block pointer types. 6628 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6629 } 6630 6631 /// Return the resulting type when the operands are both pointers. 6632 static QualType 6633 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6634 ExprResult &RHS, 6635 SourceLocation Loc) { 6636 // get the pointer types 6637 QualType LHSTy = LHS.get()->getType(); 6638 QualType RHSTy = RHS.get()->getType(); 6639 6640 // get the "pointed to" types 6641 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6642 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6643 6644 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6645 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6646 // Figure out necessary qualifiers (C99 6.5.15p6) 6647 QualType destPointee 6648 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6649 QualType destType = S.Context.getPointerType(destPointee); 6650 // Add qualifiers if necessary. 6651 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6652 // Promote to void*. 6653 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6654 return destType; 6655 } 6656 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6657 QualType destPointee 6658 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6659 QualType destType = S.Context.getPointerType(destPointee); 6660 // Add qualifiers if necessary. 6661 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6662 // Promote to void*. 6663 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6664 return destType; 6665 } 6666 6667 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6668 } 6669 6670 /// Return false if the first expression is not an integer and the second 6671 /// expression is not a pointer, true otherwise. 6672 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6673 Expr* PointerExpr, SourceLocation Loc, 6674 bool IsIntFirstExpr) { 6675 if (!PointerExpr->getType()->isPointerType() || 6676 !Int.get()->getType()->isIntegerType()) 6677 return false; 6678 6679 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6680 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6681 6682 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6683 << Expr1->getType() << Expr2->getType() 6684 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6685 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6686 CK_IntegralToPointer); 6687 return true; 6688 } 6689 6690 /// Simple conversion between integer and floating point types. 6691 /// 6692 /// Used when handling the OpenCL conditional operator where the 6693 /// condition is a vector while the other operands are scalar. 6694 /// 6695 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6696 /// types are either integer or floating type. Between the two 6697 /// operands, the type with the higher rank is defined as the "result 6698 /// type". The other operand needs to be promoted to the same type. No 6699 /// other type promotion is allowed. We cannot use 6700 /// UsualArithmeticConversions() for this purpose, since it always 6701 /// promotes promotable types. 6702 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6703 ExprResult &RHS, 6704 SourceLocation QuestionLoc) { 6705 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6706 if (LHS.isInvalid()) 6707 return QualType(); 6708 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6709 if (RHS.isInvalid()) 6710 return QualType(); 6711 6712 // For conversion purposes, we ignore any qualifiers. 6713 // For example, "const float" and "float" are equivalent. 6714 QualType LHSType = 6715 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6716 QualType RHSType = 6717 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6718 6719 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6720 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6721 << LHSType << LHS.get()->getSourceRange(); 6722 return QualType(); 6723 } 6724 6725 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6726 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6727 << RHSType << RHS.get()->getSourceRange(); 6728 return QualType(); 6729 } 6730 6731 // If both types are identical, no conversion is needed. 6732 if (LHSType == RHSType) 6733 return LHSType; 6734 6735 // Now handle "real" floating types (i.e. float, double, long double). 6736 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6737 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6738 /*IsCompAssign = */ false); 6739 6740 // Finally, we have two differing integer types. 6741 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6742 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6743 } 6744 6745 /// Convert scalar operands to a vector that matches the 6746 /// condition in length. 6747 /// 6748 /// Used when handling the OpenCL conditional operator where the 6749 /// condition is a vector while the other operands are scalar. 6750 /// 6751 /// We first compute the "result type" for the scalar operands 6752 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6753 /// into a vector of that type where the length matches the condition 6754 /// vector type. s6.11.6 requires that the element types of the result 6755 /// and the condition must have the same number of bits. 6756 static QualType 6757 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6758 QualType CondTy, SourceLocation QuestionLoc) { 6759 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6760 if (ResTy.isNull()) return QualType(); 6761 6762 const VectorType *CV = CondTy->getAs<VectorType>(); 6763 assert(CV); 6764 6765 // Determine the vector result type 6766 unsigned NumElements = CV->getNumElements(); 6767 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6768 6769 // Ensure that all types have the same number of bits 6770 if (S.Context.getTypeSize(CV->getElementType()) 6771 != S.Context.getTypeSize(ResTy)) { 6772 // Since VectorTy is created internally, it does not pretty print 6773 // with an OpenCL name. Instead, we just print a description. 6774 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6775 SmallString<64> Str; 6776 llvm::raw_svector_ostream OS(Str); 6777 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6778 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6779 << CondTy << OS.str(); 6780 return QualType(); 6781 } 6782 6783 // Convert operands to the vector result type 6784 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6785 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6786 6787 return VectorTy; 6788 } 6789 6790 /// Return false if this is a valid OpenCL condition vector 6791 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6792 SourceLocation QuestionLoc) { 6793 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6794 // integral type. 6795 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6796 assert(CondTy); 6797 QualType EleTy = CondTy->getElementType(); 6798 if (EleTy->isIntegerType()) return false; 6799 6800 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6801 << Cond->getType() << Cond->getSourceRange(); 6802 return true; 6803 } 6804 6805 /// Return false if the vector condition type and the vector 6806 /// result type are compatible. 6807 /// 6808 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6809 /// number of elements, and their element types have the same number 6810 /// of bits. 6811 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6812 SourceLocation QuestionLoc) { 6813 const VectorType *CV = CondTy->getAs<VectorType>(); 6814 const VectorType *RV = VecResTy->getAs<VectorType>(); 6815 assert(CV && RV); 6816 6817 if (CV->getNumElements() != RV->getNumElements()) { 6818 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6819 << CondTy << VecResTy; 6820 return true; 6821 } 6822 6823 QualType CVE = CV->getElementType(); 6824 QualType RVE = RV->getElementType(); 6825 6826 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6827 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6828 << CondTy << VecResTy; 6829 return true; 6830 } 6831 6832 return false; 6833 } 6834 6835 /// Return the resulting type for the conditional operator in 6836 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6837 /// s6.3.i) when the condition is a vector type. 6838 static QualType 6839 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6840 ExprResult &LHS, ExprResult &RHS, 6841 SourceLocation QuestionLoc) { 6842 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6843 if (Cond.isInvalid()) 6844 return QualType(); 6845 QualType CondTy = Cond.get()->getType(); 6846 6847 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6848 return QualType(); 6849 6850 // If either operand is a vector then find the vector type of the 6851 // result as specified in OpenCL v1.1 s6.3.i. 6852 if (LHS.get()->getType()->isVectorType() || 6853 RHS.get()->getType()->isVectorType()) { 6854 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6855 /*isCompAssign*/false, 6856 /*AllowBothBool*/true, 6857 /*AllowBoolConversions*/false); 6858 if (VecResTy.isNull()) return QualType(); 6859 // The result type must match the condition type as specified in 6860 // OpenCL v1.1 s6.11.6. 6861 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6862 return QualType(); 6863 return VecResTy; 6864 } 6865 6866 // Both operands are scalar. 6867 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6868 } 6869 6870 /// Return true if the Expr is block type 6871 static bool checkBlockType(Sema &S, const Expr *E) { 6872 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6873 QualType Ty = CE->getCallee()->getType(); 6874 if (Ty->isBlockPointerType()) { 6875 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6876 return true; 6877 } 6878 } 6879 return false; 6880 } 6881 6882 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6883 /// In that case, LHS = cond. 6884 /// C99 6.5.15 6885 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6886 ExprResult &RHS, ExprValueKind &VK, 6887 ExprObjectKind &OK, 6888 SourceLocation QuestionLoc) { 6889 6890 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6891 if (!LHSResult.isUsable()) return QualType(); 6892 LHS = LHSResult; 6893 6894 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6895 if (!RHSResult.isUsable()) return QualType(); 6896 RHS = RHSResult; 6897 6898 // C++ is sufficiently different to merit its own checker. 6899 if (getLangOpts().CPlusPlus) 6900 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6901 6902 VK = VK_RValue; 6903 OK = OK_Ordinary; 6904 6905 // The OpenCL operator with a vector condition is sufficiently 6906 // different to merit its own checker. 6907 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6908 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6909 6910 // First, check the condition. 6911 Cond = UsualUnaryConversions(Cond.get()); 6912 if (Cond.isInvalid()) 6913 return QualType(); 6914 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6915 return QualType(); 6916 6917 // Now check the two expressions. 6918 if (LHS.get()->getType()->isVectorType() || 6919 RHS.get()->getType()->isVectorType()) 6920 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6921 /*AllowBothBool*/true, 6922 /*AllowBoolConversions*/false); 6923 6924 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6925 if (LHS.isInvalid() || RHS.isInvalid()) 6926 return QualType(); 6927 6928 QualType LHSTy = LHS.get()->getType(); 6929 QualType RHSTy = RHS.get()->getType(); 6930 6931 // Diagnose attempts to convert between __float128 and long double where 6932 // such conversions currently can't be handled. 6933 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6934 Diag(QuestionLoc, 6935 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6937 return QualType(); 6938 } 6939 6940 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6941 // selection operator (?:). 6942 if (getLangOpts().OpenCL && 6943 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6944 return QualType(); 6945 } 6946 6947 // If both operands have arithmetic type, do the usual arithmetic conversions 6948 // to find a common type: C99 6.5.15p3,5. 6949 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6950 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6951 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6952 6953 return ResTy; 6954 } 6955 6956 // If both operands are the same structure or union type, the result is that 6957 // type. 6958 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6959 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6960 if (LHSRT->getDecl() == RHSRT->getDecl()) 6961 // "If both the operands have structure or union type, the result has 6962 // that type." This implies that CV qualifiers are dropped. 6963 return LHSTy.getUnqualifiedType(); 6964 // FIXME: Type of conditional expression must be complete in C mode. 6965 } 6966 6967 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6968 // The following || allows only one side to be void (a GCC-ism). 6969 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6970 return checkConditionalVoidType(*this, LHS, RHS); 6971 } 6972 6973 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6974 // the type of the other operand." 6975 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6976 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6977 6978 // All objective-c pointer type analysis is done here. 6979 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6980 QuestionLoc); 6981 if (LHS.isInvalid() || RHS.isInvalid()) 6982 return QualType(); 6983 if (!compositeType.isNull()) 6984 return compositeType; 6985 6986 6987 // Handle block pointer types. 6988 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6989 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6990 QuestionLoc); 6991 6992 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6993 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6994 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6995 QuestionLoc); 6996 6997 // GCC compatibility: soften pointer/integer mismatch. Note that 6998 // null pointers have been filtered out by this point. 6999 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7000 /*isIntFirstExpr=*/true)) 7001 return RHSTy; 7002 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7003 /*isIntFirstExpr=*/false)) 7004 return LHSTy; 7005 7006 // Emit a better diagnostic if one of the expressions is a null pointer 7007 // constant and the other is not a pointer type. In this case, the user most 7008 // likely forgot to take the address of the other expression. 7009 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7010 return QualType(); 7011 7012 // Otherwise, the operands are not compatible. 7013 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7014 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7015 << RHS.get()->getSourceRange(); 7016 return QualType(); 7017 } 7018 7019 /// FindCompositeObjCPointerType - Helper method to find composite type of 7020 /// two objective-c pointer types of the two input expressions. 7021 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7022 SourceLocation QuestionLoc) { 7023 QualType LHSTy = LHS.get()->getType(); 7024 QualType RHSTy = RHS.get()->getType(); 7025 7026 // Handle things like Class and struct objc_class*. Here we case the result 7027 // to the pseudo-builtin, because that will be implicitly cast back to the 7028 // redefinition type if an attempt is made to access its fields. 7029 if (LHSTy->isObjCClassType() && 7030 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7031 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7032 return LHSTy; 7033 } 7034 if (RHSTy->isObjCClassType() && 7035 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7036 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7037 return RHSTy; 7038 } 7039 // And the same for struct objc_object* / id 7040 if (LHSTy->isObjCIdType() && 7041 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7042 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7043 return LHSTy; 7044 } 7045 if (RHSTy->isObjCIdType() && 7046 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7047 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7048 return RHSTy; 7049 } 7050 // And the same for struct objc_selector* / SEL 7051 if (Context.isObjCSelType(LHSTy) && 7052 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7053 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7054 return LHSTy; 7055 } 7056 if (Context.isObjCSelType(RHSTy) && 7057 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7058 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7059 return RHSTy; 7060 } 7061 // Check constraints for Objective-C object pointers types. 7062 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7063 7064 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7065 // Two identical object pointer types are always compatible. 7066 return LHSTy; 7067 } 7068 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7069 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7070 QualType compositeType = LHSTy; 7071 7072 // If both operands are interfaces and either operand can be 7073 // assigned to the other, use that type as the composite 7074 // type. This allows 7075 // xxx ? (A*) a : (B*) b 7076 // where B is a subclass of A. 7077 // 7078 // Additionally, as for assignment, if either type is 'id' 7079 // allow silent coercion. Finally, if the types are 7080 // incompatible then make sure to use 'id' as the composite 7081 // type so the result is acceptable for sending messages to. 7082 7083 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7084 // It could return the composite type. 7085 if (!(compositeType = 7086 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7087 // Nothing more to do. 7088 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7089 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7090 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7091 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7092 } else if ((LHSTy->isObjCQualifiedIdType() || 7093 RHSTy->isObjCQualifiedIdType()) && 7094 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7095 // Need to handle "id<xx>" explicitly. 7096 // GCC allows qualified id and any Objective-C type to devolve to 7097 // id. Currently localizing to here until clear this should be 7098 // part of ObjCQualifiedIdTypesAreCompatible. 7099 compositeType = Context.getObjCIdType(); 7100 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7101 compositeType = Context.getObjCIdType(); 7102 } else { 7103 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7104 << LHSTy << RHSTy 7105 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7106 QualType incompatTy = Context.getObjCIdType(); 7107 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7108 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7109 return incompatTy; 7110 } 7111 // The object pointer types are compatible. 7112 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7113 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7114 return compositeType; 7115 } 7116 // Check Objective-C object pointer types and 'void *' 7117 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7118 if (getLangOpts().ObjCAutoRefCount) { 7119 // ARC forbids the implicit conversion of object pointers to 'void *', 7120 // so these types are not compatible. 7121 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7122 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7123 LHS = RHS = true; 7124 return QualType(); 7125 } 7126 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7127 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7128 QualType destPointee 7129 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7130 QualType destType = Context.getPointerType(destPointee); 7131 // Add qualifiers if necessary. 7132 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7133 // Promote to void*. 7134 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7135 return destType; 7136 } 7137 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7138 if (getLangOpts().ObjCAutoRefCount) { 7139 // ARC forbids the implicit conversion of object pointers to 'void *', 7140 // so these types are not compatible. 7141 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7142 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7143 LHS = RHS = true; 7144 return QualType(); 7145 } 7146 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7147 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7148 QualType destPointee 7149 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7150 QualType destType = Context.getPointerType(destPointee); 7151 // Add qualifiers if necessary. 7152 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7153 // Promote to void*. 7154 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7155 return destType; 7156 } 7157 return QualType(); 7158 } 7159 7160 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7161 /// ParenRange in parentheses. 7162 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7163 const PartialDiagnostic &Note, 7164 SourceRange ParenRange) { 7165 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7166 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7167 EndLoc.isValid()) { 7168 Self.Diag(Loc, Note) 7169 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7170 << FixItHint::CreateInsertion(EndLoc, ")"); 7171 } else { 7172 // We can't display the parentheses, so just show the bare note. 7173 Self.Diag(Loc, Note) << ParenRange; 7174 } 7175 } 7176 7177 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7178 return BinaryOperator::isAdditiveOp(Opc) || 7179 BinaryOperator::isMultiplicativeOp(Opc) || 7180 BinaryOperator::isShiftOp(Opc); 7181 } 7182 7183 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7184 /// expression, either using a built-in or overloaded operator, 7185 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7186 /// expression. 7187 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7188 Expr **RHSExprs) { 7189 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7190 E = E->IgnoreImpCasts(); 7191 E = E->IgnoreConversionOperator(); 7192 E = E->IgnoreImpCasts(); 7193 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7194 E = MTE->GetTemporaryExpr(); 7195 E = E->IgnoreImpCasts(); 7196 } 7197 7198 // Built-in binary operator. 7199 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7200 if (IsArithmeticOp(OP->getOpcode())) { 7201 *Opcode = OP->getOpcode(); 7202 *RHSExprs = OP->getRHS(); 7203 return true; 7204 } 7205 } 7206 7207 // Overloaded operator. 7208 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7209 if (Call->getNumArgs() != 2) 7210 return false; 7211 7212 // Make sure this is really a binary operator that is safe to pass into 7213 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7214 OverloadedOperatorKind OO = Call->getOperator(); 7215 if (OO < OO_Plus || OO > OO_Arrow || 7216 OO == OO_PlusPlus || OO == OO_MinusMinus) 7217 return false; 7218 7219 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7220 if (IsArithmeticOp(OpKind)) { 7221 *Opcode = OpKind; 7222 *RHSExprs = Call->getArg(1); 7223 return true; 7224 } 7225 } 7226 7227 return false; 7228 } 7229 7230 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7231 /// or is a logical expression such as (x==y) which has int type, but is 7232 /// commonly interpreted as boolean. 7233 static bool ExprLooksBoolean(Expr *E) { 7234 E = E->IgnoreParenImpCasts(); 7235 7236 if (E->getType()->isBooleanType()) 7237 return true; 7238 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7239 return OP->isComparisonOp() || OP->isLogicalOp(); 7240 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7241 return OP->getOpcode() == UO_LNot; 7242 if (E->getType()->isPointerType()) 7243 return true; 7244 // FIXME: What about overloaded operator calls returning "unspecified boolean 7245 // type"s (commonly pointer-to-members)? 7246 7247 return false; 7248 } 7249 7250 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7251 /// and binary operator are mixed in a way that suggests the programmer assumed 7252 /// the conditional operator has higher precedence, for example: 7253 /// "int x = a + someBinaryCondition ? 1 : 2". 7254 static void DiagnoseConditionalPrecedence(Sema &Self, 7255 SourceLocation OpLoc, 7256 Expr *Condition, 7257 Expr *LHSExpr, 7258 Expr *RHSExpr) { 7259 BinaryOperatorKind CondOpcode; 7260 Expr *CondRHS; 7261 7262 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7263 return; 7264 if (!ExprLooksBoolean(CondRHS)) 7265 return; 7266 7267 // The condition is an arithmetic binary expression, with a right- 7268 // hand side that looks boolean, so warn. 7269 7270 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7271 << Condition->getSourceRange() 7272 << BinaryOperator::getOpcodeStr(CondOpcode); 7273 7274 SuggestParentheses( 7275 Self, OpLoc, 7276 Self.PDiag(diag::note_precedence_silence) 7277 << BinaryOperator::getOpcodeStr(CondOpcode), 7278 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7279 7280 SuggestParentheses(Self, OpLoc, 7281 Self.PDiag(diag::note_precedence_conditional_first), 7282 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7283 } 7284 7285 /// Compute the nullability of a conditional expression. 7286 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7287 QualType LHSTy, QualType RHSTy, 7288 ASTContext &Ctx) { 7289 if (!ResTy->isAnyPointerType()) 7290 return ResTy; 7291 7292 auto GetNullability = [&Ctx](QualType Ty) { 7293 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7294 if (Kind) 7295 return *Kind; 7296 return NullabilityKind::Unspecified; 7297 }; 7298 7299 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7300 NullabilityKind MergedKind; 7301 7302 // Compute nullability of a binary conditional expression. 7303 if (IsBin) { 7304 if (LHSKind == NullabilityKind::NonNull) 7305 MergedKind = NullabilityKind::NonNull; 7306 else 7307 MergedKind = RHSKind; 7308 // Compute nullability of a normal conditional expression. 7309 } else { 7310 if (LHSKind == NullabilityKind::Nullable || 7311 RHSKind == NullabilityKind::Nullable) 7312 MergedKind = NullabilityKind::Nullable; 7313 else if (LHSKind == NullabilityKind::NonNull) 7314 MergedKind = RHSKind; 7315 else if (RHSKind == NullabilityKind::NonNull) 7316 MergedKind = LHSKind; 7317 else 7318 MergedKind = NullabilityKind::Unspecified; 7319 } 7320 7321 // Return if ResTy already has the correct nullability. 7322 if (GetNullability(ResTy) == MergedKind) 7323 return ResTy; 7324 7325 // Strip all nullability from ResTy. 7326 while (ResTy->getNullability(Ctx)) 7327 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7328 7329 // Create a new AttributedType with the new nullability kind. 7330 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7331 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7332 } 7333 7334 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7335 /// in the case of a the GNU conditional expr extension. 7336 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7337 SourceLocation ColonLoc, 7338 Expr *CondExpr, Expr *LHSExpr, 7339 Expr *RHSExpr) { 7340 if (!getLangOpts().CPlusPlus) { 7341 // C cannot handle TypoExpr nodes in the condition because it 7342 // doesn't handle dependent types properly, so make sure any TypoExprs have 7343 // been dealt with before checking the operands. 7344 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7345 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7346 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7347 7348 if (!CondResult.isUsable()) 7349 return ExprError(); 7350 7351 if (LHSExpr) { 7352 if (!LHSResult.isUsable()) 7353 return ExprError(); 7354 } 7355 7356 if (!RHSResult.isUsable()) 7357 return ExprError(); 7358 7359 CondExpr = CondResult.get(); 7360 LHSExpr = LHSResult.get(); 7361 RHSExpr = RHSResult.get(); 7362 } 7363 7364 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7365 // was the condition. 7366 OpaqueValueExpr *opaqueValue = nullptr; 7367 Expr *commonExpr = nullptr; 7368 if (!LHSExpr) { 7369 commonExpr = CondExpr; 7370 // Lower out placeholder types first. This is important so that we don't 7371 // try to capture a placeholder. This happens in few cases in C++; such 7372 // as Objective-C++'s dictionary subscripting syntax. 7373 if (commonExpr->hasPlaceholderType()) { 7374 ExprResult result = CheckPlaceholderExpr(commonExpr); 7375 if (!result.isUsable()) return ExprError(); 7376 commonExpr = result.get(); 7377 } 7378 // We usually want to apply unary conversions *before* saving, except 7379 // in the special case of a C++ l-value conditional. 7380 if (!(getLangOpts().CPlusPlus 7381 && !commonExpr->isTypeDependent() 7382 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7383 && commonExpr->isGLValue() 7384 && commonExpr->isOrdinaryOrBitFieldObject() 7385 && RHSExpr->isOrdinaryOrBitFieldObject() 7386 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7387 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7388 if (commonRes.isInvalid()) 7389 return ExprError(); 7390 commonExpr = commonRes.get(); 7391 } 7392 7393 // If the common expression is a class or array prvalue, materialize it 7394 // so that we can safely refer to it multiple times. 7395 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7396 commonExpr->getType()->isArrayType())) { 7397 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7398 if (MatExpr.isInvalid()) 7399 return ExprError(); 7400 commonExpr = MatExpr.get(); 7401 } 7402 7403 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7404 commonExpr->getType(), 7405 commonExpr->getValueKind(), 7406 commonExpr->getObjectKind(), 7407 commonExpr); 7408 LHSExpr = CondExpr = opaqueValue; 7409 } 7410 7411 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7412 ExprValueKind VK = VK_RValue; 7413 ExprObjectKind OK = OK_Ordinary; 7414 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7415 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7416 VK, OK, QuestionLoc); 7417 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7418 RHS.isInvalid()) 7419 return ExprError(); 7420 7421 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7422 RHS.get()); 7423 7424 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7425 7426 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7427 Context); 7428 7429 if (!commonExpr) 7430 return new (Context) 7431 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7432 RHS.get(), result, VK, OK); 7433 7434 return new (Context) BinaryConditionalOperator( 7435 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7436 ColonLoc, result, VK, OK); 7437 } 7438 7439 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7440 // being closely modeled after the C99 spec:-). The odd characteristic of this 7441 // routine is it effectively iqnores the qualifiers on the top level pointee. 7442 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7443 // FIXME: add a couple examples in this comment. 7444 static Sema::AssignConvertType 7445 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7446 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7447 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7448 7449 // get the "pointed to" type (ignoring qualifiers at the top level) 7450 const Type *lhptee, *rhptee; 7451 Qualifiers lhq, rhq; 7452 std::tie(lhptee, lhq) = 7453 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7454 std::tie(rhptee, rhq) = 7455 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7456 7457 Sema::AssignConvertType ConvTy = Sema::Compatible; 7458 7459 // C99 6.5.16.1p1: This following citation is common to constraints 7460 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7461 // qualifiers of the type *pointed to* by the right; 7462 7463 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7464 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7465 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7466 // Ignore lifetime for further calculation. 7467 lhq.removeObjCLifetime(); 7468 rhq.removeObjCLifetime(); 7469 } 7470 7471 if (!lhq.compatiblyIncludes(rhq)) { 7472 // Treat address-space mismatches as fatal. TODO: address subspaces 7473 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7474 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7475 7476 // It's okay to add or remove GC or lifetime qualifiers when converting to 7477 // and from void*. 7478 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7479 .compatiblyIncludes( 7480 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7481 && (lhptee->isVoidType() || rhptee->isVoidType())) 7482 ; // keep old 7483 7484 // Treat lifetime mismatches as fatal. 7485 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7486 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7487 7488 // For GCC/MS compatibility, other qualifier mismatches are treated 7489 // as still compatible in C. 7490 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7491 } 7492 7493 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7494 // incomplete type and the other is a pointer to a qualified or unqualified 7495 // version of void... 7496 if (lhptee->isVoidType()) { 7497 if (rhptee->isIncompleteOrObjectType()) 7498 return ConvTy; 7499 7500 // As an extension, we allow cast to/from void* to function pointer. 7501 assert(rhptee->isFunctionType()); 7502 return Sema::FunctionVoidPointer; 7503 } 7504 7505 if (rhptee->isVoidType()) { 7506 if (lhptee->isIncompleteOrObjectType()) 7507 return ConvTy; 7508 7509 // As an extension, we allow cast to/from void* to function pointer. 7510 assert(lhptee->isFunctionType()); 7511 return Sema::FunctionVoidPointer; 7512 } 7513 7514 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7515 // unqualified versions of compatible types, ... 7516 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7517 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7518 // Check if the pointee types are compatible ignoring the sign. 7519 // We explicitly check for char so that we catch "char" vs 7520 // "unsigned char" on systems where "char" is unsigned. 7521 if (lhptee->isCharType()) 7522 ltrans = S.Context.UnsignedCharTy; 7523 else if (lhptee->hasSignedIntegerRepresentation()) 7524 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7525 7526 if (rhptee->isCharType()) 7527 rtrans = S.Context.UnsignedCharTy; 7528 else if (rhptee->hasSignedIntegerRepresentation()) 7529 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7530 7531 if (ltrans == rtrans) { 7532 // Types are compatible ignoring the sign. Qualifier incompatibility 7533 // takes priority over sign incompatibility because the sign 7534 // warning can be disabled. 7535 if (ConvTy != Sema::Compatible) 7536 return ConvTy; 7537 7538 return Sema::IncompatiblePointerSign; 7539 } 7540 7541 // If we are a multi-level pointer, it's possible that our issue is simply 7542 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7543 // the eventual target type is the same and the pointers have the same 7544 // level of indirection, this must be the issue. 7545 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7546 do { 7547 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7548 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7549 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7550 7551 if (lhptee == rhptee) 7552 return Sema::IncompatibleNestedPointerQualifiers; 7553 } 7554 7555 // General pointer incompatibility takes priority over qualifiers. 7556 return Sema::IncompatiblePointer; 7557 } 7558 if (!S.getLangOpts().CPlusPlus && 7559 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7560 return Sema::IncompatiblePointer; 7561 return ConvTy; 7562 } 7563 7564 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7565 /// block pointer types are compatible or whether a block and normal pointer 7566 /// are compatible. It is more restrict than comparing two function pointer 7567 // types. 7568 static Sema::AssignConvertType 7569 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7570 QualType RHSType) { 7571 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7572 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7573 7574 QualType lhptee, rhptee; 7575 7576 // get the "pointed to" type (ignoring qualifiers at the top level) 7577 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7578 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7579 7580 // In C++, the types have to match exactly. 7581 if (S.getLangOpts().CPlusPlus) 7582 return Sema::IncompatibleBlockPointer; 7583 7584 Sema::AssignConvertType ConvTy = Sema::Compatible; 7585 7586 // For blocks we enforce that qualifiers are identical. 7587 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7588 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7589 if (S.getLangOpts().OpenCL) { 7590 LQuals.removeAddressSpace(); 7591 RQuals.removeAddressSpace(); 7592 } 7593 if (LQuals != RQuals) 7594 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7595 7596 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7597 // assignment. 7598 // The current behavior is similar to C++ lambdas. A block might be 7599 // assigned to a variable iff its return type and parameters are compatible 7600 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7601 // an assignment. Presumably it should behave in way that a function pointer 7602 // assignment does in C, so for each parameter and return type: 7603 // * CVR and address space of LHS should be a superset of CVR and address 7604 // space of RHS. 7605 // * unqualified types should be compatible. 7606 if (S.getLangOpts().OpenCL) { 7607 if (!S.Context.typesAreBlockPointerCompatible( 7608 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7609 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7610 return Sema::IncompatibleBlockPointer; 7611 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7612 return Sema::IncompatibleBlockPointer; 7613 7614 return ConvTy; 7615 } 7616 7617 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7618 /// for assignment compatibility. 7619 static Sema::AssignConvertType 7620 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7621 QualType RHSType) { 7622 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7623 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7624 7625 if (LHSType->isObjCBuiltinType()) { 7626 // Class is not compatible with ObjC object pointers. 7627 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7628 !RHSType->isObjCQualifiedClassType()) 7629 return Sema::IncompatiblePointer; 7630 return Sema::Compatible; 7631 } 7632 if (RHSType->isObjCBuiltinType()) { 7633 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7634 !LHSType->isObjCQualifiedClassType()) 7635 return Sema::IncompatiblePointer; 7636 return Sema::Compatible; 7637 } 7638 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7639 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7640 7641 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7642 // make an exception for id<P> 7643 !LHSType->isObjCQualifiedIdType()) 7644 return Sema::CompatiblePointerDiscardsQualifiers; 7645 7646 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7647 return Sema::Compatible; 7648 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7649 return Sema::IncompatibleObjCQualifiedId; 7650 return Sema::IncompatiblePointer; 7651 } 7652 7653 Sema::AssignConvertType 7654 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7655 QualType LHSType, QualType RHSType) { 7656 // Fake up an opaque expression. We don't actually care about what 7657 // cast operations are required, so if CheckAssignmentConstraints 7658 // adds casts to this they'll be wasted, but fortunately that doesn't 7659 // usually happen on valid code. 7660 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7661 ExprResult RHSPtr = &RHSExpr; 7662 CastKind K; 7663 7664 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7665 } 7666 7667 /// This helper function returns true if QT is a vector type that has element 7668 /// type ElementType. 7669 static bool isVector(QualType QT, QualType ElementType) { 7670 if (const VectorType *VT = QT->getAs<VectorType>()) 7671 return VT->getElementType() == ElementType; 7672 return false; 7673 } 7674 7675 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7676 /// has code to accommodate several GCC extensions when type checking 7677 /// pointers. Here are some objectionable examples that GCC considers warnings: 7678 /// 7679 /// int a, *pint; 7680 /// short *pshort; 7681 /// struct foo *pfoo; 7682 /// 7683 /// pint = pshort; // warning: assignment from incompatible pointer type 7684 /// a = pint; // warning: assignment makes integer from pointer without a cast 7685 /// pint = a; // warning: assignment makes pointer from integer without a cast 7686 /// pint = pfoo; // warning: assignment from incompatible pointer type 7687 /// 7688 /// As a result, the code for dealing with pointers is more complex than the 7689 /// C99 spec dictates. 7690 /// 7691 /// Sets 'Kind' for any result kind except Incompatible. 7692 Sema::AssignConvertType 7693 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7694 CastKind &Kind, bool ConvertRHS) { 7695 QualType RHSType = RHS.get()->getType(); 7696 QualType OrigLHSType = LHSType; 7697 7698 // Get canonical types. We're not formatting these types, just comparing 7699 // them. 7700 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7701 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7702 7703 // Common case: no conversion required. 7704 if (LHSType == RHSType) { 7705 Kind = CK_NoOp; 7706 return Compatible; 7707 } 7708 7709 // If we have an atomic type, try a non-atomic assignment, then just add an 7710 // atomic qualification step. 7711 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7712 Sema::AssignConvertType result = 7713 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7714 if (result != Compatible) 7715 return result; 7716 if (Kind != CK_NoOp && ConvertRHS) 7717 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7718 Kind = CK_NonAtomicToAtomic; 7719 return Compatible; 7720 } 7721 7722 // If the left-hand side is a reference type, then we are in a 7723 // (rare!) case where we've allowed the use of references in C, 7724 // e.g., as a parameter type in a built-in function. In this case, 7725 // just make sure that the type referenced is compatible with the 7726 // right-hand side type. The caller is responsible for adjusting 7727 // LHSType so that the resulting expression does not have reference 7728 // type. 7729 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7730 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7731 Kind = CK_LValueBitCast; 7732 return Compatible; 7733 } 7734 return Incompatible; 7735 } 7736 7737 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7738 // to the same ExtVector type. 7739 if (LHSType->isExtVectorType()) { 7740 if (RHSType->isExtVectorType()) 7741 return Incompatible; 7742 if (RHSType->isArithmeticType()) { 7743 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7744 if (ConvertRHS) 7745 RHS = prepareVectorSplat(LHSType, RHS.get()); 7746 Kind = CK_VectorSplat; 7747 return Compatible; 7748 } 7749 } 7750 7751 // Conversions to or from vector type. 7752 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7753 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7754 // Allow assignments of an AltiVec vector type to an equivalent GCC 7755 // vector type and vice versa 7756 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7757 Kind = CK_BitCast; 7758 return Compatible; 7759 } 7760 7761 // If we are allowing lax vector conversions, and LHS and RHS are both 7762 // vectors, the total size only needs to be the same. This is a bitcast; 7763 // no bits are changed but the result type is different. 7764 if (isLaxVectorConversion(RHSType, LHSType)) { 7765 Kind = CK_BitCast; 7766 return IncompatibleVectors; 7767 } 7768 } 7769 7770 // When the RHS comes from another lax conversion (e.g. binops between 7771 // scalars and vectors) the result is canonicalized as a vector. When the 7772 // LHS is also a vector, the lax is allowed by the condition above. Handle 7773 // the case where LHS is a scalar. 7774 if (LHSType->isScalarType()) { 7775 const VectorType *VecType = RHSType->getAs<VectorType>(); 7776 if (VecType && VecType->getNumElements() == 1 && 7777 isLaxVectorConversion(RHSType, LHSType)) { 7778 ExprResult *VecExpr = &RHS; 7779 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7780 Kind = CK_BitCast; 7781 return Compatible; 7782 } 7783 } 7784 7785 return Incompatible; 7786 } 7787 7788 // Diagnose attempts to convert between __float128 and long double where 7789 // such conversions currently can't be handled. 7790 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7791 return Incompatible; 7792 7793 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7794 // discards the imaginary part. 7795 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7796 !LHSType->getAs<ComplexType>()) 7797 return Incompatible; 7798 7799 // Arithmetic conversions. 7800 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7801 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7802 if (ConvertRHS) 7803 Kind = PrepareScalarCast(RHS, LHSType); 7804 return Compatible; 7805 } 7806 7807 // Conversions to normal pointers. 7808 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7809 // U* -> T* 7810 if (isa<PointerType>(RHSType)) { 7811 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7812 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7813 if (AddrSpaceL != AddrSpaceR) 7814 Kind = CK_AddressSpaceConversion; 7815 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 7816 Kind = CK_NoOp; 7817 else 7818 Kind = CK_BitCast; 7819 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7820 } 7821 7822 // int -> T* 7823 if (RHSType->isIntegerType()) { 7824 Kind = CK_IntegralToPointer; // FIXME: null? 7825 return IntToPointer; 7826 } 7827 7828 // C pointers are not compatible with ObjC object pointers, 7829 // with two exceptions: 7830 if (isa<ObjCObjectPointerType>(RHSType)) { 7831 // - conversions to void* 7832 if (LHSPointer->getPointeeType()->isVoidType()) { 7833 Kind = CK_BitCast; 7834 return Compatible; 7835 } 7836 7837 // - conversions from 'Class' to the redefinition type 7838 if (RHSType->isObjCClassType() && 7839 Context.hasSameType(LHSType, 7840 Context.getObjCClassRedefinitionType())) { 7841 Kind = CK_BitCast; 7842 return Compatible; 7843 } 7844 7845 Kind = CK_BitCast; 7846 return IncompatiblePointer; 7847 } 7848 7849 // U^ -> void* 7850 if (RHSType->getAs<BlockPointerType>()) { 7851 if (LHSPointer->getPointeeType()->isVoidType()) { 7852 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7853 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7854 ->getPointeeType() 7855 .getAddressSpace(); 7856 Kind = 7857 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7858 return Compatible; 7859 } 7860 } 7861 7862 return Incompatible; 7863 } 7864 7865 // Conversions to block pointers. 7866 if (isa<BlockPointerType>(LHSType)) { 7867 // U^ -> T^ 7868 if (RHSType->isBlockPointerType()) { 7869 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7870 ->getPointeeType() 7871 .getAddressSpace(); 7872 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7873 ->getPointeeType() 7874 .getAddressSpace(); 7875 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7876 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7877 } 7878 7879 // int or null -> T^ 7880 if (RHSType->isIntegerType()) { 7881 Kind = CK_IntegralToPointer; // FIXME: null 7882 return IntToBlockPointer; 7883 } 7884 7885 // id -> T^ 7886 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7887 Kind = CK_AnyPointerToBlockPointerCast; 7888 return Compatible; 7889 } 7890 7891 // void* -> T^ 7892 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7893 if (RHSPT->getPointeeType()->isVoidType()) { 7894 Kind = CK_AnyPointerToBlockPointerCast; 7895 return Compatible; 7896 } 7897 7898 return Incompatible; 7899 } 7900 7901 // Conversions to Objective-C pointers. 7902 if (isa<ObjCObjectPointerType>(LHSType)) { 7903 // A* -> B* 7904 if (RHSType->isObjCObjectPointerType()) { 7905 Kind = CK_BitCast; 7906 Sema::AssignConvertType result = 7907 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7908 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7909 result == Compatible && 7910 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7911 result = IncompatibleObjCWeakRef; 7912 return result; 7913 } 7914 7915 // int or null -> A* 7916 if (RHSType->isIntegerType()) { 7917 Kind = CK_IntegralToPointer; // FIXME: null 7918 return IntToPointer; 7919 } 7920 7921 // In general, C pointers are not compatible with ObjC object pointers, 7922 // with two exceptions: 7923 if (isa<PointerType>(RHSType)) { 7924 Kind = CK_CPointerToObjCPointerCast; 7925 7926 // - conversions from 'void*' 7927 if (RHSType->isVoidPointerType()) { 7928 return Compatible; 7929 } 7930 7931 // - conversions to 'Class' from its redefinition type 7932 if (LHSType->isObjCClassType() && 7933 Context.hasSameType(RHSType, 7934 Context.getObjCClassRedefinitionType())) { 7935 return Compatible; 7936 } 7937 7938 return IncompatiblePointer; 7939 } 7940 7941 // Only under strict condition T^ is compatible with an Objective-C pointer. 7942 if (RHSType->isBlockPointerType() && 7943 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7944 if (ConvertRHS) 7945 maybeExtendBlockObject(RHS); 7946 Kind = CK_BlockPointerToObjCPointerCast; 7947 return Compatible; 7948 } 7949 7950 return Incompatible; 7951 } 7952 7953 // Conversions from pointers that are not covered by the above. 7954 if (isa<PointerType>(RHSType)) { 7955 // T* -> _Bool 7956 if (LHSType == Context.BoolTy) { 7957 Kind = CK_PointerToBoolean; 7958 return Compatible; 7959 } 7960 7961 // T* -> int 7962 if (LHSType->isIntegerType()) { 7963 Kind = CK_PointerToIntegral; 7964 return PointerToInt; 7965 } 7966 7967 return Incompatible; 7968 } 7969 7970 // Conversions from Objective-C pointers that are not covered by the above. 7971 if (isa<ObjCObjectPointerType>(RHSType)) { 7972 // T* -> _Bool 7973 if (LHSType == Context.BoolTy) { 7974 Kind = CK_PointerToBoolean; 7975 return Compatible; 7976 } 7977 7978 // T* -> int 7979 if (LHSType->isIntegerType()) { 7980 Kind = CK_PointerToIntegral; 7981 return PointerToInt; 7982 } 7983 7984 return Incompatible; 7985 } 7986 7987 // struct A -> struct B 7988 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7989 if (Context.typesAreCompatible(LHSType, RHSType)) { 7990 Kind = CK_NoOp; 7991 return Compatible; 7992 } 7993 } 7994 7995 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7996 Kind = CK_IntToOCLSampler; 7997 return Compatible; 7998 } 7999 8000 return Incompatible; 8001 } 8002 8003 /// Constructs a transparent union from an expression that is 8004 /// used to initialize the transparent union. 8005 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8006 ExprResult &EResult, QualType UnionType, 8007 FieldDecl *Field) { 8008 // Build an initializer list that designates the appropriate member 8009 // of the transparent union. 8010 Expr *E = EResult.get(); 8011 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8012 E, SourceLocation()); 8013 Initializer->setType(UnionType); 8014 Initializer->setInitializedFieldInUnion(Field); 8015 8016 // Build a compound literal constructing a value of the transparent 8017 // union type from this initializer list. 8018 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8019 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8020 VK_RValue, Initializer, false); 8021 } 8022 8023 Sema::AssignConvertType 8024 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8025 ExprResult &RHS) { 8026 QualType RHSType = RHS.get()->getType(); 8027 8028 // If the ArgType is a Union type, we want to handle a potential 8029 // transparent_union GCC extension. 8030 const RecordType *UT = ArgType->getAsUnionType(); 8031 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8032 return Incompatible; 8033 8034 // The field to initialize within the transparent union. 8035 RecordDecl *UD = UT->getDecl(); 8036 FieldDecl *InitField = nullptr; 8037 // It's compatible if the expression matches any of the fields. 8038 for (auto *it : UD->fields()) { 8039 if (it->getType()->isPointerType()) { 8040 // If the transparent union contains a pointer type, we allow: 8041 // 1) void pointer 8042 // 2) null pointer constant 8043 if (RHSType->isPointerType()) 8044 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8045 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8046 InitField = it; 8047 break; 8048 } 8049 8050 if (RHS.get()->isNullPointerConstant(Context, 8051 Expr::NPC_ValueDependentIsNull)) { 8052 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8053 CK_NullToPointer); 8054 InitField = it; 8055 break; 8056 } 8057 } 8058 8059 CastKind Kind; 8060 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8061 == Compatible) { 8062 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8063 InitField = it; 8064 break; 8065 } 8066 } 8067 8068 if (!InitField) 8069 return Incompatible; 8070 8071 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8072 return Compatible; 8073 } 8074 8075 Sema::AssignConvertType 8076 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8077 bool Diagnose, 8078 bool DiagnoseCFAudited, 8079 bool ConvertRHS) { 8080 // We need to be able to tell the caller whether we diagnosed a problem, if 8081 // they ask us to issue diagnostics. 8082 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8083 8084 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8085 // we can't avoid *all* modifications at the moment, so we need some somewhere 8086 // to put the updated value. 8087 ExprResult LocalRHS = CallerRHS; 8088 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8089 8090 if (getLangOpts().CPlusPlus) { 8091 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8092 // C++ 5.17p3: If the left operand is not of class type, the 8093 // expression is implicitly converted (C++ 4) to the 8094 // cv-unqualified type of the left operand. 8095 QualType RHSType = RHS.get()->getType(); 8096 if (Diagnose) { 8097 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8098 AA_Assigning); 8099 } else { 8100 ImplicitConversionSequence ICS = 8101 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8102 /*SuppressUserConversions=*/false, 8103 /*AllowExplicit=*/false, 8104 /*InOverloadResolution=*/false, 8105 /*CStyle=*/false, 8106 /*AllowObjCWritebackConversion=*/false); 8107 if (ICS.isFailure()) 8108 return Incompatible; 8109 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8110 ICS, AA_Assigning); 8111 } 8112 if (RHS.isInvalid()) 8113 return Incompatible; 8114 Sema::AssignConvertType result = Compatible; 8115 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8116 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8117 result = IncompatibleObjCWeakRef; 8118 return result; 8119 } 8120 8121 // FIXME: Currently, we fall through and treat C++ classes like C 8122 // structures. 8123 // FIXME: We also fall through for atomics; not sure what should 8124 // happen there, though. 8125 } else if (RHS.get()->getType() == Context.OverloadTy) { 8126 // As a set of extensions to C, we support overloading on functions. These 8127 // functions need to be resolved here. 8128 DeclAccessPair DAP; 8129 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8130 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8131 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8132 else 8133 return Incompatible; 8134 } 8135 8136 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8137 // a null pointer constant. 8138 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8139 LHSType->isBlockPointerType()) && 8140 RHS.get()->isNullPointerConstant(Context, 8141 Expr::NPC_ValueDependentIsNull)) { 8142 if (Diagnose || ConvertRHS) { 8143 CastKind Kind; 8144 CXXCastPath Path; 8145 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8146 /*IgnoreBaseAccess=*/false, Diagnose); 8147 if (ConvertRHS) 8148 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8149 } 8150 return Compatible; 8151 } 8152 8153 // OpenCL queue_t type assignment. 8154 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8155 Context, Expr::NPC_ValueDependentIsNull)) { 8156 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8157 return Compatible; 8158 } 8159 8160 // This check seems unnatural, however it is necessary to ensure the proper 8161 // conversion of functions/arrays. If the conversion were done for all 8162 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8163 // expressions that suppress this implicit conversion (&, sizeof). 8164 // 8165 // Suppress this for references: C++ 8.5.3p5. 8166 if (!LHSType->isReferenceType()) { 8167 // FIXME: We potentially allocate here even if ConvertRHS is false. 8168 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8169 if (RHS.isInvalid()) 8170 return Incompatible; 8171 } 8172 CastKind Kind; 8173 Sema::AssignConvertType result = 8174 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8175 8176 // C99 6.5.16.1p2: The value of the right operand is converted to the 8177 // type of the assignment expression. 8178 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8179 // so that we can use references in built-in functions even in C. 8180 // The getNonReferenceType() call makes sure that the resulting expression 8181 // does not have reference type. 8182 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8183 QualType Ty = LHSType.getNonLValueExprType(Context); 8184 Expr *E = RHS.get(); 8185 8186 // Check for various Objective-C errors. If we are not reporting 8187 // diagnostics and just checking for errors, e.g., during overload 8188 // resolution, return Incompatible to indicate the failure. 8189 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8190 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8191 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8192 if (!Diagnose) 8193 return Incompatible; 8194 } 8195 if (getLangOpts().ObjC1 && 8196 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8197 E->getType(), E, Diagnose) || 8198 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8199 if (!Diagnose) 8200 return Incompatible; 8201 // Replace the expression with a corrected version and continue so we 8202 // can find further errors. 8203 RHS = E; 8204 return Compatible; 8205 } 8206 8207 if (ConvertRHS) 8208 RHS = ImpCastExprToType(E, Ty, Kind); 8209 } 8210 return result; 8211 } 8212 8213 namespace { 8214 /// The original operand to an operator, prior to the application of the usual 8215 /// arithmetic conversions and converting the arguments of a builtin operator 8216 /// candidate. 8217 struct OriginalOperand { 8218 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8219 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8220 Op = MTE->GetTemporaryExpr(); 8221 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8222 Op = BTE->getSubExpr(); 8223 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8224 Orig = ICE->getSubExprAsWritten(); 8225 Conversion = ICE->getConversionFunction(); 8226 } 8227 } 8228 8229 QualType getType() const { return Orig->getType(); } 8230 8231 Expr *Orig; 8232 NamedDecl *Conversion; 8233 }; 8234 } 8235 8236 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8237 ExprResult &RHS) { 8238 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8239 8240 Diag(Loc, diag::err_typecheck_invalid_operands) 8241 << OrigLHS.getType() << OrigRHS.getType() 8242 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8243 8244 // If a user-defined conversion was applied to either of the operands prior 8245 // to applying the built-in operator rules, tell the user about it. 8246 if (OrigLHS.Conversion) { 8247 Diag(OrigLHS.Conversion->getLocation(), 8248 diag::note_typecheck_invalid_operands_converted) 8249 << 0 << LHS.get()->getType(); 8250 } 8251 if (OrigRHS.Conversion) { 8252 Diag(OrigRHS.Conversion->getLocation(), 8253 diag::note_typecheck_invalid_operands_converted) 8254 << 1 << RHS.get()->getType(); 8255 } 8256 8257 return QualType(); 8258 } 8259 8260 // Diagnose cases where a scalar was implicitly converted to a vector and 8261 // diagnose the underlying types. Otherwise, diagnose the error 8262 // as invalid vector logical operands for non-C++ cases. 8263 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8264 ExprResult &RHS) { 8265 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8266 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8267 8268 bool LHSNatVec = LHSType->isVectorType(); 8269 bool RHSNatVec = RHSType->isVectorType(); 8270 8271 if (!(LHSNatVec && RHSNatVec)) { 8272 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8273 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8274 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8275 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8276 << Vector->getSourceRange(); 8277 return QualType(); 8278 } 8279 8280 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8281 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8282 << RHS.get()->getSourceRange(); 8283 8284 return QualType(); 8285 } 8286 8287 /// Try to convert a value of non-vector type to a vector type by converting 8288 /// the type to the element type of the vector and then performing a splat. 8289 /// If the language is OpenCL, we only use conversions that promote scalar 8290 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8291 /// for float->int. 8292 /// 8293 /// OpenCL V2.0 6.2.6.p2: 8294 /// An error shall occur if any scalar operand type has greater rank 8295 /// than the type of the vector element. 8296 /// 8297 /// \param scalar - if non-null, actually perform the conversions 8298 /// \return true if the operation fails (but without diagnosing the failure) 8299 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8300 QualType scalarTy, 8301 QualType vectorEltTy, 8302 QualType vectorTy, 8303 unsigned &DiagID) { 8304 // The conversion to apply to the scalar before splatting it, 8305 // if necessary. 8306 CastKind scalarCast = CK_NoOp; 8307 8308 if (vectorEltTy->isIntegralType(S.Context)) { 8309 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8310 (scalarTy->isIntegerType() && 8311 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8312 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8313 return true; 8314 } 8315 if (!scalarTy->isIntegralType(S.Context)) 8316 return true; 8317 scalarCast = CK_IntegralCast; 8318 } else if (vectorEltTy->isRealFloatingType()) { 8319 if (scalarTy->isRealFloatingType()) { 8320 if (S.getLangOpts().OpenCL && 8321 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8322 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8323 return true; 8324 } 8325 scalarCast = CK_FloatingCast; 8326 } 8327 else if (scalarTy->isIntegralType(S.Context)) 8328 scalarCast = CK_IntegralToFloating; 8329 else 8330 return true; 8331 } else { 8332 return true; 8333 } 8334 8335 // Adjust scalar if desired. 8336 if (scalar) { 8337 if (scalarCast != CK_NoOp) 8338 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8339 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8340 } 8341 return false; 8342 } 8343 8344 /// Convert vector E to a vector with the same number of elements but different 8345 /// element type. 8346 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8347 const auto *VecTy = E->getType()->getAs<VectorType>(); 8348 assert(VecTy && "Expression E must be a vector"); 8349 QualType NewVecTy = S.Context.getVectorType(ElementType, 8350 VecTy->getNumElements(), 8351 VecTy->getVectorKind()); 8352 8353 // Look through the implicit cast. Return the subexpression if its type is 8354 // NewVecTy. 8355 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8356 if (ICE->getSubExpr()->getType() == NewVecTy) 8357 return ICE->getSubExpr(); 8358 8359 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8360 return S.ImpCastExprToType(E, NewVecTy, Cast); 8361 } 8362 8363 /// Test if a (constant) integer Int can be casted to another integer type 8364 /// IntTy without losing precision. 8365 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8366 QualType OtherIntTy) { 8367 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8368 8369 // Reject cases where the value of the Int is unknown as that would 8370 // possibly cause truncation, but accept cases where the scalar can be 8371 // demoted without loss of precision. 8372 llvm::APSInt Result; 8373 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8374 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8375 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8376 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8377 8378 if (CstInt) { 8379 // If the scalar is constant and is of a higher order and has more active 8380 // bits that the vector element type, reject it. 8381 unsigned NumBits = IntSigned 8382 ? (Result.isNegative() ? Result.getMinSignedBits() 8383 : Result.getActiveBits()) 8384 : Result.getActiveBits(); 8385 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8386 return true; 8387 8388 // If the signedness of the scalar type and the vector element type 8389 // differs and the number of bits is greater than that of the vector 8390 // element reject it. 8391 return (IntSigned != OtherIntSigned && 8392 NumBits > S.Context.getIntWidth(OtherIntTy)); 8393 } 8394 8395 // Reject cases where the value of the scalar is not constant and it's 8396 // order is greater than that of the vector element type. 8397 return (Order < 0); 8398 } 8399 8400 /// Test if a (constant) integer Int can be casted to floating point type 8401 /// FloatTy without losing precision. 8402 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8403 QualType FloatTy) { 8404 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8405 8406 // Determine if the integer constant can be expressed as a floating point 8407 // number of the appropriate type. 8408 llvm::APSInt Result; 8409 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8410 uint64_t Bits = 0; 8411 if (CstInt) { 8412 // Reject constants that would be truncated if they were converted to 8413 // the floating point type. Test by simple to/from conversion. 8414 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8415 // could be avoided if there was a convertFromAPInt method 8416 // which could signal back if implicit truncation occurred. 8417 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8418 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8419 llvm::APFloat::rmTowardZero); 8420 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8421 !IntTy->hasSignedIntegerRepresentation()); 8422 bool Ignored = false; 8423 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8424 &Ignored); 8425 if (Result != ConvertBack) 8426 return true; 8427 } else { 8428 // Reject types that cannot be fully encoded into the mantissa of 8429 // the float. 8430 Bits = S.Context.getTypeSize(IntTy); 8431 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8432 S.Context.getFloatTypeSemantics(FloatTy)); 8433 if (Bits > FloatPrec) 8434 return true; 8435 } 8436 8437 return false; 8438 } 8439 8440 /// Attempt to convert and splat Scalar into a vector whose types matches 8441 /// Vector following GCC conversion rules. The rule is that implicit 8442 /// conversion can occur when Scalar can be casted to match Vector's element 8443 /// type without causing truncation of Scalar. 8444 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8445 ExprResult *Vector) { 8446 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8447 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8448 const VectorType *VT = VectorTy->getAs<VectorType>(); 8449 8450 assert(!isa<ExtVectorType>(VT) && 8451 "ExtVectorTypes should not be handled here!"); 8452 8453 QualType VectorEltTy = VT->getElementType(); 8454 8455 // Reject cases where the vector element type or the scalar element type are 8456 // not integral or floating point types. 8457 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8458 return true; 8459 8460 // The conversion to apply to the scalar before splatting it, 8461 // if necessary. 8462 CastKind ScalarCast = CK_NoOp; 8463 8464 // Accept cases where the vector elements are integers and the scalar is 8465 // an integer. 8466 // FIXME: Notionally if the scalar was a floating point value with a precise 8467 // integral representation, we could cast it to an appropriate integer 8468 // type and then perform the rest of the checks here. GCC will perform 8469 // this conversion in some cases as determined by the input language. 8470 // We should accept it on a language independent basis. 8471 if (VectorEltTy->isIntegralType(S.Context) && 8472 ScalarTy->isIntegralType(S.Context) && 8473 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8474 8475 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8476 return true; 8477 8478 ScalarCast = CK_IntegralCast; 8479 } else if (VectorEltTy->isRealFloatingType()) { 8480 if (ScalarTy->isRealFloatingType()) { 8481 8482 // Reject cases where the scalar type is not a constant and has a higher 8483 // Order than the vector element type. 8484 llvm::APFloat Result(0.0); 8485 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8486 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8487 if (!CstScalar && Order < 0) 8488 return true; 8489 8490 // If the scalar cannot be safely casted to the vector element type, 8491 // reject it. 8492 if (CstScalar) { 8493 bool Truncated = false; 8494 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8495 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8496 if (Truncated) 8497 return true; 8498 } 8499 8500 ScalarCast = CK_FloatingCast; 8501 } else if (ScalarTy->isIntegralType(S.Context)) { 8502 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8503 return true; 8504 8505 ScalarCast = CK_IntegralToFloating; 8506 } else 8507 return true; 8508 } 8509 8510 // Adjust scalar if desired. 8511 if (Scalar) { 8512 if (ScalarCast != CK_NoOp) 8513 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8514 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8515 } 8516 return false; 8517 } 8518 8519 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8520 SourceLocation Loc, bool IsCompAssign, 8521 bool AllowBothBool, 8522 bool AllowBoolConversions) { 8523 if (!IsCompAssign) { 8524 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8525 if (LHS.isInvalid()) 8526 return QualType(); 8527 } 8528 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8529 if (RHS.isInvalid()) 8530 return QualType(); 8531 8532 // For conversion purposes, we ignore any qualifiers. 8533 // For example, "const float" and "float" are equivalent. 8534 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8535 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8536 8537 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8538 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8539 assert(LHSVecType || RHSVecType); 8540 8541 // AltiVec-style "vector bool op vector bool" combinations are allowed 8542 // for some operators but not others. 8543 if (!AllowBothBool && 8544 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8545 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8546 return InvalidOperands(Loc, LHS, RHS); 8547 8548 // If the vector types are identical, return. 8549 if (Context.hasSameType(LHSType, RHSType)) 8550 return LHSType; 8551 8552 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8553 if (LHSVecType && RHSVecType && 8554 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8555 if (isa<ExtVectorType>(LHSVecType)) { 8556 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8557 return LHSType; 8558 } 8559 8560 if (!IsCompAssign) 8561 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8562 return RHSType; 8563 } 8564 8565 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8566 // can be mixed, with the result being the non-bool type. The non-bool 8567 // operand must have integer element type. 8568 if (AllowBoolConversions && LHSVecType && RHSVecType && 8569 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8570 (Context.getTypeSize(LHSVecType->getElementType()) == 8571 Context.getTypeSize(RHSVecType->getElementType()))) { 8572 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8573 LHSVecType->getElementType()->isIntegerType() && 8574 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8575 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8576 return LHSType; 8577 } 8578 if (!IsCompAssign && 8579 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8580 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8581 RHSVecType->getElementType()->isIntegerType()) { 8582 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8583 return RHSType; 8584 } 8585 } 8586 8587 // If there's a vector type and a scalar, try to convert the scalar to 8588 // the vector element type and splat. 8589 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8590 if (!RHSVecType) { 8591 if (isa<ExtVectorType>(LHSVecType)) { 8592 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8593 LHSVecType->getElementType(), LHSType, 8594 DiagID)) 8595 return LHSType; 8596 } else { 8597 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8598 return LHSType; 8599 } 8600 } 8601 if (!LHSVecType) { 8602 if (isa<ExtVectorType>(RHSVecType)) { 8603 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8604 LHSType, RHSVecType->getElementType(), 8605 RHSType, DiagID)) 8606 return RHSType; 8607 } else { 8608 if (LHS.get()->getValueKind() == VK_LValue || 8609 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8610 return RHSType; 8611 } 8612 } 8613 8614 // FIXME: The code below also handles conversion between vectors and 8615 // non-scalars, we should break this down into fine grained specific checks 8616 // and emit proper diagnostics. 8617 QualType VecType = LHSVecType ? LHSType : RHSType; 8618 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8619 QualType OtherType = LHSVecType ? RHSType : LHSType; 8620 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8621 if (isLaxVectorConversion(OtherType, VecType)) { 8622 // If we're allowing lax vector conversions, only the total (data) size 8623 // needs to be the same. For non compound assignment, if one of the types is 8624 // scalar, the result is always the vector type. 8625 if (!IsCompAssign) { 8626 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8627 return VecType; 8628 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8629 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8630 // type. Note that this is already done by non-compound assignments in 8631 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8632 // <1 x T> -> T. The result is also a vector type. 8633 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8634 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8635 ExprResult *RHSExpr = &RHS; 8636 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8637 return VecType; 8638 } 8639 } 8640 8641 // Okay, the expression is invalid. 8642 8643 // If there's a non-vector, non-real operand, diagnose that. 8644 if ((!RHSVecType && !RHSType->isRealType()) || 8645 (!LHSVecType && !LHSType->isRealType())) { 8646 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8647 << LHSType << RHSType 8648 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8649 return QualType(); 8650 } 8651 8652 // OpenCL V1.1 6.2.6.p1: 8653 // If the operands are of more than one vector type, then an error shall 8654 // occur. Implicit conversions between vector types are not permitted, per 8655 // section 6.2.1. 8656 if (getLangOpts().OpenCL && 8657 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8658 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8659 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8660 << RHSType; 8661 return QualType(); 8662 } 8663 8664 8665 // If there is a vector type that is not a ExtVector and a scalar, we reach 8666 // this point if scalar could not be converted to the vector's element type 8667 // without truncation. 8668 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8669 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8670 QualType Scalar = LHSVecType ? RHSType : LHSType; 8671 QualType Vector = LHSVecType ? LHSType : RHSType; 8672 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8673 Diag(Loc, 8674 diag::err_typecheck_vector_not_convertable_implict_truncation) 8675 << ScalarOrVector << Scalar << Vector; 8676 8677 return QualType(); 8678 } 8679 8680 // Otherwise, use the generic diagnostic. 8681 Diag(Loc, DiagID) 8682 << LHSType << RHSType 8683 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8684 return QualType(); 8685 } 8686 8687 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8688 // expression. These are mainly cases where the null pointer is used as an 8689 // integer instead of a pointer. 8690 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8691 SourceLocation Loc, bool IsCompare) { 8692 // The canonical way to check for a GNU null is with isNullPointerConstant, 8693 // but we use a bit of a hack here for speed; this is a relatively 8694 // hot path, and isNullPointerConstant is slow. 8695 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8696 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8697 8698 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8699 8700 // Avoid analyzing cases where the result will either be invalid (and 8701 // diagnosed as such) or entirely valid and not something to warn about. 8702 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8703 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8704 return; 8705 8706 // Comparison operations would not make sense with a null pointer no matter 8707 // what the other expression is. 8708 if (!IsCompare) { 8709 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8710 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8711 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8712 return; 8713 } 8714 8715 // The rest of the operations only make sense with a null pointer 8716 // if the other expression is a pointer. 8717 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8718 NonNullType->canDecayToPointerType()) 8719 return; 8720 8721 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8722 << LHSNull /* LHS is NULL */ << NonNullType 8723 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8724 } 8725 8726 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8727 ExprResult &RHS, 8728 SourceLocation Loc, bool IsDiv) { 8729 // Check for division/remainder by zero. 8730 llvm::APSInt RHSValue; 8731 if (!RHS.get()->isValueDependent() && 8732 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8733 S.DiagRuntimeBehavior(Loc, RHS.get(), 8734 S.PDiag(diag::warn_remainder_division_by_zero) 8735 << IsDiv << RHS.get()->getSourceRange()); 8736 } 8737 8738 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8739 SourceLocation Loc, 8740 bool IsCompAssign, bool IsDiv) { 8741 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8742 8743 if (LHS.get()->getType()->isVectorType() || 8744 RHS.get()->getType()->isVectorType()) 8745 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8746 /*AllowBothBool*/getLangOpts().AltiVec, 8747 /*AllowBoolConversions*/false); 8748 8749 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8750 if (LHS.isInvalid() || RHS.isInvalid()) 8751 return QualType(); 8752 8753 8754 if (compType.isNull() || !compType->isArithmeticType()) 8755 return InvalidOperands(Loc, LHS, RHS); 8756 if (IsDiv) 8757 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8758 return compType; 8759 } 8760 8761 QualType Sema::CheckRemainderOperands( 8762 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8763 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8764 8765 if (LHS.get()->getType()->isVectorType() || 8766 RHS.get()->getType()->isVectorType()) { 8767 if (LHS.get()->getType()->hasIntegerRepresentation() && 8768 RHS.get()->getType()->hasIntegerRepresentation()) 8769 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8770 /*AllowBothBool*/getLangOpts().AltiVec, 8771 /*AllowBoolConversions*/false); 8772 return InvalidOperands(Loc, LHS, RHS); 8773 } 8774 8775 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8776 if (LHS.isInvalid() || RHS.isInvalid()) 8777 return QualType(); 8778 8779 if (compType.isNull() || !compType->isIntegerType()) 8780 return InvalidOperands(Loc, LHS, RHS); 8781 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8782 return compType; 8783 } 8784 8785 /// Diagnose invalid arithmetic on two void pointers. 8786 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8787 Expr *LHSExpr, Expr *RHSExpr) { 8788 S.Diag(Loc, S.getLangOpts().CPlusPlus 8789 ? diag::err_typecheck_pointer_arith_void_type 8790 : diag::ext_gnu_void_ptr) 8791 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8792 << RHSExpr->getSourceRange(); 8793 } 8794 8795 /// Diagnose invalid arithmetic on a void pointer. 8796 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8797 Expr *Pointer) { 8798 S.Diag(Loc, S.getLangOpts().CPlusPlus 8799 ? diag::err_typecheck_pointer_arith_void_type 8800 : diag::ext_gnu_void_ptr) 8801 << 0 /* one pointer */ << Pointer->getSourceRange(); 8802 } 8803 8804 /// Diagnose invalid arithmetic on a null pointer. 8805 /// 8806 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8807 /// idiom, which we recognize as a GNU extension. 8808 /// 8809 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8810 Expr *Pointer, bool IsGNUIdiom) { 8811 if (IsGNUIdiom) 8812 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8813 << Pointer->getSourceRange(); 8814 else 8815 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8816 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8817 } 8818 8819 /// Diagnose invalid arithmetic on two function pointers. 8820 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8821 Expr *LHS, Expr *RHS) { 8822 assert(LHS->getType()->isAnyPointerType()); 8823 assert(RHS->getType()->isAnyPointerType()); 8824 S.Diag(Loc, S.getLangOpts().CPlusPlus 8825 ? diag::err_typecheck_pointer_arith_function_type 8826 : diag::ext_gnu_ptr_func_arith) 8827 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8828 // We only show the second type if it differs from the first. 8829 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8830 RHS->getType()) 8831 << RHS->getType()->getPointeeType() 8832 << LHS->getSourceRange() << RHS->getSourceRange(); 8833 } 8834 8835 /// Diagnose invalid arithmetic on a function pointer. 8836 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8837 Expr *Pointer) { 8838 assert(Pointer->getType()->isAnyPointerType()); 8839 S.Diag(Loc, S.getLangOpts().CPlusPlus 8840 ? diag::err_typecheck_pointer_arith_function_type 8841 : diag::ext_gnu_ptr_func_arith) 8842 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8843 << 0 /* one pointer, so only one type */ 8844 << Pointer->getSourceRange(); 8845 } 8846 8847 /// Emit error if Operand is incomplete pointer type 8848 /// 8849 /// \returns True if pointer has incomplete type 8850 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8851 Expr *Operand) { 8852 QualType ResType = Operand->getType(); 8853 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8854 ResType = ResAtomicType->getValueType(); 8855 8856 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8857 QualType PointeeTy = ResType->getPointeeType(); 8858 return S.RequireCompleteType(Loc, PointeeTy, 8859 diag::err_typecheck_arithmetic_incomplete_type, 8860 PointeeTy, Operand->getSourceRange()); 8861 } 8862 8863 /// Check the validity of an arithmetic pointer operand. 8864 /// 8865 /// If the operand has pointer type, this code will check for pointer types 8866 /// which are invalid in arithmetic operations. These will be diagnosed 8867 /// appropriately, including whether or not the use is supported as an 8868 /// extension. 8869 /// 8870 /// \returns True when the operand is valid to use (even if as an extension). 8871 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8872 Expr *Operand) { 8873 QualType ResType = Operand->getType(); 8874 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8875 ResType = ResAtomicType->getValueType(); 8876 8877 if (!ResType->isAnyPointerType()) return true; 8878 8879 QualType PointeeTy = ResType->getPointeeType(); 8880 if (PointeeTy->isVoidType()) { 8881 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8882 return !S.getLangOpts().CPlusPlus; 8883 } 8884 if (PointeeTy->isFunctionType()) { 8885 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8886 return !S.getLangOpts().CPlusPlus; 8887 } 8888 8889 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8890 8891 return true; 8892 } 8893 8894 /// Check the validity of a binary arithmetic operation w.r.t. pointer 8895 /// operands. 8896 /// 8897 /// This routine will diagnose any invalid arithmetic on pointer operands much 8898 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8899 /// for emitting a single diagnostic even for operations where both LHS and RHS 8900 /// are (potentially problematic) pointers. 8901 /// 8902 /// \returns True when the operand is valid to use (even if as an extension). 8903 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8904 Expr *LHSExpr, Expr *RHSExpr) { 8905 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8906 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8907 if (!isLHSPointer && !isRHSPointer) return true; 8908 8909 QualType LHSPointeeTy, RHSPointeeTy; 8910 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8911 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8912 8913 // if both are pointers check if operation is valid wrt address spaces 8914 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8915 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8916 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8917 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8918 S.Diag(Loc, 8919 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8920 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8921 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8922 return false; 8923 } 8924 } 8925 8926 // Check for arithmetic on pointers to incomplete types. 8927 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8928 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8929 if (isLHSVoidPtr || isRHSVoidPtr) { 8930 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8931 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8932 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8933 8934 return !S.getLangOpts().CPlusPlus; 8935 } 8936 8937 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8938 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8939 if (isLHSFuncPtr || isRHSFuncPtr) { 8940 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8941 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8942 RHSExpr); 8943 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8944 8945 return !S.getLangOpts().CPlusPlus; 8946 } 8947 8948 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8949 return false; 8950 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8951 return false; 8952 8953 return true; 8954 } 8955 8956 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8957 /// literal. 8958 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8959 Expr *LHSExpr, Expr *RHSExpr) { 8960 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8961 Expr* IndexExpr = RHSExpr; 8962 if (!StrExpr) { 8963 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8964 IndexExpr = LHSExpr; 8965 } 8966 8967 bool IsStringPlusInt = StrExpr && 8968 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8969 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8970 return; 8971 8972 llvm::APSInt index; 8973 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8974 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8975 if (index.isNonNegative() && 8976 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8977 index.isUnsigned())) 8978 return; 8979 } 8980 8981 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 8982 Self.Diag(OpLoc, diag::warn_string_plus_int) 8983 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8984 8985 // Only print a fixit for "str" + int, not for int + "str". 8986 if (IndexExpr == RHSExpr) { 8987 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 8988 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8989 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 8990 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8991 << FixItHint::CreateInsertion(EndLoc, "]"); 8992 } else 8993 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8994 } 8995 8996 /// Emit a warning when adding a char literal to a string. 8997 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8998 Expr *LHSExpr, Expr *RHSExpr) { 8999 const Expr *StringRefExpr = LHSExpr; 9000 const CharacterLiteral *CharExpr = 9001 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9002 9003 if (!CharExpr) { 9004 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9005 StringRefExpr = RHSExpr; 9006 } 9007 9008 if (!CharExpr || !StringRefExpr) 9009 return; 9010 9011 const QualType StringType = StringRefExpr->getType(); 9012 9013 // Return if not a PointerType. 9014 if (!StringType->isAnyPointerType()) 9015 return; 9016 9017 // Return if not a CharacterType. 9018 if (!StringType->getPointeeType()->isAnyCharacterType()) 9019 return; 9020 9021 ASTContext &Ctx = Self.getASTContext(); 9022 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9023 9024 const QualType CharType = CharExpr->getType(); 9025 if (!CharType->isAnyCharacterType() && 9026 CharType->isIntegerType() && 9027 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9028 Self.Diag(OpLoc, diag::warn_string_plus_char) 9029 << DiagRange << Ctx.CharTy; 9030 } else { 9031 Self.Diag(OpLoc, diag::warn_string_plus_char) 9032 << DiagRange << CharExpr->getType(); 9033 } 9034 9035 // Only print a fixit for str + char, not for char + str. 9036 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9037 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9038 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9039 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9040 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9041 << FixItHint::CreateInsertion(EndLoc, "]"); 9042 } else { 9043 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9044 } 9045 } 9046 9047 /// Emit error when two pointers are incompatible. 9048 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9049 Expr *LHSExpr, Expr *RHSExpr) { 9050 assert(LHSExpr->getType()->isAnyPointerType()); 9051 assert(RHSExpr->getType()->isAnyPointerType()); 9052 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9053 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9054 << RHSExpr->getSourceRange(); 9055 } 9056 9057 // C99 6.5.6 9058 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9059 SourceLocation Loc, BinaryOperatorKind Opc, 9060 QualType* CompLHSTy) { 9061 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9062 9063 if (LHS.get()->getType()->isVectorType() || 9064 RHS.get()->getType()->isVectorType()) { 9065 QualType compType = CheckVectorOperands( 9066 LHS, RHS, Loc, CompLHSTy, 9067 /*AllowBothBool*/getLangOpts().AltiVec, 9068 /*AllowBoolConversions*/getLangOpts().ZVector); 9069 if (CompLHSTy) *CompLHSTy = compType; 9070 return compType; 9071 } 9072 9073 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9074 if (LHS.isInvalid() || RHS.isInvalid()) 9075 return QualType(); 9076 9077 // Diagnose "string literal" '+' int and string '+' "char literal". 9078 if (Opc == BO_Add) { 9079 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9080 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9081 } 9082 9083 // handle the common case first (both operands are arithmetic). 9084 if (!compType.isNull() && compType->isArithmeticType()) { 9085 if (CompLHSTy) *CompLHSTy = compType; 9086 return compType; 9087 } 9088 9089 // Type-checking. Ultimately the pointer's going to be in PExp; 9090 // note that we bias towards the LHS being the pointer. 9091 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9092 9093 bool isObjCPointer; 9094 if (PExp->getType()->isPointerType()) { 9095 isObjCPointer = false; 9096 } else if (PExp->getType()->isObjCObjectPointerType()) { 9097 isObjCPointer = true; 9098 } else { 9099 std::swap(PExp, IExp); 9100 if (PExp->getType()->isPointerType()) { 9101 isObjCPointer = false; 9102 } else if (PExp->getType()->isObjCObjectPointerType()) { 9103 isObjCPointer = true; 9104 } else { 9105 return InvalidOperands(Loc, LHS, RHS); 9106 } 9107 } 9108 assert(PExp->getType()->isAnyPointerType()); 9109 9110 if (!IExp->getType()->isIntegerType()) 9111 return InvalidOperands(Loc, LHS, RHS); 9112 9113 // Adding to a null pointer results in undefined behavior. 9114 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9115 Context, Expr::NPC_ValueDependentIsNotNull)) { 9116 // In C++ adding zero to a null pointer is defined. 9117 llvm::APSInt KnownVal; 9118 if (!getLangOpts().CPlusPlus || 9119 (!IExp->isValueDependent() && 9120 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9121 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9122 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9123 Context, BO_Add, PExp, IExp); 9124 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9125 } 9126 } 9127 9128 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9129 return QualType(); 9130 9131 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9132 return QualType(); 9133 9134 // Check array bounds for pointer arithemtic 9135 CheckArrayAccess(PExp, IExp); 9136 9137 if (CompLHSTy) { 9138 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9139 if (LHSTy.isNull()) { 9140 LHSTy = LHS.get()->getType(); 9141 if (LHSTy->isPromotableIntegerType()) 9142 LHSTy = Context.getPromotedIntegerType(LHSTy); 9143 } 9144 *CompLHSTy = LHSTy; 9145 } 9146 9147 return PExp->getType(); 9148 } 9149 9150 // C99 6.5.6 9151 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9152 SourceLocation Loc, 9153 QualType* CompLHSTy) { 9154 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9155 9156 if (LHS.get()->getType()->isVectorType() || 9157 RHS.get()->getType()->isVectorType()) { 9158 QualType compType = CheckVectorOperands( 9159 LHS, RHS, Loc, CompLHSTy, 9160 /*AllowBothBool*/getLangOpts().AltiVec, 9161 /*AllowBoolConversions*/getLangOpts().ZVector); 9162 if (CompLHSTy) *CompLHSTy = compType; 9163 return compType; 9164 } 9165 9166 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9167 if (LHS.isInvalid() || RHS.isInvalid()) 9168 return QualType(); 9169 9170 // Enforce type constraints: C99 6.5.6p3. 9171 9172 // Handle the common case first (both operands are arithmetic). 9173 if (!compType.isNull() && compType->isArithmeticType()) { 9174 if (CompLHSTy) *CompLHSTy = compType; 9175 return compType; 9176 } 9177 9178 // Either ptr - int or ptr - ptr. 9179 if (LHS.get()->getType()->isAnyPointerType()) { 9180 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9181 9182 // Diagnose bad cases where we step over interface counts. 9183 if (LHS.get()->getType()->isObjCObjectPointerType() && 9184 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9185 return QualType(); 9186 9187 // The result type of a pointer-int computation is the pointer type. 9188 if (RHS.get()->getType()->isIntegerType()) { 9189 // Subtracting from a null pointer should produce a warning. 9190 // The last argument to the diagnose call says this doesn't match the 9191 // GNU int-to-pointer idiom. 9192 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9193 Expr::NPC_ValueDependentIsNotNull)) { 9194 // In C++ adding zero to a null pointer is defined. 9195 llvm::APSInt KnownVal; 9196 if (!getLangOpts().CPlusPlus || 9197 (!RHS.get()->isValueDependent() && 9198 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9199 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9200 } 9201 } 9202 9203 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9204 return QualType(); 9205 9206 // Check array bounds for pointer arithemtic 9207 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9208 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9209 9210 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9211 return LHS.get()->getType(); 9212 } 9213 9214 // Handle pointer-pointer subtractions. 9215 if (const PointerType *RHSPTy 9216 = RHS.get()->getType()->getAs<PointerType>()) { 9217 QualType rpointee = RHSPTy->getPointeeType(); 9218 9219 if (getLangOpts().CPlusPlus) { 9220 // Pointee types must be the same: C++ [expr.add] 9221 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9222 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9223 } 9224 } else { 9225 // Pointee types must be compatible C99 6.5.6p3 9226 if (!Context.typesAreCompatible( 9227 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9228 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9229 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9230 return QualType(); 9231 } 9232 } 9233 9234 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9235 LHS.get(), RHS.get())) 9236 return QualType(); 9237 9238 // FIXME: Add warnings for nullptr - ptr. 9239 9240 // The pointee type may have zero size. As an extension, a structure or 9241 // union may have zero size or an array may have zero length. In this 9242 // case subtraction does not make sense. 9243 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9244 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9245 if (ElementSize.isZero()) { 9246 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9247 << rpointee.getUnqualifiedType() 9248 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9249 } 9250 } 9251 9252 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9253 return Context.getPointerDiffType(); 9254 } 9255 } 9256 9257 return InvalidOperands(Loc, LHS, RHS); 9258 } 9259 9260 static bool isScopedEnumerationType(QualType T) { 9261 if (const EnumType *ET = T->getAs<EnumType>()) 9262 return ET->getDecl()->isScoped(); 9263 return false; 9264 } 9265 9266 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9267 SourceLocation Loc, BinaryOperatorKind Opc, 9268 QualType LHSType) { 9269 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9270 // so skip remaining warnings as we don't want to modify values within Sema. 9271 if (S.getLangOpts().OpenCL) 9272 return; 9273 9274 llvm::APSInt Right; 9275 // Check right/shifter operand 9276 if (RHS.get()->isValueDependent() || 9277 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9278 return; 9279 9280 if (Right.isNegative()) { 9281 S.DiagRuntimeBehavior(Loc, RHS.get(), 9282 S.PDiag(diag::warn_shift_negative) 9283 << RHS.get()->getSourceRange()); 9284 return; 9285 } 9286 llvm::APInt LeftBits(Right.getBitWidth(), 9287 S.Context.getTypeSize(LHS.get()->getType())); 9288 if (Right.uge(LeftBits)) { 9289 S.DiagRuntimeBehavior(Loc, RHS.get(), 9290 S.PDiag(diag::warn_shift_gt_typewidth) 9291 << RHS.get()->getSourceRange()); 9292 return; 9293 } 9294 if (Opc != BO_Shl) 9295 return; 9296 9297 // When left shifting an ICE which is signed, we can check for overflow which 9298 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9299 // integers have defined behavior modulo one more than the maximum value 9300 // representable in the result type, so never warn for those. 9301 llvm::APSInt Left; 9302 if (LHS.get()->isValueDependent() || 9303 LHSType->hasUnsignedIntegerRepresentation() || 9304 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9305 return; 9306 9307 // If LHS does not have a signed type and non-negative value 9308 // then, the behavior is undefined. Warn about it. 9309 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9310 S.DiagRuntimeBehavior(Loc, LHS.get(), 9311 S.PDiag(diag::warn_shift_lhs_negative) 9312 << LHS.get()->getSourceRange()); 9313 return; 9314 } 9315 9316 llvm::APInt ResultBits = 9317 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9318 if (LeftBits.uge(ResultBits)) 9319 return; 9320 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9321 Result = Result.shl(Right); 9322 9323 // Print the bit representation of the signed integer as an unsigned 9324 // hexadecimal number. 9325 SmallString<40> HexResult; 9326 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9327 9328 // If we are only missing a sign bit, this is less likely to result in actual 9329 // bugs -- if the result is cast back to an unsigned type, it will have the 9330 // expected value. Thus we place this behind a different warning that can be 9331 // turned off separately if needed. 9332 if (LeftBits == ResultBits - 1) { 9333 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9334 << HexResult << LHSType 9335 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9336 return; 9337 } 9338 9339 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9340 << HexResult.str() << Result.getMinSignedBits() << LHSType 9341 << Left.getBitWidth() << LHS.get()->getSourceRange() 9342 << RHS.get()->getSourceRange(); 9343 } 9344 9345 /// Return the resulting type when a vector is shifted 9346 /// by a scalar or vector shift amount. 9347 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9348 SourceLocation Loc, bool IsCompAssign) { 9349 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9350 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9351 !LHS.get()->getType()->isVectorType()) { 9352 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9353 << RHS.get()->getType() << LHS.get()->getType() 9354 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9355 return QualType(); 9356 } 9357 9358 if (!IsCompAssign) { 9359 LHS = S.UsualUnaryConversions(LHS.get()); 9360 if (LHS.isInvalid()) return QualType(); 9361 } 9362 9363 RHS = S.UsualUnaryConversions(RHS.get()); 9364 if (RHS.isInvalid()) return QualType(); 9365 9366 QualType LHSType = LHS.get()->getType(); 9367 // Note that LHS might be a scalar because the routine calls not only in 9368 // OpenCL case. 9369 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9370 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9371 9372 // Note that RHS might not be a vector. 9373 QualType RHSType = RHS.get()->getType(); 9374 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9375 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9376 9377 // The operands need to be integers. 9378 if (!LHSEleType->isIntegerType()) { 9379 S.Diag(Loc, diag::err_typecheck_expect_int) 9380 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9381 return QualType(); 9382 } 9383 9384 if (!RHSEleType->isIntegerType()) { 9385 S.Diag(Loc, diag::err_typecheck_expect_int) 9386 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9387 return QualType(); 9388 } 9389 9390 if (!LHSVecTy) { 9391 assert(RHSVecTy); 9392 if (IsCompAssign) 9393 return RHSType; 9394 if (LHSEleType != RHSEleType) { 9395 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9396 LHSEleType = RHSEleType; 9397 } 9398 QualType VecTy = 9399 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9400 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9401 LHSType = VecTy; 9402 } else if (RHSVecTy) { 9403 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9404 // are applied component-wise. So if RHS is a vector, then ensure 9405 // that the number of elements is the same as LHS... 9406 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9407 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9408 << LHS.get()->getType() << RHS.get()->getType() 9409 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9410 return QualType(); 9411 } 9412 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9413 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9414 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9415 if (LHSBT != RHSBT && 9416 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9417 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9418 << LHS.get()->getType() << RHS.get()->getType() 9419 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9420 } 9421 } 9422 } else { 9423 // ...else expand RHS to match the number of elements in LHS. 9424 QualType VecTy = 9425 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9426 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9427 } 9428 9429 return LHSType; 9430 } 9431 9432 // C99 6.5.7 9433 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9434 SourceLocation Loc, BinaryOperatorKind Opc, 9435 bool IsCompAssign) { 9436 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9437 9438 // Vector shifts promote their scalar inputs to vector type. 9439 if (LHS.get()->getType()->isVectorType() || 9440 RHS.get()->getType()->isVectorType()) { 9441 if (LangOpts.ZVector) { 9442 // The shift operators for the z vector extensions work basically 9443 // like general shifts, except that neither the LHS nor the RHS is 9444 // allowed to be a "vector bool". 9445 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9446 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9447 return InvalidOperands(Loc, LHS, RHS); 9448 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9449 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9450 return InvalidOperands(Loc, LHS, RHS); 9451 } 9452 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9453 } 9454 9455 // Shifts don't perform usual arithmetic conversions, they just do integer 9456 // promotions on each operand. C99 6.5.7p3 9457 9458 // For the LHS, do usual unary conversions, but then reset them away 9459 // if this is a compound assignment. 9460 ExprResult OldLHS = LHS; 9461 LHS = UsualUnaryConversions(LHS.get()); 9462 if (LHS.isInvalid()) 9463 return QualType(); 9464 QualType LHSType = LHS.get()->getType(); 9465 if (IsCompAssign) LHS = OldLHS; 9466 9467 // The RHS is simpler. 9468 RHS = UsualUnaryConversions(RHS.get()); 9469 if (RHS.isInvalid()) 9470 return QualType(); 9471 QualType RHSType = RHS.get()->getType(); 9472 9473 // C99 6.5.7p2: Each of the operands shall have integer type. 9474 if (!LHSType->hasIntegerRepresentation() || 9475 !RHSType->hasIntegerRepresentation()) 9476 return InvalidOperands(Loc, LHS, RHS); 9477 9478 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9479 // hasIntegerRepresentation() above instead of this. 9480 if (isScopedEnumerationType(LHSType) || 9481 isScopedEnumerationType(RHSType)) { 9482 return InvalidOperands(Loc, LHS, RHS); 9483 } 9484 // Sanity-check shift operands 9485 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9486 9487 // "The type of the result is that of the promoted left operand." 9488 return LHSType; 9489 } 9490 9491 /// If two different enums are compared, raise a warning. 9492 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9493 Expr *RHS) { 9494 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9495 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9496 9497 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9498 if (!LHSEnumType) 9499 return; 9500 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9501 if (!RHSEnumType) 9502 return; 9503 9504 // Ignore anonymous enums. 9505 if (!LHSEnumType->getDecl()->getIdentifier() && 9506 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9507 return; 9508 if (!RHSEnumType->getDecl()->getIdentifier() && 9509 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9510 return; 9511 9512 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9513 return; 9514 9515 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9516 << LHSStrippedType << RHSStrippedType 9517 << LHS->getSourceRange() << RHS->getSourceRange(); 9518 } 9519 9520 /// Diagnose bad pointer comparisons. 9521 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9522 ExprResult &LHS, ExprResult &RHS, 9523 bool IsError) { 9524 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9525 : diag::ext_typecheck_comparison_of_distinct_pointers) 9526 << LHS.get()->getType() << RHS.get()->getType() 9527 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9528 } 9529 9530 /// Returns false if the pointers are converted to a composite type, 9531 /// true otherwise. 9532 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9533 ExprResult &LHS, ExprResult &RHS) { 9534 // C++ [expr.rel]p2: 9535 // [...] Pointer conversions (4.10) and qualification 9536 // conversions (4.4) are performed on pointer operands (or on 9537 // a pointer operand and a null pointer constant) to bring 9538 // them to their composite pointer type. [...] 9539 // 9540 // C++ [expr.eq]p1 uses the same notion for (in)equality 9541 // comparisons of pointers. 9542 9543 QualType LHSType = LHS.get()->getType(); 9544 QualType RHSType = RHS.get()->getType(); 9545 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9546 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9547 9548 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9549 if (T.isNull()) { 9550 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9551 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9552 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9553 else 9554 S.InvalidOperands(Loc, LHS, RHS); 9555 return true; 9556 } 9557 9558 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9559 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9560 return false; 9561 } 9562 9563 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9564 ExprResult &LHS, 9565 ExprResult &RHS, 9566 bool IsError) { 9567 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9568 : diag::ext_typecheck_comparison_of_fptr_to_void) 9569 << LHS.get()->getType() << RHS.get()->getType() 9570 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9571 } 9572 9573 static bool isObjCObjectLiteral(ExprResult &E) { 9574 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9575 case Stmt::ObjCArrayLiteralClass: 9576 case Stmt::ObjCDictionaryLiteralClass: 9577 case Stmt::ObjCStringLiteralClass: 9578 case Stmt::ObjCBoxedExprClass: 9579 return true; 9580 default: 9581 // Note that ObjCBoolLiteral is NOT an object literal! 9582 return false; 9583 } 9584 } 9585 9586 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9587 const ObjCObjectPointerType *Type = 9588 LHS->getType()->getAs<ObjCObjectPointerType>(); 9589 9590 // If this is not actually an Objective-C object, bail out. 9591 if (!Type) 9592 return false; 9593 9594 // Get the LHS object's interface type. 9595 QualType InterfaceType = Type->getPointeeType(); 9596 9597 // If the RHS isn't an Objective-C object, bail out. 9598 if (!RHS->getType()->isObjCObjectPointerType()) 9599 return false; 9600 9601 // Try to find the -isEqual: method. 9602 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9603 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9604 InterfaceType, 9605 /*instance=*/true); 9606 if (!Method) { 9607 if (Type->isObjCIdType()) { 9608 // For 'id', just check the global pool. 9609 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9610 /*receiverId=*/true); 9611 } else { 9612 // Check protocols. 9613 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9614 /*instance=*/true); 9615 } 9616 } 9617 9618 if (!Method) 9619 return false; 9620 9621 QualType T = Method->parameters()[0]->getType(); 9622 if (!T->isObjCObjectPointerType()) 9623 return false; 9624 9625 QualType R = Method->getReturnType(); 9626 if (!R->isScalarType()) 9627 return false; 9628 9629 return true; 9630 } 9631 9632 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9633 FromE = FromE->IgnoreParenImpCasts(); 9634 switch (FromE->getStmtClass()) { 9635 default: 9636 break; 9637 case Stmt::ObjCStringLiteralClass: 9638 // "string literal" 9639 return LK_String; 9640 case Stmt::ObjCArrayLiteralClass: 9641 // "array literal" 9642 return LK_Array; 9643 case Stmt::ObjCDictionaryLiteralClass: 9644 // "dictionary literal" 9645 return LK_Dictionary; 9646 case Stmt::BlockExprClass: 9647 return LK_Block; 9648 case Stmt::ObjCBoxedExprClass: { 9649 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9650 switch (Inner->getStmtClass()) { 9651 case Stmt::IntegerLiteralClass: 9652 case Stmt::FloatingLiteralClass: 9653 case Stmt::CharacterLiteralClass: 9654 case Stmt::ObjCBoolLiteralExprClass: 9655 case Stmt::CXXBoolLiteralExprClass: 9656 // "numeric literal" 9657 return LK_Numeric; 9658 case Stmt::ImplicitCastExprClass: { 9659 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9660 // Boolean literals can be represented by implicit casts. 9661 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9662 return LK_Numeric; 9663 break; 9664 } 9665 default: 9666 break; 9667 } 9668 return LK_Boxed; 9669 } 9670 } 9671 return LK_None; 9672 } 9673 9674 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9675 ExprResult &LHS, ExprResult &RHS, 9676 BinaryOperator::Opcode Opc){ 9677 Expr *Literal; 9678 Expr *Other; 9679 if (isObjCObjectLiteral(LHS)) { 9680 Literal = LHS.get(); 9681 Other = RHS.get(); 9682 } else { 9683 Literal = RHS.get(); 9684 Other = LHS.get(); 9685 } 9686 9687 // Don't warn on comparisons against nil. 9688 Other = Other->IgnoreParenCasts(); 9689 if (Other->isNullPointerConstant(S.getASTContext(), 9690 Expr::NPC_ValueDependentIsNotNull)) 9691 return; 9692 9693 // This should be kept in sync with warn_objc_literal_comparison. 9694 // LK_String should always be after the other literals, since it has its own 9695 // warning flag. 9696 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9697 assert(LiteralKind != Sema::LK_Block); 9698 if (LiteralKind == Sema::LK_None) { 9699 llvm_unreachable("Unknown Objective-C object literal kind"); 9700 } 9701 9702 if (LiteralKind == Sema::LK_String) 9703 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9704 << Literal->getSourceRange(); 9705 else 9706 S.Diag(Loc, diag::warn_objc_literal_comparison) 9707 << LiteralKind << Literal->getSourceRange(); 9708 9709 if (BinaryOperator::isEqualityOp(Opc) && 9710 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9711 SourceLocation Start = LHS.get()->getBeginLoc(); 9712 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9713 CharSourceRange OpRange = 9714 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9715 9716 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9717 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9718 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9719 << FixItHint::CreateInsertion(End, "]"); 9720 } 9721 } 9722 9723 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9724 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9725 ExprResult &RHS, SourceLocation Loc, 9726 BinaryOperatorKind Opc) { 9727 // Check that left hand side is !something. 9728 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9729 if (!UO || UO->getOpcode() != UO_LNot) return; 9730 9731 // Only check if the right hand side is non-bool arithmetic type. 9732 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9733 9734 // Make sure that the something in !something is not bool. 9735 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9736 if (SubExpr->isKnownToHaveBooleanValue()) return; 9737 9738 // Emit warning. 9739 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9740 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9741 << Loc << IsBitwiseOp; 9742 9743 // First note suggest !(x < y) 9744 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9745 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9746 FirstClose = S.getLocForEndOfToken(FirstClose); 9747 if (FirstClose.isInvalid()) 9748 FirstOpen = SourceLocation(); 9749 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9750 << IsBitwiseOp 9751 << FixItHint::CreateInsertion(FirstOpen, "(") 9752 << FixItHint::CreateInsertion(FirstClose, ")"); 9753 9754 // Second note suggests (!x) < y 9755 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9756 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9757 SecondClose = S.getLocForEndOfToken(SecondClose); 9758 if (SecondClose.isInvalid()) 9759 SecondOpen = SourceLocation(); 9760 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9761 << FixItHint::CreateInsertion(SecondOpen, "(") 9762 << FixItHint::CreateInsertion(SecondClose, ")"); 9763 } 9764 9765 // Get the decl for a simple expression: a reference to a variable, 9766 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9767 static ValueDecl *getCompareDecl(Expr *E) { 9768 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9769 return DR->getDecl(); 9770 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9771 if (Ivar->isFreeIvar()) 9772 return Ivar->getDecl(); 9773 } 9774 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9775 if (Mem->isImplicitAccess()) 9776 return Mem->getMemberDecl(); 9777 } 9778 return nullptr; 9779 } 9780 9781 /// Diagnose some forms of syntactically-obvious tautological comparison. 9782 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9783 Expr *LHS, Expr *RHS, 9784 BinaryOperatorKind Opc) { 9785 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9786 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9787 9788 QualType LHSType = LHS->getType(); 9789 QualType RHSType = RHS->getType(); 9790 if (LHSType->hasFloatingRepresentation() || 9791 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9792 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9793 S.inTemplateInstantiation()) 9794 return; 9795 9796 // Comparisons between two array types are ill-formed for operator<=>, so 9797 // we shouldn't emit any additional warnings about it. 9798 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9799 return; 9800 9801 // For non-floating point types, check for self-comparisons of the form 9802 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9803 // often indicate logic errors in the program. 9804 // 9805 // NOTE: Don't warn about comparison expressions resulting from macro 9806 // expansion. Also don't warn about comparisons which are only self 9807 // comparisons within a template instantiation. The warnings should catch 9808 // obvious cases in the definition of the template anyways. The idea is to 9809 // warn when the typed comparison operator will always evaluate to the same 9810 // result. 9811 ValueDecl *DL = getCompareDecl(LHSStripped); 9812 ValueDecl *DR = getCompareDecl(RHSStripped); 9813 if (DL && DR && declaresSameEntity(DL, DR)) { 9814 StringRef Result; 9815 switch (Opc) { 9816 case BO_EQ: case BO_LE: case BO_GE: 9817 Result = "true"; 9818 break; 9819 case BO_NE: case BO_LT: case BO_GT: 9820 Result = "false"; 9821 break; 9822 case BO_Cmp: 9823 Result = "'std::strong_ordering::equal'"; 9824 break; 9825 default: 9826 break; 9827 } 9828 S.DiagRuntimeBehavior(Loc, nullptr, 9829 S.PDiag(diag::warn_comparison_always) 9830 << 0 /*self-comparison*/ << !Result.empty() 9831 << Result); 9832 } else if (DL && DR && 9833 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9834 !DL->isWeak() && !DR->isWeak()) { 9835 // What is it always going to evaluate to? 9836 StringRef Result; 9837 switch(Opc) { 9838 case BO_EQ: // e.g. array1 == array2 9839 Result = "false"; 9840 break; 9841 case BO_NE: // e.g. array1 != array2 9842 Result = "true"; 9843 break; 9844 default: // e.g. array1 <= array2 9845 // The best we can say is 'a constant' 9846 break; 9847 } 9848 S.DiagRuntimeBehavior(Loc, nullptr, 9849 S.PDiag(diag::warn_comparison_always) 9850 << 1 /*array comparison*/ 9851 << !Result.empty() << Result); 9852 } 9853 9854 if (isa<CastExpr>(LHSStripped)) 9855 LHSStripped = LHSStripped->IgnoreParenCasts(); 9856 if (isa<CastExpr>(RHSStripped)) 9857 RHSStripped = RHSStripped->IgnoreParenCasts(); 9858 9859 // Warn about comparisons against a string constant (unless the other 9860 // operand is null); the user probably wants strcmp. 9861 Expr *LiteralString = nullptr; 9862 Expr *LiteralStringStripped = nullptr; 9863 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9864 !RHSStripped->isNullPointerConstant(S.Context, 9865 Expr::NPC_ValueDependentIsNull)) { 9866 LiteralString = LHS; 9867 LiteralStringStripped = LHSStripped; 9868 } else if ((isa<StringLiteral>(RHSStripped) || 9869 isa<ObjCEncodeExpr>(RHSStripped)) && 9870 !LHSStripped->isNullPointerConstant(S.Context, 9871 Expr::NPC_ValueDependentIsNull)) { 9872 LiteralString = RHS; 9873 LiteralStringStripped = RHSStripped; 9874 } 9875 9876 if (LiteralString) { 9877 S.DiagRuntimeBehavior(Loc, nullptr, 9878 S.PDiag(diag::warn_stringcompare) 9879 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9880 << LiteralString->getSourceRange()); 9881 } 9882 } 9883 9884 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9885 switch (CK) { 9886 default: { 9887 #ifndef NDEBUG 9888 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9889 << "\n"; 9890 #endif 9891 llvm_unreachable("unhandled cast kind"); 9892 } 9893 case CK_UserDefinedConversion: 9894 return ICK_Identity; 9895 case CK_LValueToRValue: 9896 return ICK_Lvalue_To_Rvalue; 9897 case CK_ArrayToPointerDecay: 9898 return ICK_Array_To_Pointer; 9899 case CK_FunctionToPointerDecay: 9900 return ICK_Function_To_Pointer; 9901 case CK_IntegralCast: 9902 return ICK_Integral_Conversion; 9903 case CK_FloatingCast: 9904 return ICK_Floating_Conversion; 9905 case CK_IntegralToFloating: 9906 case CK_FloatingToIntegral: 9907 return ICK_Floating_Integral; 9908 case CK_IntegralComplexCast: 9909 case CK_FloatingComplexCast: 9910 case CK_FloatingComplexToIntegralComplex: 9911 case CK_IntegralComplexToFloatingComplex: 9912 return ICK_Complex_Conversion; 9913 case CK_FloatingComplexToReal: 9914 case CK_FloatingRealToComplex: 9915 case CK_IntegralComplexToReal: 9916 case CK_IntegralRealToComplex: 9917 return ICK_Complex_Real; 9918 } 9919 } 9920 9921 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 9922 QualType FromType, 9923 SourceLocation Loc) { 9924 // Check for a narrowing implicit conversion. 9925 StandardConversionSequence SCS; 9926 SCS.setAsIdentityConversion(); 9927 SCS.setToType(0, FromType); 9928 SCS.setToType(1, ToType); 9929 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9930 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 9931 9932 APValue PreNarrowingValue; 9933 QualType PreNarrowingType; 9934 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 9935 PreNarrowingType, 9936 /*IgnoreFloatToIntegralConversion*/ true)) { 9937 case NK_Dependent_Narrowing: 9938 // Implicit conversion to a narrower type, but the expression is 9939 // value-dependent so we can't tell whether it's actually narrowing. 9940 case NK_Not_Narrowing: 9941 return false; 9942 9943 case NK_Constant_Narrowing: 9944 // Implicit conversion to a narrower type, and the value is not a constant 9945 // expression. 9946 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9947 << /*Constant*/ 1 9948 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 9949 return true; 9950 9951 case NK_Variable_Narrowing: 9952 // Implicit conversion to a narrower type, and the value is not a constant 9953 // expression. 9954 case NK_Type_Narrowing: 9955 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9956 << /*Constant*/ 0 << FromType << ToType; 9957 // TODO: It's not a constant expression, but what if the user intended it 9958 // to be? Can we produce notes to help them figure out why it isn't? 9959 return true; 9960 } 9961 llvm_unreachable("unhandled case in switch"); 9962 } 9963 9964 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 9965 ExprResult &LHS, 9966 ExprResult &RHS, 9967 SourceLocation Loc) { 9968 using CCT = ComparisonCategoryType; 9969 9970 QualType LHSType = LHS.get()->getType(); 9971 QualType RHSType = RHS.get()->getType(); 9972 // Dig out the original argument type and expression before implicit casts 9973 // were applied. These are the types/expressions we need to check the 9974 // [expr.spaceship] requirements against. 9975 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9976 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9977 QualType LHSStrippedType = LHSStripped.get()->getType(); 9978 QualType RHSStrippedType = RHSStripped.get()->getType(); 9979 9980 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 9981 // other is not, the program is ill-formed. 9982 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 9983 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9984 return QualType(); 9985 } 9986 9987 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 9988 RHSStrippedType->isEnumeralType(); 9989 if (NumEnumArgs == 1) { 9990 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 9991 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 9992 if (OtherTy->hasFloatingRepresentation()) { 9993 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9994 return QualType(); 9995 } 9996 } 9997 if (NumEnumArgs == 2) { 9998 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 9999 // type E, the operator yields the result of converting the operands 10000 // to the underlying type of E and applying <=> to the converted operands. 10001 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10002 S.InvalidOperands(Loc, LHS, RHS); 10003 return QualType(); 10004 } 10005 QualType IntType = 10006 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10007 assert(IntType->isArithmeticType()); 10008 10009 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10010 // promote the boolean type, and all other promotable integer types, to 10011 // avoid this. 10012 if (IntType->isPromotableIntegerType()) 10013 IntType = S.Context.getPromotedIntegerType(IntType); 10014 10015 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10016 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10017 LHSType = RHSType = IntType; 10018 } 10019 10020 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10021 // usual arithmetic conversions are applied to the operands. 10022 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10023 if (LHS.isInvalid() || RHS.isInvalid()) 10024 return QualType(); 10025 if (Type.isNull()) 10026 return S.InvalidOperands(Loc, LHS, RHS); 10027 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10028 10029 bool HasNarrowing = checkThreeWayNarrowingConversion( 10030 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10031 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10032 RHS.get()->getBeginLoc()); 10033 if (HasNarrowing) 10034 return QualType(); 10035 10036 assert(!Type.isNull() && "composite type for <=> has not been set"); 10037 10038 auto TypeKind = [&]() { 10039 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10040 if (CT->getElementType()->hasFloatingRepresentation()) 10041 return CCT::WeakEquality; 10042 return CCT::StrongEquality; 10043 } 10044 if (Type->isIntegralOrEnumerationType()) 10045 return CCT::StrongOrdering; 10046 if (Type->hasFloatingRepresentation()) 10047 return CCT::PartialOrdering; 10048 llvm_unreachable("other types are unimplemented"); 10049 }(); 10050 10051 return S.CheckComparisonCategoryType(TypeKind, Loc); 10052 } 10053 10054 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10055 ExprResult &RHS, 10056 SourceLocation Loc, 10057 BinaryOperatorKind Opc) { 10058 if (Opc == BO_Cmp) 10059 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10060 10061 // C99 6.5.8p3 / C99 6.5.9p4 10062 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10063 if (LHS.isInvalid() || RHS.isInvalid()) 10064 return QualType(); 10065 if (Type.isNull()) 10066 return S.InvalidOperands(Loc, LHS, RHS); 10067 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10068 10069 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10070 10071 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10072 return S.InvalidOperands(Loc, LHS, RHS); 10073 10074 // Check for comparisons of floating point operands using != and ==. 10075 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10076 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10077 10078 // The result of comparisons is 'bool' in C++, 'int' in C. 10079 return S.Context.getLogicalOperationType(); 10080 } 10081 10082 // C99 6.5.8, C++ [expr.rel] 10083 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10084 SourceLocation Loc, 10085 BinaryOperatorKind Opc) { 10086 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10087 bool IsThreeWay = Opc == BO_Cmp; 10088 auto IsAnyPointerType = [](ExprResult E) { 10089 QualType Ty = E.get()->getType(); 10090 return Ty->isPointerType() || Ty->isMemberPointerType(); 10091 }; 10092 10093 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10094 // type, array-to-pointer, ..., conversions are performed on both operands to 10095 // bring them to their composite type. 10096 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10097 // any type-related checks. 10098 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10099 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10100 if (LHS.isInvalid()) 10101 return QualType(); 10102 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10103 if (RHS.isInvalid()) 10104 return QualType(); 10105 } else { 10106 LHS = DefaultLvalueConversion(LHS.get()); 10107 if (LHS.isInvalid()) 10108 return QualType(); 10109 RHS = DefaultLvalueConversion(RHS.get()); 10110 if (RHS.isInvalid()) 10111 return QualType(); 10112 } 10113 10114 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10115 10116 // Handle vector comparisons separately. 10117 if (LHS.get()->getType()->isVectorType() || 10118 RHS.get()->getType()->isVectorType()) 10119 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10120 10121 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10122 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10123 10124 QualType LHSType = LHS.get()->getType(); 10125 QualType RHSType = RHS.get()->getType(); 10126 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10127 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10128 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10129 10130 const Expr::NullPointerConstantKind LHSNullKind = 10131 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10132 const Expr::NullPointerConstantKind RHSNullKind = 10133 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10134 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10135 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10136 10137 auto computeResultTy = [&]() { 10138 if (Opc != BO_Cmp) 10139 return Context.getLogicalOperationType(); 10140 assert(getLangOpts().CPlusPlus); 10141 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10142 10143 QualType CompositeTy = LHS.get()->getType(); 10144 assert(!CompositeTy->isReferenceType()); 10145 10146 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10147 return CheckComparisonCategoryType(Kind, Loc); 10148 }; 10149 10150 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10151 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10152 // result is of type std::strong_equality 10153 if (CompositeTy->isFunctionPointerType() || 10154 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10155 // FIXME: consider making the function pointer case produce 10156 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10157 // and direction polls 10158 return buildResultTy(ComparisonCategoryType::StrongEquality); 10159 10160 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10161 // pointer type, p <=> q is of type std::strong_ordering. 10162 if (CompositeTy->isPointerType()) { 10163 // P0946R0: Comparisons between a null pointer constant and an object 10164 // pointer result in std::strong_equality 10165 if (LHSIsNull != RHSIsNull) 10166 return buildResultTy(ComparisonCategoryType::StrongEquality); 10167 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10168 } 10169 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10170 // TODO: Extend support for operator<=> to ObjC types. 10171 return InvalidOperands(Loc, LHS, RHS); 10172 }; 10173 10174 10175 if (!IsRelational && LHSIsNull != RHSIsNull) { 10176 bool IsEquality = Opc == BO_EQ; 10177 if (RHSIsNull) 10178 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10179 RHS.get()->getSourceRange()); 10180 else 10181 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10182 LHS.get()->getSourceRange()); 10183 } 10184 10185 if ((LHSType->isIntegerType() && !LHSIsNull) || 10186 (RHSType->isIntegerType() && !RHSIsNull)) { 10187 // Skip normal pointer conversion checks in this case; we have better 10188 // diagnostics for this below. 10189 } else if (getLangOpts().CPlusPlus) { 10190 // Equality comparison of a function pointer to a void pointer is invalid, 10191 // but we allow it as an extension. 10192 // FIXME: If we really want to allow this, should it be part of composite 10193 // pointer type computation so it works in conditionals too? 10194 if (!IsRelational && 10195 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10196 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10197 // This is a gcc extension compatibility comparison. 10198 // In a SFINAE context, we treat this as a hard error to maintain 10199 // conformance with the C++ standard. 10200 diagnoseFunctionPointerToVoidComparison( 10201 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10202 10203 if (isSFINAEContext()) 10204 return QualType(); 10205 10206 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10207 return computeResultTy(); 10208 } 10209 10210 // C++ [expr.eq]p2: 10211 // If at least one operand is a pointer [...] bring them to their 10212 // composite pointer type. 10213 // C++ [expr.spaceship]p6 10214 // If at least one of the operands is of pointer type, [...] bring them 10215 // to their composite pointer type. 10216 // C++ [expr.rel]p2: 10217 // If both operands are pointers, [...] bring them to their composite 10218 // pointer type. 10219 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10220 (IsRelational ? 2 : 1) && 10221 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10222 RHSType->isObjCObjectPointerType()))) { 10223 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10224 return QualType(); 10225 return computeResultTy(); 10226 } 10227 } else if (LHSType->isPointerType() && 10228 RHSType->isPointerType()) { // C99 6.5.8p2 10229 // All of the following pointer-related warnings are GCC extensions, except 10230 // when handling null pointer constants. 10231 QualType LCanPointeeTy = 10232 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10233 QualType RCanPointeeTy = 10234 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10235 10236 // C99 6.5.9p2 and C99 6.5.8p2 10237 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10238 RCanPointeeTy.getUnqualifiedType())) { 10239 // Valid unless a relational comparison of function pointers 10240 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10241 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10242 << LHSType << RHSType << LHS.get()->getSourceRange() 10243 << RHS.get()->getSourceRange(); 10244 } 10245 } else if (!IsRelational && 10246 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10247 // Valid unless comparison between non-null pointer and function pointer 10248 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10249 && !LHSIsNull && !RHSIsNull) 10250 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10251 /*isError*/false); 10252 } else { 10253 // Invalid 10254 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10255 } 10256 if (LCanPointeeTy != RCanPointeeTy) { 10257 // Treat NULL constant as a special case in OpenCL. 10258 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10259 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10260 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10261 Diag(Loc, 10262 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10263 << LHSType << RHSType << 0 /* comparison */ 10264 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10265 } 10266 } 10267 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10268 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10269 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10270 : CK_BitCast; 10271 if (LHSIsNull && !RHSIsNull) 10272 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10273 else 10274 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10275 } 10276 return computeResultTy(); 10277 } 10278 10279 if (getLangOpts().CPlusPlus) { 10280 // C++ [expr.eq]p4: 10281 // Two operands of type std::nullptr_t or one operand of type 10282 // std::nullptr_t and the other a null pointer constant compare equal. 10283 if (!IsRelational && LHSIsNull && RHSIsNull) { 10284 if (LHSType->isNullPtrType()) { 10285 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10286 return computeResultTy(); 10287 } 10288 if (RHSType->isNullPtrType()) { 10289 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10290 return computeResultTy(); 10291 } 10292 } 10293 10294 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10295 // These aren't covered by the composite pointer type rules. 10296 if (!IsRelational && RHSType->isNullPtrType() && 10297 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10298 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10299 return computeResultTy(); 10300 } 10301 if (!IsRelational && LHSType->isNullPtrType() && 10302 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10303 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10304 return computeResultTy(); 10305 } 10306 10307 if (IsRelational && 10308 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10309 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10310 // HACK: Relational comparison of nullptr_t against a pointer type is 10311 // invalid per DR583, but we allow it within std::less<> and friends, 10312 // since otherwise common uses of it break. 10313 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10314 // friends to have std::nullptr_t overload candidates. 10315 DeclContext *DC = CurContext; 10316 if (isa<FunctionDecl>(DC)) 10317 DC = DC->getParent(); 10318 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10319 if (CTSD->isInStdNamespace() && 10320 llvm::StringSwitch<bool>(CTSD->getName()) 10321 .Cases("less", "less_equal", "greater", "greater_equal", true) 10322 .Default(false)) { 10323 if (RHSType->isNullPtrType()) 10324 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10325 else 10326 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10327 return computeResultTy(); 10328 } 10329 } 10330 } 10331 10332 // C++ [expr.eq]p2: 10333 // If at least one operand is a pointer to member, [...] bring them to 10334 // their composite pointer type. 10335 if (!IsRelational && 10336 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10337 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10338 return QualType(); 10339 else 10340 return computeResultTy(); 10341 } 10342 } 10343 10344 // Handle block pointer types. 10345 if (!IsRelational && LHSType->isBlockPointerType() && 10346 RHSType->isBlockPointerType()) { 10347 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10348 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10349 10350 if (!LHSIsNull && !RHSIsNull && 10351 !Context.typesAreCompatible(lpointee, rpointee)) { 10352 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10353 << LHSType << RHSType << LHS.get()->getSourceRange() 10354 << RHS.get()->getSourceRange(); 10355 } 10356 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10357 return computeResultTy(); 10358 } 10359 10360 // Allow block pointers to be compared with null pointer constants. 10361 if (!IsRelational 10362 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10363 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10364 if (!LHSIsNull && !RHSIsNull) { 10365 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10366 ->getPointeeType()->isVoidType()) 10367 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10368 ->getPointeeType()->isVoidType()))) 10369 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10370 << LHSType << RHSType << LHS.get()->getSourceRange() 10371 << RHS.get()->getSourceRange(); 10372 } 10373 if (LHSIsNull && !RHSIsNull) 10374 LHS = ImpCastExprToType(LHS.get(), RHSType, 10375 RHSType->isPointerType() ? CK_BitCast 10376 : CK_AnyPointerToBlockPointerCast); 10377 else 10378 RHS = ImpCastExprToType(RHS.get(), LHSType, 10379 LHSType->isPointerType() ? CK_BitCast 10380 : CK_AnyPointerToBlockPointerCast); 10381 return computeResultTy(); 10382 } 10383 10384 if (LHSType->isObjCObjectPointerType() || 10385 RHSType->isObjCObjectPointerType()) { 10386 const PointerType *LPT = LHSType->getAs<PointerType>(); 10387 const PointerType *RPT = RHSType->getAs<PointerType>(); 10388 if (LPT || RPT) { 10389 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10390 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10391 10392 if (!LPtrToVoid && !RPtrToVoid && 10393 !Context.typesAreCompatible(LHSType, RHSType)) { 10394 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10395 /*isError*/false); 10396 } 10397 if (LHSIsNull && !RHSIsNull) { 10398 Expr *E = LHS.get(); 10399 if (getLangOpts().ObjCAutoRefCount) 10400 CheckObjCConversion(SourceRange(), RHSType, E, 10401 CCK_ImplicitConversion); 10402 LHS = ImpCastExprToType(E, RHSType, 10403 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10404 } 10405 else { 10406 Expr *E = RHS.get(); 10407 if (getLangOpts().ObjCAutoRefCount) 10408 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10409 /*Diagnose=*/true, 10410 /*DiagnoseCFAudited=*/false, Opc); 10411 RHS = ImpCastExprToType(E, LHSType, 10412 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10413 } 10414 return computeResultTy(); 10415 } 10416 if (LHSType->isObjCObjectPointerType() && 10417 RHSType->isObjCObjectPointerType()) { 10418 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10419 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10420 /*isError*/false); 10421 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10422 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10423 10424 if (LHSIsNull && !RHSIsNull) 10425 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10426 else 10427 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10428 return computeResultTy(); 10429 } 10430 10431 if (!IsRelational && LHSType->isBlockPointerType() && 10432 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10433 LHS = ImpCastExprToType(LHS.get(), RHSType, 10434 CK_BlockPointerToObjCPointerCast); 10435 return computeResultTy(); 10436 } else if (!IsRelational && 10437 LHSType->isBlockCompatibleObjCPointerType(Context) && 10438 RHSType->isBlockPointerType()) { 10439 RHS = ImpCastExprToType(RHS.get(), LHSType, 10440 CK_BlockPointerToObjCPointerCast); 10441 return computeResultTy(); 10442 } 10443 } 10444 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10445 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10446 unsigned DiagID = 0; 10447 bool isError = false; 10448 if (LangOpts.DebuggerSupport) { 10449 // Under a debugger, allow the comparison of pointers to integers, 10450 // since users tend to want to compare addresses. 10451 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10452 (RHSIsNull && RHSType->isIntegerType())) { 10453 if (IsRelational) { 10454 isError = getLangOpts().CPlusPlus; 10455 DiagID = 10456 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10457 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10458 } 10459 } else if (getLangOpts().CPlusPlus) { 10460 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10461 isError = true; 10462 } else if (IsRelational) 10463 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10464 else 10465 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10466 10467 if (DiagID) { 10468 Diag(Loc, DiagID) 10469 << LHSType << RHSType << LHS.get()->getSourceRange() 10470 << RHS.get()->getSourceRange(); 10471 if (isError) 10472 return QualType(); 10473 } 10474 10475 if (LHSType->isIntegerType()) 10476 LHS = ImpCastExprToType(LHS.get(), RHSType, 10477 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10478 else 10479 RHS = ImpCastExprToType(RHS.get(), LHSType, 10480 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10481 return computeResultTy(); 10482 } 10483 10484 // Handle block pointers. 10485 if (!IsRelational && RHSIsNull 10486 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10487 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10488 return computeResultTy(); 10489 } 10490 if (!IsRelational && LHSIsNull 10491 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10492 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10493 return computeResultTy(); 10494 } 10495 10496 if (getLangOpts().OpenCLVersion >= 200) { 10497 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10498 return computeResultTy(); 10499 } 10500 10501 if (LHSIsNull && RHSType->isQueueT()) { 10502 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10503 return computeResultTy(); 10504 } 10505 10506 if (LHSType->isQueueT() && RHSIsNull) { 10507 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10508 return computeResultTy(); 10509 } 10510 } 10511 10512 return InvalidOperands(Loc, LHS, RHS); 10513 } 10514 10515 // Return a signed ext_vector_type that is of identical size and number of 10516 // elements. For floating point vectors, return an integer type of identical 10517 // size and number of elements. In the non ext_vector_type case, search from 10518 // the largest type to the smallest type to avoid cases where long long == long, 10519 // where long gets picked over long long. 10520 QualType Sema::GetSignedVectorType(QualType V) { 10521 const VectorType *VTy = V->getAs<VectorType>(); 10522 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10523 10524 if (isa<ExtVectorType>(VTy)) { 10525 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10526 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10527 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10528 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10529 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10530 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10531 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10532 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10533 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10534 "Unhandled vector element size in vector compare"); 10535 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10536 } 10537 10538 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10539 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10540 VectorType::GenericVector); 10541 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10542 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10543 VectorType::GenericVector); 10544 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10545 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10546 VectorType::GenericVector); 10547 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10548 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10549 VectorType::GenericVector); 10550 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10551 "Unhandled vector element size in vector compare"); 10552 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10553 VectorType::GenericVector); 10554 } 10555 10556 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10557 /// operates on extended vector types. Instead of producing an IntTy result, 10558 /// like a scalar comparison, a vector comparison produces a vector of integer 10559 /// types. 10560 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10561 SourceLocation Loc, 10562 BinaryOperatorKind Opc) { 10563 // Check to make sure we're operating on vectors of the same type and width, 10564 // Allowing one side to be a scalar of element type. 10565 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10566 /*AllowBothBool*/true, 10567 /*AllowBoolConversions*/getLangOpts().ZVector); 10568 if (vType.isNull()) 10569 return vType; 10570 10571 QualType LHSType = LHS.get()->getType(); 10572 10573 // If AltiVec, the comparison results in a numeric type, i.e. 10574 // bool for C++, int for C 10575 if (getLangOpts().AltiVec && 10576 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10577 return Context.getLogicalOperationType(); 10578 10579 // For non-floating point types, check for self-comparisons of the form 10580 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10581 // often indicate logic errors in the program. 10582 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10583 10584 // Check for comparisons of floating point operands using != and ==. 10585 if (BinaryOperator::isEqualityOp(Opc) && 10586 LHSType->hasFloatingRepresentation()) { 10587 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10588 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10589 } 10590 10591 // Return a signed type for the vector. 10592 return GetSignedVectorType(vType); 10593 } 10594 10595 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10596 SourceLocation Loc) { 10597 // Ensure that either both operands are of the same vector type, or 10598 // one operand is of a vector type and the other is of its element type. 10599 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10600 /*AllowBothBool*/true, 10601 /*AllowBoolConversions*/false); 10602 if (vType.isNull()) 10603 return InvalidOperands(Loc, LHS, RHS); 10604 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10605 vType->hasFloatingRepresentation()) 10606 return InvalidOperands(Loc, LHS, RHS); 10607 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10608 // usage of the logical operators && and || with vectors in C. This 10609 // check could be notionally dropped. 10610 if (!getLangOpts().CPlusPlus && 10611 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10612 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10613 10614 return GetSignedVectorType(LHS.get()->getType()); 10615 } 10616 10617 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10618 SourceLocation Loc, 10619 BinaryOperatorKind Opc) { 10620 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10621 10622 bool IsCompAssign = 10623 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10624 10625 if (LHS.get()->getType()->isVectorType() || 10626 RHS.get()->getType()->isVectorType()) { 10627 if (LHS.get()->getType()->hasIntegerRepresentation() && 10628 RHS.get()->getType()->hasIntegerRepresentation()) 10629 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10630 /*AllowBothBool*/true, 10631 /*AllowBoolConversions*/getLangOpts().ZVector); 10632 return InvalidOperands(Loc, LHS, RHS); 10633 } 10634 10635 if (Opc == BO_And) 10636 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10637 10638 ExprResult LHSResult = LHS, RHSResult = RHS; 10639 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10640 IsCompAssign); 10641 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10642 return QualType(); 10643 LHS = LHSResult.get(); 10644 RHS = RHSResult.get(); 10645 10646 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10647 return compType; 10648 return InvalidOperands(Loc, LHS, RHS); 10649 } 10650 10651 // C99 6.5.[13,14] 10652 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10653 SourceLocation Loc, 10654 BinaryOperatorKind Opc) { 10655 // Check vector operands differently. 10656 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10657 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10658 10659 // Diagnose cases where the user write a logical and/or but probably meant a 10660 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10661 // is a constant. 10662 if (LHS.get()->getType()->isIntegerType() && 10663 !LHS.get()->getType()->isBooleanType() && 10664 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10665 // Don't warn in macros or template instantiations. 10666 !Loc.isMacroID() && !inTemplateInstantiation()) { 10667 // If the RHS can be constant folded, and if it constant folds to something 10668 // that isn't 0 or 1 (which indicate a potential logical operation that 10669 // happened to fold to true/false) then warn. 10670 // Parens on the RHS are ignored. 10671 llvm::APSInt Result; 10672 if (RHS.get()->EvaluateAsInt(Result, Context)) 10673 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10674 !RHS.get()->getExprLoc().isMacroID()) || 10675 (Result != 0 && Result != 1)) { 10676 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10677 << RHS.get()->getSourceRange() 10678 << (Opc == BO_LAnd ? "&&" : "||"); 10679 // Suggest replacing the logical operator with the bitwise version 10680 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10681 << (Opc == BO_LAnd ? "&" : "|") 10682 << FixItHint::CreateReplacement(SourceRange( 10683 Loc, getLocForEndOfToken(Loc)), 10684 Opc == BO_LAnd ? "&" : "|"); 10685 if (Opc == BO_LAnd) 10686 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10687 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10688 << FixItHint::CreateRemoval( 10689 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10690 RHS.get()->getEndLoc())); 10691 } 10692 } 10693 10694 if (!Context.getLangOpts().CPlusPlus) { 10695 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10696 // not operate on the built-in scalar and vector float types. 10697 if (Context.getLangOpts().OpenCL && 10698 Context.getLangOpts().OpenCLVersion < 120) { 10699 if (LHS.get()->getType()->isFloatingType() || 10700 RHS.get()->getType()->isFloatingType()) 10701 return InvalidOperands(Loc, LHS, RHS); 10702 } 10703 10704 LHS = UsualUnaryConversions(LHS.get()); 10705 if (LHS.isInvalid()) 10706 return QualType(); 10707 10708 RHS = UsualUnaryConversions(RHS.get()); 10709 if (RHS.isInvalid()) 10710 return QualType(); 10711 10712 if (!LHS.get()->getType()->isScalarType() || 10713 !RHS.get()->getType()->isScalarType()) 10714 return InvalidOperands(Loc, LHS, RHS); 10715 10716 return Context.IntTy; 10717 } 10718 10719 // The following is safe because we only use this method for 10720 // non-overloadable operands. 10721 10722 // C++ [expr.log.and]p1 10723 // C++ [expr.log.or]p1 10724 // The operands are both contextually converted to type bool. 10725 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10726 if (LHSRes.isInvalid()) 10727 return InvalidOperands(Loc, LHS, RHS); 10728 LHS = LHSRes; 10729 10730 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10731 if (RHSRes.isInvalid()) 10732 return InvalidOperands(Loc, LHS, RHS); 10733 RHS = RHSRes; 10734 10735 // C++ [expr.log.and]p2 10736 // C++ [expr.log.or]p2 10737 // The result is a bool. 10738 return Context.BoolTy; 10739 } 10740 10741 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10742 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10743 if (!ME) return false; 10744 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10745 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10746 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10747 if (!Base) return false; 10748 return Base->getMethodDecl() != nullptr; 10749 } 10750 10751 /// Is the given expression (which must be 'const') a reference to a 10752 /// variable which was originally non-const, but which has become 10753 /// 'const' due to being captured within a block? 10754 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10755 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10756 assert(E->isLValue() && E->getType().isConstQualified()); 10757 E = E->IgnoreParens(); 10758 10759 // Must be a reference to a declaration from an enclosing scope. 10760 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10761 if (!DRE) return NCCK_None; 10762 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10763 10764 // The declaration must be a variable which is not declared 'const'. 10765 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10766 if (!var) return NCCK_None; 10767 if (var->getType().isConstQualified()) return NCCK_None; 10768 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10769 10770 // Decide whether the first capture was for a block or a lambda. 10771 DeclContext *DC = S.CurContext, *Prev = nullptr; 10772 // Decide whether the first capture was for a block or a lambda. 10773 while (DC) { 10774 // For init-capture, it is possible that the variable belongs to the 10775 // template pattern of the current context. 10776 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10777 if (var->isInitCapture() && 10778 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10779 break; 10780 if (DC == var->getDeclContext()) 10781 break; 10782 Prev = DC; 10783 DC = DC->getParent(); 10784 } 10785 // Unless we have an init-capture, we've gone one step too far. 10786 if (!var->isInitCapture()) 10787 DC = Prev; 10788 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10789 } 10790 10791 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10792 Ty = Ty.getNonReferenceType(); 10793 if (IsDereference && Ty->isPointerType()) 10794 Ty = Ty->getPointeeType(); 10795 return !Ty.isConstQualified(); 10796 } 10797 10798 // Update err_typecheck_assign_const and note_typecheck_assign_const 10799 // when this enum is changed. 10800 enum { 10801 ConstFunction, 10802 ConstVariable, 10803 ConstMember, 10804 ConstMethod, 10805 NestedConstMember, 10806 ConstUnknown, // Keep as last element 10807 }; 10808 10809 /// Emit the "read-only variable not assignable" error and print notes to give 10810 /// more information about why the variable is not assignable, such as pointing 10811 /// to the declaration of a const variable, showing that a method is const, or 10812 /// that the function is returning a const reference. 10813 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10814 SourceLocation Loc) { 10815 SourceRange ExprRange = E->getSourceRange(); 10816 10817 // Only emit one error on the first const found. All other consts will emit 10818 // a note to the error. 10819 bool DiagnosticEmitted = false; 10820 10821 // Track if the current expression is the result of a dereference, and if the 10822 // next checked expression is the result of a dereference. 10823 bool IsDereference = false; 10824 bool NextIsDereference = false; 10825 10826 // Loop to process MemberExpr chains. 10827 while (true) { 10828 IsDereference = NextIsDereference; 10829 10830 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10831 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10832 NextIsDereference = ME->isArrow(); 10833 const ValueDecl *VD = ME->getMemberDecl(); 10834 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10835 // Mutable fields can be modified even if the class is const. 10836 if (Field->isMutable()) { 10837 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10838 break; 10839 } 10840 10841 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10842 if (!DiagnosticEmitted) { 10843 S.Diag(Loc, diag::err_typecheck_assign_const) 10844 << ExprRange << ConstMember << false /*static*/ << Field 10845 << Field->getType(); 10846 DiagnosticEmitted = true; 10847 } 10848 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10849 << ConstMember << false /*static*/ << Field << Field->getType() 10850 << Field->getSourceRange(); 10851 } 10852 E = ME->getBase(); 10853 continue; 10854 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10855 if (VDecl->getType().isConstQualified()) { 10856 if (!DiagnosticEmitted) { 10857 S.Diag(Loc, diag::err_typecheck_assign_const) 10858 << ExprRange << ConstMember << true /*static*/ << VDecl 10859 << VDecl->getType(); 10860 DiagnosticEmitted = true; 10861 } 10862 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10863 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10864 << VDecl->getSourceRange(); 10865 } 10866 // Static fields do not inherit constness from parents. 10867 break; 10868 } 10869 break; // End MemberExpr 10870 } else if (const ArraySubscriptExpr *ASE = 10871 dyn_cast<ArraySubscriptExpr>(E)) { 10872 E = ASE->getBase()->IgnoreParenImpCasts(); 10873 continue; 10874 } else if (const ExtVectorElementExpr *EVE = 10875 dyn_cast<ExtVectorElementExpr>(E)) { 10876 E = EVE->getBase()->IgnoreParenImpCasts(); 10877 continue; 10878 } 10879 break; 10880 } 10881 10882 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10883 // Function calls 10884 const FunctionDecl *FD = CE->getDirectCallee(); 10885 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10886 if (!DiagnosticEmitted) { 10887 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10888 << ConstFunction << FD; 10889 DiagnosticEmitted = true; 10890 } 10891 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10892 diag::note_typecheck_assign_const) 10893 << ConstFunction << FD << FD->getReturnType() 10894 << FD->getReturnTypeSourceRange(); 10895 } 10896 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10897 // Point to variable declaration. 10898 if (const ValueDecl *VD = DRE->getDecl()) { 10899 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10900 if (!DiagnosticEmitted) { 10901 S.Diag(Loc, diag::err_typecheck_assign_const) 10902 << ExprRange << ConstVariable << VD << VD->getType(); 10903 DiagnosticEmitted = true; 10904 } 10905 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10906 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10907 } 10908 } 10909 } else if (isa<CXXThisExpr>(E)) { 10910 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10912 if (MD->isConst()) { 10913 if (!DiagnosticEmitted) { 10914 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10915 << ConstMethod << MD; 10916 DiagnosticEmitted = true; 10917 } 10918 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10919 << ConstMethod << MD << MD->getSourceRange(); 10920 } 10921 } 10922 } 10923 } 10924 10925 if (DiagnosticEmitted) 10926 return; 10927 10928 // Can't determine a more specific message, so display the generic error. 10929 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10930 } 10931 10932 enum OriginalExprKind { 10933 OEK_Variable, 10934 OEK_Member, 10935 OEK_LValue 10936 }; 10937 10938 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10939 const RecordType *Ty, 10940 SourceLocation Loc, SourceRange Range, 10941 OriginalExprKind OEK, 10942 bool &DiagnosticEmitted, 10943 bool IsNested = false) { 10944 // We walk the record hierarchy breadth-first to ensure that we print 10945 // diagnostics in field nesting order. 10946 // First, check every field for constness. 10947 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10948 if (Field->getType().isConstQualified()) { 10949 if (!DiagnosticEmitted) { 10950 S.Diag(Loc, diag::err_typecheck_assign_const) 10951 << Range << NestedConstMember << OEK << VD 10952 << IsNested << Field; 10953 DiagnosticEmitted = true; 10954 } 10955 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10956 << NestedConstMember << IsNested << Field 10957 << Field->getType() << Field->getSourceRange(); 10958 } 10959 } 10960 // Then, recurse. 10961 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10962 QualType FTy = Field->getType(); 10963 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10964 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10965 OEK, DiagnosticEmitted, true); 10966 } 10967 } 10968 10969 /// Emit an error for the case where a record we are trying to assign to has a 10970 /// const-qualified field somewhere in its hierarchy. 10971 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10972 SourceLocation Loc) { 10973 QualType Ty = E->getType(); 10974 assert(Ty->isRecordType() && "lvalue was not record?"); 10975 SourceRange Range = E->getSourceRange(); 10976 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10977 bool DiagEmitted = false; 10978 10979 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10980 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10981 Range, OEK_Member, DiagEmitted); 10982 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10983 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10984 Range, OEK_Variable, DiagEmitted); 10985 else 10986 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10987 Range, OEK_LValue, DiagEmitted); 10988 if (!DiagEmitted) 10989 DiagnoseConstAssignment(S, E, Loc); 10990 } 10991 10992 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10993 /// emit an error and return true. If so, return false. 10994 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10995 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10996 10997 S.CheckShadowingDeclModification(E, Loc); 10998 10999 SourceLocation OrigLoc = Loc; 11000 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11001 &Loc); 11002 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11003 IsLV = Expr::MLV_InvalidMessageExpression; 11004 if (IsLV == Expr::MLV_Valid) 11005 return false; 11006 11007 unsigned DiagID = 0; 11008 bool NeedType = false; 11009 switch (IsLV) { // C99 6.5.16p2 11010 case Expr::MLV_ConstQualified: 11011 // Use a specialized diagnostic when we're assigning to an object 11012 // from an enclosing function or block. 11013 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11014 if (NCCK == NCCK_Block) 11015 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11016 else 11017 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11018 break; 11019 } 11020 11021 // In ARC, use some specialized diagnostics for occasions where we 11022 // infer 'const'. These are always pseudo-strong variables. 11023 if (S.getLangOpts().ObjCAutoRefCount) { 11024 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11025 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11026 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11027 11028 // Use the normal diagnostic if it's pseudo-__strong but the 11029 // user actually wrote 'const'. 11030 if (var->isARCPseudoStrong() && 11031 (!var->getTypeSourceInfo() || 11032 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11033 // There are two pseudo-strong cases: 11034 // - self 11035 ObjCMethodDecl *method = S.getCurMethodDecl(); 11036 if (method && var == method->getSelfDecl()) 11037 DiagID = method->isClassMethod() 11038 ? diag::err_typecheck_arc_assign_self_class_method 11039 : diag::err_typecheck_arc_assign_self; 11040 11041 // - fast enumeration variables 11042 else 11043 DiagID = diag::err_typecheck_arr_assign_enumeration; 11044 11045 SourceRange Assign; 11046 if (Loc != OrigLoc) 11047 Assign = SourceRange(OrigLoc, OrigLoc); 11048 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11049 // We need to preserve the AST regardless, so migration tool 11050 // can do its job. 11051 return false; 11052 } 11053 } 11054 } 11055 11056 // If none of the special cases above are triggered, then this is a 11057 // simple const assignment. 11058 if (DiagID == 0) { 11059 DiagnoseConstAssignment(S, E, Loc); 11060 return true; 11061 } 11062 11063 break; 11064 case Expr::MLV_ConstAddrSpace: 11065 DiagnoseConstAssignment(S, E, Loc); 11066 return true; 11067 case Expr::MLV_ConstQualifiedField: 11068 DiagnoseRecursiveConstFields(S, E, Loc); 11069 return true; 11070 case Expr::MLV_ArrayType: 11071 case Expr::MLV_ArrayTemporary: 11072 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11073 NeedType = true; 11074 break; 11075 case Expr::MLV_NotObjectType: 11076 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11077 NeedType = true; 11078 break; 11079 case Expr::MLV_LValueCast: 11080 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11081 break; 11082 case Expr::MLV_Valid: 11083 llvm_unreachable("did not take early return for MLV_Valid"); 11084 case Expr::MLV_InvalidExpression: 11085 case Expr::MLV_MemberFunction: 11086 case Expr::MLV_ClassTemporary: 11087 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11088 break; 11089 case Expr::MLV_IncompleteType: 11090 case Expr::MLV_IncompleteVoidType: 11091 return S.RequireCompleteType(Loc, E->getType(), 11092 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11093 case Expr::MLV_DuplicateVectorComponents: 11094 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11095 break; 11096 case Expr::MLV_NoSetterProperty: 11097 llvm_unreachable("readonly properties should be processed differently"); 11098 case Expr::MLV_InvalidMessageExpression: 11099 DiagID = diag::err_readonly_message_assignment; 11100 break; 11101 case Expr::MLV_SubObjCPropertySetting: 11102 DiagID = diag::err_no_subobject_property_setting; 11103 break; 11104 } 11105 11106 SourceRange Assign; 11107 if (Loc != OrigLoc) 11108 Assign = SourceRange(OrigLoc, OrigLoc); 11109 if (NeedType) 11110 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11111 else 11112 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11113 return true; 11114 } 11115 11116 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11117 SourceLocation Loc, 11118 Sema &Sema) { 11119 if (Sema.inTemplateInstantiation()) 11120 return; 11121 if (Sema.isUnevaluatedContext()) 11122 return; 11123 if (Loc.isInvalid() || Loc.isMacroID()) 11124 return; 11125 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11126 return; 11127 11128 // C / C++ fields 11129 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11130 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11131 if (ML && MR) { 11132 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11133 return; 11134 const ValueDecl *LHSDecl = 11135 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11136 const ValueDecl *RHSDecl = 11137 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11138 if (LHSDecl != RHSDecl) 11139 return; 11140 if (LHSDecl->getType().isVolatileQualified()) 11141 return; 11142 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11143 if (RefTy->getPointeeType().isVolatileQualified()) 11144 return; 11145 11146 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11147 } 11148 11149 // Objective-C instance variables 11150 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11151 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11152 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11153 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11154 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11155 if (RL && RR && RL->getDecl() == RR->getDecl()) 11156 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11157 } 11158 } 11159 11160 // C99 6.5.16.1 11161 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11162 SourceLocation Loc, 11163 QualType CompoundType) { 11164 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11165 11166 // Verify that LHS is a modifiable lvalue, and emit error if not. 11167 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11168 return QualType(); 11169 11170 QualType LHSType = LHSExpr->getType(); 11171 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11172 CompoundType; 11173 // OpenCL v1.2 s6.1.1.1 p2: 11174 // The half data type can only be used to declare a pointer to a buffer that 11175 // contains half values 11176 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11177 LHSType->isHalfType()) { 11178 Diag(Loc, diag::err_opencl_half_load_store) << 1 11179 << LHSType.getUnqualifiedType(); 11180 return QualType(); 11181 } 11182 11183 AssignConvertType ConvTy; 11184 if (CompoundType.isNull()) { 11185 Expr *RHSCheck = RHS.get(); 11186 11187 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11188 11189 QualType LHSTy(LHSType); 11190 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11191 if (RHS.isInvalid()) 11192 return QualType(); 11193 // Special case of NSObject attributes on c-style pointer types. 11194 if (ConvTy == IncompatiblePointer && 11195 ((Context.isObjCNSObjectType(LHSType) && 11196 RHSType->isObjCObjectPointerType()) || 11197 (Context.isObjCNSObjectType(RHSType) && 11198 LHSType->isObjCObjectPointerType()))) 11199 ConvTy = Compatible; 11200 11201 if (ConvTy == Compatible && 11202 LHSType->isObjCObjectType()) 11203 Diag(Loc, diag::err_objc_object_assignment) 11204 << LHSType; 11205 11206 // If the RHS is a unary plus or minus, check to see if they = and + are 11207 // right next to each other. If so, the user may have typo'd "x =+ 4" 11208 // instead of "x += 4". 11209 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11210 RHSCheck = ICE->getSubExpr(); 11211 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11212 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11213 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11214 // Only if the two operators are exactly adjacent. 11215 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11216 // And there is a space or other character before the subexpr of the 11217 // unary +/-. We don't want to warn on "x=-1". 11218 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11219 UO->getSubExpr()->getBeginLoc().isFileID()) { 11220 Diag(Loc, diag::warn_not_compound_assign) 11221 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11222 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11223 } 11224 } 11225 11226 if (ConvTy == Compatible) { 11227 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11228 // Warn about retain cycles where a block captures the LHS, but 11229 // not if the LHS is a simple variable into which the block is 11230 // being stored...unless that variable can be captured by reference! 11231 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11232 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11233 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11234 checkRetainCycles(LHSExpr, RHS.get()); 11235 } 11236 11237 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11238 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11239 // It is safe to assign a weak reference into a strong variable. 11240 // Although this code can still have problems: 11241 // id x = self.weakProp; 11242 // id y = self.weakProp; 11243 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11244 // paths through the function. This should be revisited if 11245 // -Wrepeated-use-of-weak is made flow-sensitive. 11246 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11247 // variable, which will be valid for the current autorelease scope. 11248 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11249 RHS.get()->getBeginLoc())) 11250 getCurFunction()->markSafeWeakUse(RHS.get()); 11251 11252 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11253 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11254 } 11255 } 11256 } else { 11257 // Compound assignment "x += y" 11258 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11259 } 11260 11261 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11262 RHS.get(), AA_Assigning)) 11263 return QualType(); 11264 11265 CheckForNullPointerDereference(*this, LHSExpr); 11266 11267 // C99 6.5.16p3: The type of an assignment expression is the type of the 11268 // left operand unless the left operand has qualified type, in which case 11269 // it is the unqualified version of the type of the left operand. 11270 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11271 // is converted to the type of the assignment expression (above). 11272 // C++ 5.17p1: the type of the assignment expression is that of its left 11273 // operand. 11274 return (getLangOpts().CPlusPlus 11275 ? LHSType : LHSType.getUnqualifiedType()); 11276 } 11277 11278 // Only ignore explicit casts to void. 11279 static bool IgnoreCommaOperand(const Expr *E) { 11280 E = E->IgnoreParens(); 11281 11282 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11283 if (CE->getCastKind() == CK_ToVoid) { 11284 return true; 11285 } 11286 11287 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11288 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11289 CE->getSubExpr()->getType()->isDependentType()) { 11290 return true; 11291 } 11292 } 11293 11294 return false; 11295 } 11296 11297 // Look for instances where it is likely the comma operator is confused with 11298 // another operator. There is a whitelist of acceptable expressions for the 11299 // left hand side of the comma operator, otherwise emit a warning. 11300 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11301 // No warnings in macros 11302 if (Loc.isMacroID()) 11303 return; 11304 11305 // Don't warn in template instantiations. 11306 if (inTemplateInstantiation()) 11307 return; 11308 11309 // Scope isn't fine-grained enough to whitelist the specific cases, so 11310 // instead, skip more than needed, then call back into here with the 11311 // CommaVisitor in SemaStmt.cpp. 11312 // The whitelisted locations are the initialization and increment portions 11313 // of a for loop. The additional checks are on the condition of 11314 // if statements, do/while loops, and for loops. 11315 // Differences in scope flags for C89 mode requires the extra logic. 11316 const unsigned ForIncrementFlags = 11317 getLangOpts().C99 || getLangOpts().CPlusPlus 11318 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11319 : Scope::ContinueScope | Scope::BreakScope; 11320 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11321 const unsigned ScopeFlags = getCurScope()->getFlags(); 11322 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11323 (ScopeFlags & ForInitFlags) == ForInitFlags) 11324 return; 11325 11326 // If there are multiple comma operators used together, get the RHS of the 11327 // of the comma operator as the LHS. 11328 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11329 if (BO->getOpcode() != BO_Comma) 11330 break; 11331 LHS = BO->getRHS(); 11332 } 11333 11334 // Only allow some expressions on LHS to not warn. 11335 if (IgnoreCommaOperand(LHS)) 11336 return; 11337 11338 Diag(Loc, diag::warn_comma_operator); 11339 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11340 << LHS->getSourceRange() 11341 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11342 LangOpts.CPlusPlus ? "static_cast<void>(" 11343 : "(void)(") 11344 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11345 ")"); 11346 } 11347 11348 // C99 6.5.17 11349 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11350 SourceLocation Loc) { 11351 LHS = S.CheckPlaceholderExpr(LHS.get()); 11352 RHS = S.CheckPlaceholderExpr(RHS.get()); 11353 if (LHS.isInvalid() || RHS.isInvalid()) 11354 return QualType(); 11355 11356 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11357 // operands, but not unary promotions. 11358 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11359 11360 // So we treat the LHS as a ignored value, and in C++ we allow the 11361 // containing site to determine what should be done with the RHS. 11362 LHS = S.IgnoredValueConversions(LHS.get()); 11363 if (LHS.isInvalid()) 11364 return QualType(); 11365 11366 S.DiagnoseUnusedExprResult(LHS.get()); 11367 11368 if (!S.getLangOpts().CPlusPlus) { 11369 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11370 if (RHS.isInvalid()) 11371 return QualType(); 11372 if (!RHS.get()->getType()->isVoidType()) 11373 S.RequireCompleteType(Loc, RHS.get()->getType(), 11374 diag::err_incomplete_type); 11375 } 11376 11377 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11378 S.DiagnoseCommaOperator(LHS.get(), Loc); 11379 11380 return RHS.get()->getType(); 11381 } 11382 11383 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11384 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11385 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11386 ExprValueKind &VK, 11387 ExprObjectKind &OK, 11388 SourceLocation OpLoc, 11389 bool IsInc, bool IsPrefix) { 11390 if (Op->isTypeDependent()) 11391 return S.Context.DependentTy; 11392 11393 QualType ResType = Op->getType(); 11394 // Atomic types can be used for increment / decrement where the non-atomic 11395 // versions can, so ignore the _Atomic() specifier for the purpose of 11396 // checking. 11397 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11398 ResType = ResAtomicType->getValueType(); 11399 11400 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11401 11402 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11403 // Decrement of bool is not allowed. 11404 if (!IsInc) { 11405 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11406 return QualType(); 11407 } 11408 // Increment of bool sets it to true, but is deprecated. 11409 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11410 : diag::warn_increment_bool) 11411 << Op->getSourceRange(); 11412 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11413 // Error on enum increments and decrements in C++ mode 11414 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11415 return QualType(); 11416 } else if (ResType->isRealType()) { 11417 // OK! 11418 } else if (ResType->isPointerType()) { 11419 // C99 6.5.2.4p2, 6.5.6p2 11420 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11421 return QualType(); 11422 } else if (ResType->isObjCObjectPointerType()) { 11423 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11424 // Otherwise, we just need a complete type. 11425 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11426 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11427 return QualType(); 11428 } else if (ResType->isAnyComplexType()) { 11429 // C99 does not support ++/-- on complex types, we allow as an extension. 11430 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11431 << ResType << Op->getSourceRange(); 11432 } else if (ResType->isPlaceholderType()) { 11433 ExprResult PR = S.CheckPlaceholderExpr(Op); 11434 if (PR.isInvalid()) return QualType(); 11435 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11436 IsInc, IsPrefix); 11437 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11438 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11439 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11440 (ResType->getAs<VectorType>()->getVectorKind() != 11441 VectorType::AltiVecBool)) { 11442 // The z vector extensions allow ++ and -- for non-bool vectors. 11443 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11444 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11445 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11446 } else { 11447 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11448 << ResType << int(IsInc) << Op->getSourceRange(); 11449 return QualType(); 11450 } 11451 // At this point, we know we have a real, complex or pointer type. 11452 // Now make sure the operand is a modifiable lvalue. 11453 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11454 return QualType(); 11455 // In C++, a prefix increment is the same type as the operand. Otherwise 11456 // (in C or with postfix), the increment is the unqualified type of the 11457 // operand. 11458 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11459 VK = VK_LValue; 11460 OK = Op->getObjectKind(); 11461 return ResType; 11462 } else { 11463 VK = VK_RValue; 11464 return ResType.getUnqualifiedType(); 11465 } 11466 } 11467 11468 11469 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11470 /// This routine allows us to typecheck complex/recursive expressions 11471 /// where the declaration is needed for type checking. We only need to 11472 /// handle cases when the expression references a function designator 11473 /// or is an lvalue. Here are some examples: 11474 /// - &(x) => x 11475 /// - &*****f => f for f a function designator. 11476 /// - &s.xx => s 11477 /// - &s.zz[1].yy -> s, if zz is an array 11478 /// - *(x + 1) -> x, if x is an array 11479 /// - &"123"[2] -> 0 11480 /// - & __real__ x -> x 11481 static ValueDecl *getPrimaryDecl(Expr *E) { 11482 switch (E->getStmtClass()) { 11483 case Stmt::DeclRefExprClass: 11484 return cast<DeclRefExpr>(E)->getDecl(); 11485 case Stmt::MemberExprClass: 11486 // If this is an arrow operator, the address is an offset from 11487 // the base's value, so the object the base refers to is 11488 // irrelevant. 11489 if (cast<MemberExpr>(E)->isArrow()) 11490 return nullptr; 11491 // Otherwise, the expression refers to a part of the base 11492 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11493 case Stmt::ArraySubscriptExprClass: { 11494 // FIXME: This code shouldn't be necessary! We should catch the implicit 11495 // promotion of register arrays earlier. 11496 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11497 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11498 if (ICE->getSubExpr()->getType()->isArrayType()) 11499 return getPrimaryDecl(ICE->getSubExpr()); 11500 } 11501 return nullptr; 11502 } 11503 case Stmt::UnaryOperatorClass: { 11504 UnaryOperator *UO = cast<UnaryOperator>(E); 11505 11506 switch(UO->getOpcode()) { 11507 case UO_Real: 11508 case UO_Imag: 11509 case UO_Extension: 11510 return getPrimaryDecl(UO->getSubExpr()); 11511 default: 11512 return nullptr; 11513 } 11514 } 11515 case Stmt::ParenExprClass: 11516 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11517 case Stmt::ImplicitCastExprClass: 11518 // If the result of an implicit cast is an l-value, we care about 11519 // the sub-expression; otherwise, the result here doesn't matter. 11520 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11521 default: 11522 return nullptr; 11523 } 11524 } 11525 11526 namespace { 11527 enum { 11528 AO_Bit_Field = 0, 11529 AO_Vector_Element = 1, 11530 AO_Property_Expansion = 2, 11531 AO_Register_Variable = 3, 11532 AO_No_Error = 4 11533 }; 11534 } 11535 /// Diagnose invalid operand for address of operations. 11536 /// 11537 /// \param Type The type of operand which cannot have its address taken. 11538 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11539 Expr *E, unsigned Type) { 11540 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11541 } 11542 11543 /// CheckAddressOfOperand - The operand of & must be either a function 11544 /// designator or an lvalue designating an object. If it is an lvalue, the 11545 /// object cannot be declared with storage class register or be a bit field. 11546 /// Note: The usual conversions are *not* applied to the operand of the & 11547 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11548 /// In C++, the operand might be an overloaded function name, in which case 11549 /// we allow the '&' but retain the overloaded-function type. 11550 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11551 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11552 if (PTy->getKind() == BuiltinType::Overload) { 11553 Expr *E = OrigOp.get()->IgnoreParens(); 11554 if (!isa<OverloadExpr>(E)) { 11555 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11556 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11557 << OrigOp.get()->getSourceRange(); 11558 return QualType(); 11559 } 11560 11561 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11562 if (isa<UnresolvedMemberExpr>(Ovl)) 11563 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11564 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11565 << OrigOp.get()->getSourceRange(); 11566 return QualType(); 11567 } 11568 11569 return Context.OverloadTy; 11570 } 11571 11572 if (PTy->getKind() == BuiltinType::UnknownAny) 11573 return Context.UnknownAnyTy; 11574 11575 if (PTy->getKind() == BuiltinType::BoundMember) { 11576 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11577 << OrigOp.get()->getSourceRange(); 11578 return QualType(); 11579 } 11580 11581 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11582 if (OrigOp.isInvalid()) return QualType(); 11583 } 11584 11585 if (OrigOp.get()->isTypeDependent()) 11586 return Context.DependentTy; 11587 11588 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11589 11590 // Make sure to ignore parentheses in subsequent checks 11591 Expr *op = OrigOp.get()->IgnoreParens(); 11592 11593 // In OpenCL captures for blocks called as lambda functions 11594 // are located in the private address space. Blocks used in 11595 // enqueue_kernel can be located in a different address space 11596 // depending on a vendor implementation. Thus preventing 11597 // taking an address of the capture to avoid invalid AS casts. 11598 if (LangOpts.OpenCL) { 11599 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11600 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11601 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11602 return QualType(); 11603 } 11604 } 11605 11606 if (getLangOpts().C99) { 11607 // Implement C99-only parts of addressof rules. 11608 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11609 if (uOp->getOpcode() == UO_Deref) 11610 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11611 // (assuming the deref expression is valid). 11612 return uOp->getSubExpr()->getType(); 11613 } 11614 // Technically, there should be a check for array subscript 11615 // expressions here, but the result of one is always an lvalue anyway. 11616 } 11617 ValueDecl *dcl = getPrimaryDecl(op); 11618 11619 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11620 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11621 op->getBeginLoc())) 11622 return QualType(); 11623 11624 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11625 unsigned AddressOfError = AO_No_Error; 11626 11627 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11628 bool sfinae = (bool)isSFINAEContext(); 11629 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11630 : diag::ext_typecheck_addrof_temporary) 11631 << op->getType() << op->getSourceRange(); 11632 if (sfinae) 11633 return QualType(); 11634 // Materialize the temporary as an lvalue so that we can take its address. 11635 OrigOp = op = 11636 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11637 } else if (isa<ObjCSelectorExpr>(op)) { 11638 return Context.getPointerType(op->getType()); 11639 } else if (lval == Expr::LV_MemberFunction) { 11640 // If it's an instance method, make a member pointer. 11641 // The expression must have exactly the form &A::foo. 11642 11643 // If the underlying expression isn't a decl ref, give up. 11644 if (!isa<DeclRefExpr>(op)) { 11645 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11646 << OrigOp.get()->getSourceRange(); 11647 return QualType(); 11648 } 11649 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11650 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11651 11652 // The id-expression was parenthesized. 11653 if (OrigOp.get() != DRE) { 11654 Diag(OpLoc, diag::err_parens_pointer_member_function) 11655 << OrigOp.get()->getSourceRange(); 11656 11657 // The method was named without a qualifier. 11658 } else if (!DRE->getQualifier()) { 11659 if (MD->getParent()->getName().empty()) 11660 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11661 << op->getSourceRange(); 11662 else { 11663 SmallString<32> Str; 11664 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11665 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11666 << op->getSourceRange() 11667 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11668 } 11669 } 11670 11671 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11672 if (isa<CXXDestructorDecl>(MD)) 11673 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11674 11675 QualType MPTy = Context.getMemberPointerType( 11676 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11677 // Under the MS ABI, lock down the inheritance model now. 11678 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11679 (void)isCompleteType(OpLoc, MPTy); 11680 return MPTy; 11681 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11682 // C99 6.5.3.2p1 11683 // The operand must be either an l-value or a function designator 11684 if (!op->getType()->isFunctionType()) { 11685 // Use a special diagnostic for loads from property references. 11686 if (isa<PseudoObjectExpr>(op)) { 11687 AddressOfError = AO_Property_Expansion; 11688 } else { 11689 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11690 << op->getType() << op->getSourceRange(); 11691 return QualType(); 11692 } 11693 } 11694 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11695 // The operand cannot be a bit-field 11696 AddressOfError = AO_Bit_Field; 11697 } else if (op->getObjectKind() == OK_VectorComponent) { 11698 // The operand cannot be an element of a vector 11699 AddressOfError = AO_Vector_Element; 11700 } else if (dcl) { // C99 6.5.3.2p1 11701 // We have an lvalue with a decl. Make sure the decl is not declared 11702 // with the register storage-class specifier. 11703 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11704 // in C++ it is not error to take address of a register 11705 // variable (c++03 7.1.1P3) 11706 if (vd->getStorageClass() == SC_Register && 11707 !getLangOpts().CPlusPlus) { 11708 AddressOfError = AO_Register_Variable; 11709 } 11710 } else if (isa<MSPropertyDecl>(dcl)) { 11711 AddressOfError = AO_Property_Expansion; 11712 } else if (isa<FunctionTemplateDecl>(dcl)) { 11713 return Context.OverloadTy; 11714 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11715 // Okay: we can take the address of a field. 11716 // Could be a pointer to member, though, if there is an explicit 11717 // scope qualifier for the class. 11718 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11719 DeclContext *Ctx = dcl->getDeclContext(); 11720 if (Ctx && Ctx->isRecord()) { 11721 if (dcl->getType()->isReferenceType()) { 11722 Diag(OpLoc, 11723 diag::err_cannot_form_pointer_to_member_of_reference_type) 11724 << dcl->getDeclName() << dcl->getType(); 11725 return QualType(); 11726 } 11727 11728 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11729 Ctx = Ctx->getParent(); 11730 11731 QualType MPTy = Context.getMemberPointerType( 11732 op->getType(), 11733 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11734 // Under the MS ABI, lock down the inheritance model now. 11735 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11736 (void)isCompleteType(OpLoc, MPTy); 11737 return MPTy; 11738 } 11739 } 11740 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11741 !isa<BindingDecl>(dcl)) 11742 llvm_unreachable("Unknown/unexpected decl type"); 11743 } 11744 11745 if (AddressOfError != AO_No_Error) { 11746 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11747 return QualType(); 11748 } 11749 11750 if (lval == Expr::LV_IncompleteVoidType) { 11751 // Taking the address of a void variable is technically illegal, but we 11752 // allow it in cases which are otherwise valid. 11753 // Example: "extern void x; void* y = &x;". 11754 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11755 } 11756 11757 // If the operand has type "type", the result has type "pointer to type". 11758 if (op->getType()->isObjCObjectType()) 11759 return Context.getObjCObjectPointerType(op->getType()); 11760 11761 CheckAddressOfPackedMember(op); 11762 11763 return Context.getPointerType(op->getType()); 11764 } 11765 11766 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11767 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11768 if (!DRE) 11769 return; 11770 const Decl *D = DRE->getDecl(); 11771 if (!D) 11772 return; 11773 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11774 if (!Param) 11775 return; 11776 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11777 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11778 return; 11779 if (FunctionScopeInfo *FD = S.getCurFunction()) 11780 if (!FD->ModifiedNonNullParams.count(Param)) 11781 FD->ModifiedNonNullParams.insert(Param); 11782 } 11783 11784 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11785 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11786 SourceLocation OpLoc) { 11787 if (Op->isTypeDependent()) 11788 return S.Context.DependentTy; 11789 11790 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11791 if (ConvResult.isInvalid()) 11792 return QualType(); 11793 Op = ConvResult.get(); 11794 QualType OpTy = Op->getType(); 11795 QualType Result; 11796 11797 if (isa<CXXReinterpretCastExpr>(Op)) { 11798 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11799 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11800 Op->getSourceRange()); 11801 } 11802 11803 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11804 { 11805 Result = PT->getPointeeType(); 11806 } 11807 else if (const ObjCObjectPointerType *OPT = 11808 OpTy->getAs<ObjCObjectPointerType>()) 11809 Result = OPT->getPointeeType(); 11810 else { 11811 ExprResult PR = S.CheckPlaceholderExpr(Op); 11812 if (PR.isInvalid()) return QualType(); 11813 if (PR.get() != Op) 11814 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11815 } 11816 11817 if (Result.isNull()) { 11818 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11819 << OpTy << Op->getSourceRange(); 11820 return QualType(); 11821 } 11822 11823 // Note that per both C89 and C99, indirection is always legal, even if Result 11824 // is an incomplete type or void. It would be possible to warn about 11825 // dereferencing a void pointer, but it's completely well-defined, and such a 11826 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11827 // for pointers to 'void' but is fine for any other pointer type: 11828 // 11829 // C++ [expr.unary.op]p1: 11830 // [...] the expression to which [the unary * operator] is applied shall 11831 // be a pointer to an object type, or a pointer to a function type 11832 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11833 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11834 << OpTy << Op->getSourceRange(); 11835 11836 // Dereferences are usually l-values... 11837 VK = VK_LValue; 11838 11839 // ...except that certain expressions are never l-values in C. 11840 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11841 VK = VK_RValue; 11842 11843 return Result; 11844 } 11845 11846 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11847 BinaryOperatorKind Opc; 11848 switch (Kind) { 11849 default: llvm_unreachable("Unknown binop!"); 11850 case tok::periodstar: Opc = BO_PtrMemD; break; 11851 case tok::arrowstar: Opc = BO_PtrMemI; break; 11852 case tok::star: Opc = BO_Mul; break; 11853 case tok::slash: Opc = BO_Div; break; 11854 case tok::percent: Opc = BO_Rem; break; 11855 case tok::plus: Opc = BO_Add; break; 11856 case tok::minus: Opc = BO_Sub; break; 11857 case tok::lessless: Opc = BO_Shl; break; 11858 case tok::greatergreater: Opc = BO_Shr; break; 11859 case tok::lessequal: Opc = BO_LE; break; 11860 case tok::less: Opc = BO_LT; break; 11861 case tok::greaterequal: Opc = BO_GE; break; 11862 case tok::greater: Opc = BO_GT; break; 11863 case tok::exclaimequal: Opc = BO_NE; break; 11864 case tok::equalequal: Opc = BO_EQ; break; 11865 case tok::spaceship: Opc = BO_Cmp; break; 11866 case tok::amp: Opc = BO_And; break; 11867 case tok::caret: Opc = BO_Xor; break; 11868 case tok::pipe: Opc = BO_Or; break; 11869 case tok::ampamp: Opc = BO_LAnd; break; 11870 case tok::pipepipe: Opc = BO_LOr; break; 11871 case tok::equal: Opc = BO_Assign; break; 11872 case tok::starequal: Opc = BO_MulAssign; break; 11873 case tok::slashequal: Opc = BO_DivAssign; break; 11874 case tok::percentequal: Opc = BO_RemAssign; break; 11875 case tok::plusequal: Opc = BO_AddAssign; break; 11876 case tok::minusequal: Opc = BO_SubAssign; break; 11877 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11878 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11879 case tok::ampequal: Opc = BO_AndAssign; break; 11880 case tok::caretequal: Opc = BO_XorAssign; break; 11881 case tok::pipeequal: Opc = BO_OrAssign; break; 11882 case tok::comma: Opc = BO_Comma; break; 11883 } 11884 return Opc; 11885 } 11886 11887 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11888 tok::TokenKind Kind) { 11889 UnaryOperatorKind Opc; 11890 switch (Kind) { 11891 default: llvm_unreachable("Unknown unary op!"); 11892 case tok::plusplus: Opc = UO_PreInc; break; 11893 case tok::minusminus: Opc = UO_PreDec; break; 11894 case tok::amp: Opc = UO_AddrOf; break; 11895 case tok::star: Opc = UO_Deref; break; 11896 case tok::plus: Opc = UO_Plus; break; 11897 case tok::minus: Opc = UO_Minus; break; 11898 case tok::tilde: Opc = UO_Not; break; 11899 case tok::exclaim: Opc = UO_LNot; break; 11900 case tok::kw___real: Opc = UO_Real; break; 11901 case tok::kw___imag: Opc = UO_Imag; break; 11902 case tok::kw___extension__: Opc = UO_Extension; break; 11903 } 11904 return Opc; 11905 } 11906 11907 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11908 /// This warning suppressed in the event of macro expansions. 11909 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11910 SourceLocation OpLoc, bool IsBuiltin) { 11911 if (S.inTemplateInstantiation()) 11912 return; 11913 if (S.isUnevaluatedContext()) 11914 return; 11915 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11916 return; 11917 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11918 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11919 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11920 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11921 if (!LHSDeclRef || !RHSDeclRef || 11922 LHSDeclRef->getLocation().isMacroID() || 11923 RHSDeclRef->getLocation().isMacroID()) 11924 return; 11925 const ValueDecl *LHSDecl = 11926 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11927 const ValueDecl *RHSDecl = 11928 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11929 if (LHSDecl != RHSDecl) 11930 return; 11931 if (LHSDecl->getType().isVolatileQualified()) 11932 return; 11933 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11934 if (RefTy->getPointeeType().isVolatileQualified()) 11935 return; 11936 11937 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 11938 : diag::warn_self_assignment_overloaded) 11939 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 11940 << RHSExpr->getSourceRange(); 11941 } 11942 11943 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11944 /// is usually indicative of introspection within the Objective-C pointer. 11945 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11946 SourceLocation OpLoc) { 11947 if (!S.getLangOpts().ObjC1) 11948 return; 11949 11950 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11951 const Expr *LHS = L.get(); 11952 const Expr *RHS = R.get(); 11953 11954 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11955 ObjCPointerExpr = LHS; 11956 OtherExpr = RHS; 11957 } 11958 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11959 ObjCPointerExpr = RHS; 11960 OtherExpr = LHS; 11961 } 11962 11963 // This warning is deliberately made very specific to reduce false 11964 // positives with logic that uses '&' for hashing. This logic mainly 11965 // looks for code trying to introspect into tagged pointers, which 11966 // code should generally never do. 11967 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11968 unsigned Diag = diag::warn_objc_pointer_masking; 11969 // Determine if we are introspecting the result of performSelectorXXX. 11970 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11971 // Special case messages to -performSelector and friends, which 11972 // can return non-pointer values boxed in a pointer value. 11973 // Some clients may wish to silence warnings in this subcase. 11974 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11975 Selector S = ME->getSelector(); 11976 StringRef SelArg0 = S.getNameForSlot(0); 11977 if (SelArg0.startswith("performSelector")) 11978 Diag = diag::warn_objc_pointer_masking_performSelector; 11979 } 11980 11981 S.Diag(OpLoc, Diag) 11982 << ObjCPointerExpr->getSourceRange(); 11983 } 11984 } 11985 11986 static NamedDecl *getDeclFromExpr(Expr *E) { 11987 if (!E) 11988 return nullptr; 11989 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11990 return DRE->getDecl(); 11991 if (auto *ME = dyn_cast<MemberExpr>(E)) 11992 return ME->getMemberDecl(); 11993 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11994 return IRE->getDecl(); 11995 return nullptr; 11996 } 11997 11998 // This helper function promotes a binary operator's operands (which are of a 11999 // half vector type) to a vector of floats and then truncates the result to 12000 // a vector of either half or short. 12001 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12002 BinaryOperatorKind Opc, QualType ResultTy, 12003 ExprValueKind VK, ExprObjectKind OK, 12004 bool IsCompAssign, SourceLocation OpLoc, 12005 FPOptions FPFeatures) { 12006 auto &Context = S.getASTContext(); 12007 assert((isVector(ResultTy, Context.HalfTy) || 12008 isVector(ResultTy, Context.ShortTy)) && 12009 "Result must be a vector of half or short"); 12010 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12011 isVector(RHS.get()->getType(), Context.HalfTy) && 12012 "both operands expected to be a half vector"); 12013 12014 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12015 QualType BinOpResTy = RHS.get()->getType(); 12016 12017 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12018 // change BinOpResTy to a vector of ints. 12019 if (isVector(ResultTy, Context.ShortTy)) 12020 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12021 12022 if (IsCompAssign) 12023 return new (Context) CompoundAssignOperator( 12024 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12025 OpLoc, FPFeatures); 12026 12027 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12028 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12029 VK, OK, OpLoc, FPFeatures); 12030 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12031 } 12032 12033 static std::pair<ExprResult, ExprResult> 12034 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12035 Expr *RHSExpr) { 12036 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12037 if (!S.getLangOpts().CPlusPlus) { 12038 // C cannot handle TypoExpr nodes on either side of a binop because it 12039 // doesn't handle dependent types properly, so make sure any TypoExprs have 12040 // been dealt with before checking the operands. 12041 LHS = S.CorrectDelayedTyposInExpr(LHS); 12042 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12043 if (Opc != BO_Assign) 12044 return ExprResult(E); 12045 // Avoid correcting the RHS to the same Expr as the LHS. 12046 Decl *D = getDeclFromExpr(E); 12047 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12048 }); 12049 } 12050 return std::make_pair(LHS, RHS); 12051 } 12052 12053 /// Returns true if conversion between vectors of halfs and vectors of floats 12054 /// is needed. 12055 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12056 QualType SrcType) { 12057 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12058 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12059 isVector(SrcType, Ctx.HalfTy); 12060 } 12061 12062 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12063 /// operator @p Opc at location @c TokLoc. This routine only supports 12064 /// built-in operations; ActOnBinOp handles overloaded operators. 12065 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12066 BinaryOperatorKind Opc, 12067 Expr *LHSExpr, Expr *RHSExpr) { 12068 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12069 // The syntax only allows initializer lists on the RHS of assignment, 12070 // so we don't need to worry about accepting invalid code for 12071 // non-assignment operators. 12072 // C++11 5.17p9: 12073 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12074 // of x = {} is x = T(). 12075 InitializationKind Kind = InitializationKind::CreateDirectList( 12076 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12077 InitializedEntity Entity = 12078 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12079 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12080 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12081 if (Init.isInvalid()) 12082 return Init; 12083 RHSExpr = Init.get(); 12084 } 12085 12086 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12087 QualType ResultTy; // Result type of the binary operator. 12088 // The following two variables are used for compound assignment operators 12089 QualType CompLHSTy; // Type of LHS after promotions for computation 12090 QualType CompResultTy; // Type of computation result 12091 ExprValueKind VK = VK_RValue; 12092 ExprObjectKind OK = OK_Ordinary; 12093 bool ConvertHalfVec = false; 12094 12095 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12096 if (!LHS.isUsable() || !RHS.isUsable()) 12097 return ExprError(); 12098 12099 if (getLangOpts().OpenCL) { 12100 QualType LHSTy = LHSExpr->getType(); 12101 QualType RHSTy = RHSExpr->getType(); 12102 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12103 // the ATOMIC_VAR_INIT macro. 12104 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12105 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12106 if (BO_Assign == Opc) 12107 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12108 else 12109 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12110 return ExprError(); 12111 } 12112 12113 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12114 // only with a builtin functions and therefore should be disallowed here. 12115 if (LHSTy->isImageType() || RHSTy->isImageType() || 12116 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12117 LHSTy->isPipeType() || RHSTy->isPipeType() || 12118 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12119 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12120 return ExprError(); 12121 } 12122 } 12123 12124 switch (Opc) { 12125 case BO_Assign: 12126 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12127 if (getLangOpts().CPlusPlus && 12128 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12129 VK = LHS.get()->getValueKind(); 12130 OK = LHS.get()->getObjectKind(); 12131 } 12132 if (!ResultTy.isNull()) { 12133 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12134 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12135 } 12136 RecordModifiableNonNullParam(*this, LHS.get()); 12137 break; 12138 case BO_PtrMemD: 12139 case BO_PtrMemI: 12140 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12141 Opc == BO_PtrMemI); 12142 break; 12143 case BO_Mul: 12144 case BO_Div: 12145 ConvertHalfVec = true; 12146 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12147 Opc == BO_Div); 12148 break; 12149 case BO_Rem: 12150 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12151 break; 12152 case BO_Add: 12153 ConvertHalfVec = true; 12154 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12155 break; 12156 case BO_Sub: 12157 ConvertHalfVec = true; 12158 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12159 break; 12160 case BO_Shl: 12161 case BO_Shr: 12162 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12163 break; 12164 case BO_LE: 12165 case BO_LT: 12166 case BO_GE: 12167 case BO_GT: 12168 ConvertHalfVec = true; 12169 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12170 break; 12171 case BO_EQ: 12172 case BO_NE: 12173 ConvertHalfVec = true; 12174 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12175 break; 12176 case BO_Cmp: 12177 ConvertHalfVec = true; 12178 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12179 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12180 break; 12181 case BO_And: 12182 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12183 LLVM_FALLTHROUGH; 12184 case BO_Xor: 12185 case BO_Or: 12186 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12187 break; 12188 case BO_LAnd: 12189 case BO_LOr: 12190 ConvertHalfVec = true; 12191 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12192 break; 12193 case BO_MulAssign: 12194 case BO_DivAssign: 12195 ConvertHalfVec = true; 12196 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12197 Opc == BO_DivAssign); 12198 CompLHSTy = CompResultTy; 12199 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12200 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12201 break; 12202 case BO_RemAssign: 12203 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12204 CompLHSTy = CompResultTy; 12205 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12206 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12207 break; 12208 case BO_AddAssign: 12209 ConvertHalfVec = true; 12210 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12211 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12212 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12213 break; 12214 case BO_SubAssign: 12215 ConvertHalfVec = true; 12216 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12217 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12218 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12219 break; 12220 case BO_ShlAssign: 12221 case BO_ShrAssign: 12222 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12223 CompLHSTy = CompResultTy; 12224 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12225 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12226 break; 12227 case BO_AndAssign: 12228 case BO_OrAssign: // fallthrough 12229 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12230 LLVM_FALLTHROUGH; 12231 case BO_XorAssign: 12232 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12233 CompLHSTy = CompResultTy; 12234 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12235 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12236 break; 12237 case BO_Comma: 12238 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12239 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12240 VK = RHS.get()->getValueKind(); 12241 OK = RHS.get()->getObjectKind(); 12242 } 12243 break; 12244 } 12245 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12246 return ExprError(); 12247 12248 // Some of the binary operations require promoting operands of half vector to 12249 // float vectors and truncating the result back to half vector. For now, we do 12250 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12251 // arm64). 12252 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12253 isVector(LHS.get()->getType(), Context.HalfTy) && 12254 "both sides are half vectors or neither sides are"); 12255 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12256 LHS.get()->getType()); 12257 12258 // Check for array bounds violations for both sides of the BinaryOperator 12259 CheckArrayAccess(LHS.get()); 12260 CheckArrayAccess(RHS.get()); 12261 12262 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12263 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12264 &Context.Idents.get("object_setClass"), 12265 SourceLocation(), LookupOrdinaryName); 12266 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12267 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12268 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12269 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12270 "object_setClass(") 12271 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12272 ",") 12273 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12274 } 12275 else 12276 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12277 } 12278 else if (const ObjCIvarRefExpr *OIRE = 12279 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12280 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12281 12282 // Opc is not a compound assignment if CompResultTy is null. 12283 if (CompResultTy.isNull()) { 12284 if (ConvertHalfVec) 12285 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12286 OpLoc, FPFeatures); 12287 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12288 OK, OpLoc, FPFeatures); 12289 } 12290 12291 // Handle compound assignments. 12292 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12293 OK_ObjCProperty) { 12294 VK = VK_LValue; 12295 OK = LHS.get()->getObjectKind(); 12296 } 12297 12298 if (ConvertHalfVec) 12299 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12300 OpLoc, FPFeatures); 12301 12302 return new (Context) CompoundAssignOperator( 12303 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12304 OpLoc, FPFeatures); 12305 } 12306 12307 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12308 /// operators are mixed in a way that suggests that the programmer forgot that 12309 /// comparison operators have higher precedence. The most typical example of 12310 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12311 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12312 SourceLocation OpLoc, Expr *LHSExpr, 12313 Expr *RHSExpr) { 12314 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12315 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12316 12317 // Check that one of the sides is a comparison operator and the other isn't. 12318 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12319 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12320 if (isLeftComp == isRightComp) 12321 return; 12322 12323 // Bitwise operations are sometimes used as eager logical ops. 12324 // Don't diagnose this. 12325 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12326 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12327 if (isLeftBitwise || isRightBitwise) 12328 return; 12329 12330 SourceRange DiagRange = isLeftComp 12331 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12332 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12333 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12334 SourceRange ParensRange = 12335 isLeftComp 12336 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12337 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12338 12339 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12340 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12341 SuggestParentheses(Self, OpLoc, 12342 Self.PDiag(diag::note_precedence_silence) << OpStr, 12343 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12344 SuggestParentheses(Self, OpLoc, 12345 Self.PDiag(diag::note_precedence_bitwise_first) 12346 << BinaryOperator::getOpcodeStr(Opc), 12347 ParensRange); 12348 } 12349 12350 /// It accepts a '&&' expr that is inside a '||' one. 12351 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12352 /// in parentheses. 12353 static void 12354 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12355 BinaryOperator *Bop) { 12356 assert(Bop->getOpcode() == BO_LAnd); 12357 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12358 << Bop->getSourceRange() << OpLoc; 12359 SuggestParentheses(Self, Bop->getOperatorLoc(), 12360 Self.PDiag(diag::note_precedence_silence) 12361 << Bop->getOpcodeStr(), 12362 Bop->getSourceRange()); 12363 } 12364 12365 /// Returns true if the given expression can be evaluated as a constant 12366 /// 'true'. 12367 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12368 bool Res; 12369 return !E->isValueDependent() && 12370 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12371 } 12372 12373 /// Returns true if the given expression can be evaluated as a constant 12374 /// 'false'. 12375 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12376 bool Res; 12377 return !E->isValueDependent() && 12378 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12379 } 12380 12381 /// Look for '&&' in the left hand of a '||' expr. 12382 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12383 Expr *LHSExpr, Expr *RHSExpr) { 12384 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12385 if (Bop->getOpcode() == BO_LAnd) { 12386 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12387 if (EvaluatesAsFalse(S, RHSExpr)) 12388 return; 12389 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12390 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12391 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12392 } else if (Bop->getOpcode() == BO_LOr) { 12393 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12394 // If it's "a || b && 1 || c" we didn't warn earlier for 12395 // "a || b && 1", but warn now. 12396 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12397 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12398 } 12399 } 12400 } 12401 } 12402 12403 /// Look for '&&' in the right hand of a '||' expr. 12404 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12405 Expr *LHSExpr, Expr *RHSExpr) { 12406 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12407 if (Bop->getOpcode() == BO_LAnd) { 12408 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12409 if (EvaluatesAsFalse(S, LHSExpr)) 12410 return; 12411 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12412 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12413 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12414 } 12415 } 12416 } 12417 12418 /// Look for bitwise op in the left or right hand of a bitwise op with 12419 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12420 /// the '&' expression in parentheses. 12421 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12422 SourceLocation OpLoc, Expr *SubExpr) { 12423 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12424 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12425 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12426 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12427 << Bop->getSourceRange() << OpLoc; 12428 SuggestParentheses(S, Bop->getOperatorLoc(), 12429 S.PDiag(diag::note_precedence_silence) 12430 << Bop->getOpcodeStr(), 12431 Bop->getSourceRange()); 12432 } 12433 } 12434 } 12435 12436 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12437 Expr *SubExpr, StringRef Shift) { 12438 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12439 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12440 StringRef Op = Bop->getOpcodeStr(); 12441 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12442 << Bop->getSourceRange() << OpLoc << Shift << Op; 12443 SuggestParentheses(S, Bop->getOperatorLoc(), 12444 S.PDiag(diag::note_precedence_silence) << Op, 12445 Bop->getSourceRange()); 12446 } 12447 } 12448 } 12449 12450 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12451 Expr *LHSExpr, Expr *RHSExpr) { 12452 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12453 if (!OCE) 12454 return; 12455 12456 FunctionDecl *FD = OCE->getDirectCallee(); 12457 if (!FD || !FD->isOverloadedOperator()) 12458 return; 12459 12460 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12461 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12462 return; 12463 12464 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12465 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12466 << (Kind == OO_LessLess); 12467 SuggestParentheses(S, OCE->getOperatorLoc(), 12468 S.PDiag(diag::note_precedence_silence) 12469 << (Kind == OO_LessLess ? "<<" : ">>"), 12470 OCE->getSourceRange()); 12471 SuggestParentheses( 12472 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12473 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12474 } 12475 12476 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12477 /// precedence. 12478 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12479 SourceLocation OpLoc, Expr *LHSExpr, 12480 Expr *RHSExpr){ 12481 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12482 if (BinaryOperator::isBitwiseOp(Opc)) 12483 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12484 12485 // Diagnose "arg1 & arg2 | arg3" 12486 if ((Opc == BO_Or || Opc == BO_Xor) && 12487 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12488 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12489 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12490 } 12491 12492 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12493 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12494 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12495 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12496 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12497 } 12498 12499 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12500 || Opc == BO_Shr) { 12501 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12502 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12503 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12504 } 12505 12506 // Warn on overloaded shift operators and comparisons, such as: 12507 // cout << 5 == 4; 12508 if (BinaryOperator::isComparisonOp(Opc)) 12509 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12510 } 12511 12512 // Binary Operators. 'Tok' is the token for the operator. 12513 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12514 tok::TokenKind Kind, 12515 Expr *LHSExpr, Expr *RHSExpr) { 12516 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12517 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12518 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12519 12520 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12521 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12522 12523 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12524 } 12525 12526 /// Build an overloaded binary operator expression in the given scope. 12527 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12528 BinaryOperatorKind Opc, 12529 Expr *LHS, Expr *RHS) { 12530 switch (Opc) { 12531 case BO_Assign: 12532 case BO_DivAssign: 12533 case BO_RemAssign: 12534 case BO_SubAssign: 12535 case BO_AndAssign: 12536 case BO_OrAssign: 12537 case BO_XorAssign: 12538 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12539 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12540 break; 12541 default: 12542 break; 12543 } 12544 12545 // Find all of the overloaded operators visible from this 12546 // point. We perform both an operator-name lookup from the local 12547 // scope and an argument-dependent lookup based on the types of 12548 // the arguments. 12549 UnresolvedSet<16> Functions; 12550 OverloadedOperatorKind OverOp 12551 = BinaryOperator::getOverloadedOperator(Opc); 12552 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12553 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12554 RHS->getType(), Functions); 12555 12556 // Build the (potentially-overloaded, potentially-dependent) 12557 // binary operation. 12558 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12559 } 12560 12561 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12562 BinaryOperatorKind Opc, 12563 Expr *LHSExpr, Expr *RHSExpr) { 12564 ExprResult LHS, RHS; 12565 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12566 if (!LHS.isUsable() || !RHS.isUsable()) 12567 return ExprError(); 12568 LHSExpr = LHS.get(); 12569 RHSExpr = RHS.get(); 12570 12571 // We want to end up calling one of checkPseudoObjectAssignment 12572 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12573 // both expressions are overloadable or either is type-dependent), 12574 // or CreateBuiltinBinOp (in any other case). We also want to get 12575 // any placeholder types out of the way. 12576 12577 // Handle pseudo-objects in the LHS. 12578 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12579 // Assignments with a pseudo-object l-value need special analysis. 12580 if (pty->getKind() == BuiltinType::PseudoObject && 12581 BinaryOperator::isAssignmentOp(Opc)) 12582 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12583 12584 // Don't resolve overloads if the other type is overloadable. 12585 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12586 // We can't actually test that if we still have a placeholder, 12587 // though. Fortunately, none of the exceptions we see in that 12588 // code below are valid when the LHS is an overload set. Note 12589 // that an overload set can be dependently-typed, but it never 12590 // instantiates to having an overloadable type. 12591 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12592 if (resolvedRHS.isInvalid()) return ExprError(); 12593 RHSExpr = resolvedRHS.get(); 12594 12595 if (RHSExpr->isTypeDependent() || 12596 RHSExpr->getType()->isOverloadableType()) 12597 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12598 } 12599 12600 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12601 // template, diagnose the missing 'template' keyword instead of diagnosing 12602 // an invalid use of a bound member function. 12603 // 12604 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12605 // to C++1z [over.over]/1.4, but we already checked for that case above. 12606 if (Opc == BO_LT && inTemplateInstantiation() && 12607 (pty->getKind() == BuiltinType::BoundMember || 12608 pty->getKind() == BuiltinType::Overload)) { 12609 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12610 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12611 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12612 return isa<FunctionTemplateDecl>(ND); 12613 })) { 12614 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12615 : OE->getNameLoc(), 12616 diag::err_template_kw_missing) 12617 << OE->getName().getAsString() << ""; 12618 return ExprError(); 12619 } 12620 } 12621 12622 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12623 if (LHS.isInvalid()) return ExprError(); 12624 LHSExpr = LHS.get(); 12625 } 12626 12627 // Handle pseudo-objects in the RHS. 12628 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12629 // An overload in the RHS can potentially be resolved by the type 12630 // being assigned to. 12631 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12632 if (getLangOpts().CPlusPlus && 12633 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12634 LHSExpr->getType()->isOverloadableType())) 12635 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12636 12637 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12638 } 12639 12640 // Don't resolve overloads if the other type is overloadable. 12641 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12642 LHSExpr->getType()->isOverloadableType()) 12643 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12644 12645 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12646 if (!resolvedRHS.isUsable()) return ExprError(); 12647 RHSExpr = resolvedRHS.get(); 12648 } 12649 12650 if (getLangOpts().CPlusPlus) { 12651 // If either expression is type-dependent, always build an 12652 // overloaded op. 12653 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12654 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12655 12656 // Otherwise, build an overloaded op if either expression has an 12657 // overloadable type. 12658 if (LHSExpr->getType()->isOverloadableType() || 12659 RHSExpr->getType()->isOverloadableType()) 12660 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12661 } 12662 12663 // Build a built-in binary operation. 12664 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12665 } 12666 12667 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12668 if (T.isNull() || T->isDependentType()) 12669 return false; 12670 12671 if (!T->isPromotableIntegerType()) 12672 return true; 12673 12674 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12675 } 12676 12677 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12678 UnaryOperatorKind Opc, 12679 Expr *InputExpr) { 12680 ExprResult Input = InputExpr; 12681 ExprValueKind VK = VK_RValue; 12682 ExprObjectKind OK = OK_Ordinary; 12683 QualType resultType; 12684 bool CanOverflow = false; 12685 12686 bool ConvertHalfVec = false; 12687 if (getLangOpts().OpenCL) { 12688 QualType Ty = InputExpr->getType(); 12689 // The only legal unary operation for atomics is '&'. 12690 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12691 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12692 // only with a builtin functions and therefore should be disallowed here. 12693 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12694 || Ty->isBlockPointerType())) { 12695 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12696 << InputExpr->getType() 12697 << Input.get()->getSourceRange()); 12698 } 12699 } 12700 switch (Opc) { 12701 case UO_PreInc: 12702 case UO_PreDec: 12703 case UO_PostInc: 12704 case UO_PostDec: 12705 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12706 OpLoc, 12707 Opc == UO_PreInc || 12708 Opc == UO_PostInc, 12709 Opc == UO_PreInc || 12710 Opc == UO_PreDec); 12711 CanOverflow = isOverflowingIntegerType(Context, resultType); 12712 break; 12713 case UO_AddrOf: 12714 resultType = CheckAddressOfOperand(Input, OpLoc); 12715 RecordModifiableNonNullParam(*this, InputExpr); 12716 break; 12717 case UO_Deref: { 12718 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12719 if (Input.isInvalid()) return ExprError(); 12720 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12721 break; 12722 } 12723 case UO_Plus: 12724 case UO_Minus: 12725 CanOverflow = Opc == UO_Minus && 12726 isOverflowingIntegerType(Context, Input.get()->getType()); 12727 Input = UsualUnaryConversions(Input.get()); 12728 if (Input.isInvalid()) return ExprError(); 12729 // Unary plus and minus require promoting an operand of half vector to a 12730 // float vector and truncating the result back to a half vector. For now, we 12731 // do this only when HalfArgsAndReturns is set (that is, when the target is 12732 // arm or arm64). 12733 ConvertHalfVec = 12734 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12735 12736 // If the operand is a half vector, promote it to a float vector. 12737 if (ConvertHalfVec) 12738 Input = convertVector(Input.get(), Context.FloatTy, *this); 12739 resultType = Input.get()->getType(); 12740 if (resultType->isDependentType()) 12741 break; 12742 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12743 break; 12744 else if (resultType->isVectorType() && 12745 // The z vector extensions don't allow + or - with bool vectors. 12746 (!Context.getLangOpts().ZVector || 12747 resultType->getAs<VectorType>()->getVectorKind() != 12748 VectorType::AltiVecBool)) 12749 break; 12750 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12751 Opc == UO_Plus && 12752 resultType->isPointerType()) 12753 break; 12754 12755 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12756 << resultType << Input.get()->getSourceRange()); 12757 12758 case UO_Not: // bitwise complement 12759 Input = UsualUnaryConversions(Input.get()); 12760 if (Input.isInvalid()) 12761 return ExprError(); 12762 resultType = Input.get()->getType(); 12763 12764 if (resultType->isDependentType()) 12765 break; 12766 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12767 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12768 // C99 does not support '~' for complex conjugation. 12769 Diag(OpLoc, diag::ext_integer_complement_complex) 12770 << resultType << Input.get()->getSourceRange(); 12771 else if (resultType->hasIntegerRepresentation()) 12772 break; 12773 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12774 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12775 // on vector float types. 12776 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12777 if (!T->isIntegerType()) 12778 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12779 << resultType << Input.get()->getSourceRange()); 12780 } else { 12781 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12782 << resultType << Input.get()->getSourceRange()); 12783 } 12784 break; 12785 12786 case UO_LNot: // logical negation 12787 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12788 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12789 if (Input.isInvalid()) return ExprError(); 12790 resultType = Input.get()->getType(); 12791 12792 // Though we still have to promote half FP to float... 12793 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12794 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12795 resultType = Context.FloatTy; 12796 } 12797 12798 if (resultType->isDependentType()) 12799 break; 12800 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12801 // C99 6.5.3.3p1: ok, fallthrough; 12802 if (Context.getLangOpts().CPlusPlus) { 12803 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12804 // operand contextually converted to bool. 12805 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12806 ScalarTypeToBooleanCastKind(resultType)); 12807 } else if (Context.getLangOpts().OpenCL && 12808 Context.getLangOpts().OpenCLVersion < 120) { 12809 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12810 // operate on scalar float types. 12811 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12812 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12813 << resultType << Input.get()->getSourceRange()); 12814 } 12815 } else if (resultType->isExtVectorType()) { 12816 if (Context.getLangOpts().OpenCL && 12817 Context.getLangOpts().OpenCLVersion < 120) { 12818 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12819 // operate on vector float types. 12820 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12821 if (!T->isIntegerType()) 12822 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12823 << resultType << Input.get()->getSourceRange()); 12824 } 12825 // Vector logical not returns the signed variant of the operand type. 12826 resultType = GetSignedVectorType(resultType); 12827 break; 12828 } else { 12829 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12830 // type in C++. We should allow that here too. 12831 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12832 << resultType << Input.get()->getSourceRange()); 12833 } 12834 12835 // LNot always has type int. C99 6.5.3.3p5. 12836 // In C++, it's bool. C++ 5.3.1p8 12837 resultType = Context.getLogicalOperationType(); 12838 break; 12839 case UO_Real: 12840 case UO_Imag: 12841 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12842 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12843 // complex l-values to ordinary l-values and all other values to r-values. 12844 if (Input.isInvalid()) return ExprError(); 12845 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12846 if (Input.get()->getValueKind() != VK_RValue && 12847 Input.get()->getObjectKind() == OK_Ordinary) 12848 VK = Input.get()->getValueKind(); 12849 } else if (!getLangOpts().CPlusPlus) { 12850 // In C, a volatile scalar is read by __imag. In C++, it is not. 12851 Input = DefaultLvalueConversion(Input.get()); 12852 } 12853 break; 12854 case UO_Extension: 12855 resultType = Input.get()->getType(); 12856 VK = Input.get()->getValueKind(); 12857 OK = Input.get()->getObjectKind(); 12858 break; 12859 case UO_Coawait: 12860 // It's unnecessary to represent the pass-through operator co_await in the 12861 // AST; just return the input expression instead. 12862 assert(!Input.get()->getType()->isDependentType() && 12863 "the co_await expression must be non-dependant before " 12864 "building operator co_await"); 12865 return Input; 12866 } 12867 if (resultType.isNull() || Input.isInvalid()) 12868 return ExprError(); 12869 12870 // Check for array bounds violations in the operand of the UnaryOperator, 12871 // except for the '*' and '&' operators that have to be handled specially 12872 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12873 // that are explicitly defined as valid by the standard). 12874 if (Opc != UO_AddrOf && Opc != UO_Deref) 12875 CheckArrayAccess(Input.get()); 12876 12877 auto *UO = new (Context) 12878 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12879 // Convert the result back to a half vector. 12880 if (ConvertHalfVec) 12881 return convertVector(UO, Context.HalfTy, *this); 12882 return UO; 12883 } 12884 12885 /// Determine whether the given expression is a qualified member 12886 /// access expression, of a form that could be turned into a pointer to member 12887 /// with the address-of operator. 12888 bool Sema::isQualifiedMemberAccess(Expr *E) { 12889 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12890 if (!DRE->getQualifier()) 12891 return false; 12892 12893 ValueDecl *VD = DRE->getDecl(); 12894 if (!VD->isCXXClassMember()) 12895 return false; 12896 12897 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12898 return true; 12899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12900 return Method->isInstance(); 12901 12902 return false; 12903 } 12904 12905 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12906 if (!ULE->getQualifier()) 12907 return false; 12908 12909 for (NamedDecl *D : ULE->decls()) { 12910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12911 if (Method->isInstance()) 12912 return true; 12913 } else { 12914 // Overload set does not contain methods. 12915 break; 12916 } 12917 } 12918 12919 return false; 12920 } 12921 12922 return false; 12923 } 12924 12925 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12926 UnaryOperatorKind Opc, Expr *Input) { 12927 // First things first: handle placeholders so that the 12928 // overloaded-operator check considers the right type. 12929 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12930 // Increment and decrement of pseudo-object references. 12931 if (pty->getKind() == BuiltinType::PseudoObject && 12932 UnaryOperator::isIncrementDecrementOp(Opc)) 12933 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12934 12935 // extension is always a builtin operator. 12936 if (Opc == UO_Extension) 12937 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12938 12939 // & gets special logic for several kinds of placeholder. 12940 // The builtin code knows what to do. 12941 if (Opc == UO_AddrOf && 12942 (pty->getKind() == BuiltinType::Overload || 12943 pty->getKind() == BuiltinType::UnknownAny || 12944 pty->getKind() == BuiltinType::BoundMember)) 12945 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12946 12947 // Anything else needs to be handled now. 12948 ExprResult Result = CheckPlaceholderExpr(Input); 12949 if (Result.isInvalid()) return ExprError(); 12950 Input = Result.get(); 12951 } 12952 12953 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12954 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12955 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12956 // Find all of the overloaded operators visible from this 12957 // point. We perform both an operator-name lookup from the local 12958 // scope and an argument-dependent lookup based on the types of 12959 // the arguments. 12960 UnresolvedSet<16> Functions; 12961 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12962 if (S && OverOp != OO_None) 12963 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12964 Functions); 12965 12966 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12967 } 12968 12969 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12970 } 12971 12972 // Unary Operators. 'Tok' is the token for the operator. 12973 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12974 tok::TokenKind Op, Expr *Input) { 12975 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12976 } 12977 12978 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12979 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12980 LabelDecl *TheDecl) { 12981 TheDecl->markUsed(Context); 12982 // Create the AST node. The address of a label always has type 'void*'. 12983 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12984 Context.getPointerType(Context.VoidTy)); 12985 } 12986 12987 /// Given the last statement in a statement-expression, check whether 12988 /// the result is a producing expression (like a call to an 12989 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12990 /// release out of the full-expression. Otherwise, return null. 12991 /// Cannot fail. 12992 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12993 // Should always be wrapped with one of these. 12994 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12995 if (!cleanups) return nullptr; 12996 12997 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12998 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12999 return nullptr; 13000 13001 // Splice out the cast. This shouldn't modify any interesting 13002 // features of the statement. 13003 Expr *producer = cast->getSubExpr(); 13004 assert(producer->getType() == cast->getType()); 13005 assert(producer->getValueKind() == cast->getValueKind()); 13006 cleanups->setSubExpr(producer); 13007 return cleanups; 13008 } 13009 13010 void Sema::ActOnStartStmtExpr() { 13011 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13012 } 13013 13014 void Sema::ActOnStmtExprError() { 13015 // Note that function is also called by TreeTransform when leaving a 13016 // StmtExpr scope without rebuilding anything. 13017 13018 DiscardCleanupsInEvaluationContext(); 13019 PopExpressionEvaluationContext(); 13020 } 13021 13022 ExprResult 13023 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13024 SourceLocation RPLoc) { // "({..})" 13025 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13026 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13027 13028 if (hasAnyUnrecoverableErrorsInThisFunction()) 13029 DiscardCleanupsInEvaluationContext(); 13030 assert(!Cleanup.exprNeedsCleanups() && 13031 "cleanups within StmtExpr not correctly bound!"); 13032 PopExpressionEvaluationContext(); 13033 13034 // FIXME: there are a variety of strange constraints to enforce here, for 13035 // example, it is not possible to goto into a stmt expression apparently. 13036 // More semantic analysis is needed. 13037 13038 // If there are sub-stmts in the compound stmt, take the type of the last one 13039 // as the type of the stmtexpr. 13040 QualType Ty = Context.VoidTy; 13041 bool StmtExprMayBindToTemp = false; 13042 if (!Compound->body_empty()) { 13043 Stmt *LastStmt = Compound->body_back(); 13044 LabelStmt *LastLabelStmt = nullptr; 13045 // If LastStmt is a label, skip down through into the body. 13046 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 13047 LastLabelStmt = Label; 13048 LastStmt = Label->getSubStmt(); 13049 } 13050 13051 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 13052 // Do function/array conversion on the last expression, but not 13053 // lvalue-to-rvalue. However, initialize an unqualified type. 13054 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 13055 if (LastExpr.isInvalid()) 13056 return ExprError(); 13057 Ty = LastExpr.get()->getType().getUnqualifiedType(); 13058 13059 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 13060 // In ARC, if the final expression ends in a consume, splice 13061 // the consume out and bind it later. In the alternate case 13062 // (when dealing with a retainable type), the result 13063 // initialization will create a produce. In both cases the 13064 // result will be +1, and we'll need to balance that out with 13065 // a bind. 13066 if (Expr *rebuiltLastStmt 13067 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 13068 LastExpr = rebuiltLastStmt; 13069 } else { 13070 LastExpr = PerformCopyInitialization( 13071 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 13072 SourceLocation(), LastExpr); 13073 } 13074 13075 if (LastExpr.isInvalid()) 13076 return ExprError(); 13077 if (LastExpr.get() != nullptr) { 13078 if (!LastLabelStmt) 13079 Compound->setLastStmt(LastExpr.get()); 13080 else 13081 LastLabelStmt->setSubStmt(LastExpr.get()); 13082 StmtExprMayBindToTemp = true; 13083 } 13084 } 13085 } 13086 } 13087 13088 // FIXME: Check that expression type is complete/non-abstract; statement 13089 // expressions are not lvalues. 13090 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13091 if (StmtExprMayBindToTemp) 13092 return MaybeBindToTemporary(ResStmtExpr); 13093 return ResStmtExpr; 13094 } 13095 13096 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13097 TypeSourceInfo *TInfo, 13098 ArrayRef<OffsetOfComponent> Components, 13099 SourceLocation RParenLoc) { 13100 QualType ArgTy = TInfo->getType(); 13101 bool Dependent = ArgTy->isDependentType(); 13102 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13103 13104 // We must have at least one component that refers to the type, and the first 13105 // one is known to be a field designator. Verify that the ArgTy represents 13106 // a struct/union/class. 13107 if (!Dependent && !ArgTy->isRecordType()) 13108 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13109 << ArgTy << TypeRange); 13110 13111 // Type must be complete per C99 7.17p3 because a declaring a variable 13112 // with an incomplete type would be ill-formed. 13113 if (!Dependent 13114 && RequireCompleteType(BuiltinLoc, ArgTy, 13115 diag::err_offsetof_incomplete_type, TypeRange)) 13116 return ExprError(); 13117 13118 bool DidWarnAboutNonPOD = false; 13119 QualType CurrentType = ArgTy; 13120 SmallVector<OffsetOfNode, 4> Comps; 13121 SmallVector<Expr*, 4> Exprs; 13122 for (const OffsetOfComponent &OC : Components) { 13123 if (OC.isBrackets) { 13124 // Offset of an array sub-field. TODO: Should we allow vector elements? 13125 if (!CurrentType->isDependentType()) { 13126 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13127 if(!AT) 13128 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13129 << CurrentType); 13130 CurrentType = AT->getElementType(); 13131 } else 13132 CurrentType = Context.DependentTy; 13133 13134 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13135 if (IdxRval.isInvalid()) 13136 return ExprError(); 13137 Expr *Idx = IdxRval.get(); 13138 13139 // The expression must be an integral expression. 13140 // FIXME: An integral constant expression? 13141 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13142 !Idx->getType()->isIntegerType()) 13143 return ExprError( 13144 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13145 << Idx->getSourceRange()); 13146 13147 // Record this array index. 13148 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13149 Exprs.push_back(Idx); 13150 continue; 13151 } 13152 13153 // Offset of a field. 13154 if (CurrentType->isDependentType()) { 13155 // We have the offset of a field, but we can't look into the dependent 13156 // type. Just record the identifier of the field. 13157 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13158 CurrentType = Context.DependentTy; 13159 continue; 13160 } 13161 13162 // We need to have a complete type to look into. 13163 if (RequireCompleteType(OC.LocStart, CurrentType, 13164 diag::err_offsetof_incomplete_type)) 13165 return ExprError(); 13166 13167 // Look for the designated field. 13168 const RecordType *RC = CurrentType->getAs<RecordType>(); 13169 if (!RC) 13170 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13171 << CurrentType); 13172 RecordDecl *RD = RC->getDecl(); 13173 13174 // C++ [lib.support.types]p5: 13175 // The macro offsetof accepts a restricted set of type arguments in this 13176 // International Standard. type shall be a POD structure or a POD union 13177 // (clause 9). 13178 // C++11 [support.types]p4: 13179 // If type is not a standard-layout class (Clause 9), the results are 13180 // undefined. 13181 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13182 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13183 unsigned DiagID = 13184 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13185 : diag::ext_offsetof_non_pod_type; 13186 13187 if (!IsSafe && !DidWarnAboutNonPOD && 13188 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13189 PDiag(DiagID) 13190 << SourceRange(Components[0].LocStart, OC.LocEnd) 13191 << CurrentType)) 13192 DidWarnAboutNonPOD = true; 13193 } 13194 13195 // Look for the field. 13196 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13197 LookupQualifiedName(R, RD); 13198 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13199 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13200 if (!MemberDecl) { 13201 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13202 MemberDecl = IndirectMemberDecl->getAnonField(); 13203 } 13204 13205 if (!MemberDecl) 13206 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13207 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13208 OC.LocEnd)); 13209 13210 // C99 7.17p3: 13211 // (If the specified member is a bit-field, the behavior is undefined.) 13212 // 13213 // We diagnose this as an error. 13214 if (MemberDecl->isBitField()) { 13215 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13216 << MemberDecl->getDeclName() 13217 << SourceRange(BuiltinLoc, RParenLoc); 13218 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13219 return ExprError(); 13220 } 13221 13222 RecordDecl *Parent = MemberDecl->getParent(); 13223 if (IndirectMemberDecl) 13224 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13225 13226 // If the member was found in a base class, introduce OffsetOfNodes for 13227 // the base class indirections. 13228 CXXBasePaths Paths; 13229 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13230 Paths)) { 13231 if (Paths.getDetectedVirtual()) { 13232 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13233 << MemberDecl->getDeclName() 13234 << SourceRange(BuiltinLoc, RParenLoc); 13235 return ExprError(); 13236 } 13237 13238 CXXBasePath &Path = Paths.front(); 13239 for (const CXXBasePathElement &B : Path) 13240 Comps.push_back(OffsetOfNode(B.Base)); 13241 } 13242 13243 if (IndirectMemberDecl) { 13244 for (auto *FI : IndirectMemberDecl->chain()) { 13245 assert(isa<FieldDecl>(FI)); 13246 Comps.push_back(OffsetOfNode(OC.LocStart, 13247 cast<FieldDecl>(FI), OC.LocEnd)); 13248 } 13249 } else 13250 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13251 13252 CurrentType = MemberDecl->getType().getNonReferenceType(); 13253 } 13254 13255 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13256 Comps, Exprs, RParenLoc); 13257 } 13258 13259 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13260 SourceLocation BuiltinLoc, 13261 SourceLocation TypeLoc, 13262 ParsedType ParsedArgTy, 13263 ArrayRef<OffsetOfComponent> Components, 13264 SourceLocation RParenLoc) { 13265 13266 TypeSourceInfo *ArgTInfo; 13267 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13268 if (ArgTy.isNull()) 13269 return ExprError(); 13270 13271 if (!ArgTInfo) 13272 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13273 13274 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13275 } 13276 13277 13278 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13279 Expr *CondExpr, 13280 Expr *LHSExpr, Expr *RHSExpr, 13281 SourceLocation RPLoc) { 13282 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13283 13284 ExprValueKind VK = VK_RValue; 13285 ExprObjectKind OK = OK_Ordinary; 13286 QualType resType; 13287 bool ValueDependent = false; 13288 bool CondIsTrue = false; 13289 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13290 resType = Context.DependentTy; 13291 ValueDependent = true; 13292 } else { 13293 // The conditional expression is required to be a constant expression. 13294 llvm::APSInt condEval(32); 13295 ExprResult CondICE 13296 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13297 diag::err_typecheck_choose_expr_requires_constant, false); 13298 if (CondICE.isInvalid()) 13299 return ExprError(); 13300 CondExpr = CondICE.get(); 13301 CondIsTrue = condEval.getZExtValue(); 13302 13303 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13304 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13305 13306 resType = ActiveExpr->getType(); 13307 ValueDependent = ActiveExpr->isValueDependent(); 13308 VK = ActiveExpr->getValueKind(); 13309 OK = ActiveExpr->getObjectKind(); 13310 } 13311 13312 return new (Context) 13313 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13314 CondIsTrue, resType->isDependentType(), ValueDependent); 13315 } 13316 13317 //===----------------------------------------------------------------------===// 13318 // Clang Extensions. 13319 //===----------------------------------------------------------------------===// 13320 13321 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13322 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13323 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13324 13325 if (LangOpts.CPlusPlus) { 13326 Decl *ManglingContextDecl; 13327 if (MangleNumberingContext *MCtx = 13328 getCurrentMangleNumberContext(Block->getDeclContext(), 13329 ManglingContextDecl)) { 13330 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13331 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13332 } 13333 } 13334 13335 PushBlockScope(CurScope, Block); 13336 CurContext->addDecl(Block); 13337 if (CurScope) 13338 PushDeclContext(CurScope, Block); 13339 else 13340 CurContext = Block; 13341 13342 getCurBlock()->HasImplicitReturnType = true; 13343 13344 // Enter a new evaluation context to insulate the block from any 13345 // cleanups from the enclosing full-expression. 13346 PushExpressionEvaluationContext( 13347 ExpressionEvaluationContext::PotentiallyEvaluated); 13348 } 13349 13350 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13351 Scope *CurScope) { 13352 assert(ParamInfo.getIdentifier() == nullptr && 13353 "block-id should have no identifier!"); 13354 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13355 BlockScopeInfo *CurBlock = getCurBlock(); 13356 13357 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13358 QualType T = Sig->getType(); 13359 13360 // FIXME: We should allow unexpanded parameter packs here, but that would, 13361 // in turn, make the block expression contain unexpanded parameter packs. 13362 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13363 // Drop the parameters. 13364 FunctionProtoType::ExtProtoInfo EPI; 13365 EPI.HasTrailingReturn = false; 13366 EPI.TypeQuals |= DeclSpec::TQ_const; 13367 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13368 Sig = Context.getTrivialTypeSourceInfo(T); 13369 } 13370 13371 // GetTypeForDeclarator always produces a function type for a block 13372 // literal signature. Furthermore, it is always a FunctionProtoType 13373 // unless the function was written with a typedef. 13374 assert(T->isFunctionType() && 13375 "GetTypeForDeclarator made a non-function block signature"); 13376 13377 // Look for an explicit signature in that function type. 13378 FunctionProtoTypeLoc ExplicitSignature; 13379 13380 if ((ExplicitSignature = 13381 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13382 13383 // Check whether that explicit signature was synthesized by 13384 // GetTypeForDeclarator. If so, don't save that as part of the 13385 // written signature. 13386 if (ExplicitSignature.getLocalRangeBegin() == 13387 ExplicitSignature.getLocalRangeEnd()) { 13388 // This would be much cheaper if we stored TypeLocs instead of 13389 // TypeSourceInfos. 13390 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13391 unsigned Size = Result.getFullDataSize(); 13392 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13393 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13394 13395 ExplicitSignature = FunctionProtoTypeLoc(); 13396 } 13397 } 13398 13399 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13400 CurBlock->FunctionType = T; 13401 13402 const FunctionType *Fn = T->getAs<FunctionType>(); 13403 QualType RetTy = Fn->getReturnType(); 13404 bool isVariadic = 13405 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13406 13407 CurBlock->TheDecl->setIsVariadic(isVariadic); 13408 13409 // Context.DependentTy is used as a placeholder for a missing block 13410 // return type. TODO: what should we do with declarators like: 13411 // ^ * { ... } 13412 // If the answer is "apply template argument deduction".... 13413 if (RetTy != Context.DependentTy) { 13414 CurBlock->ReturnType = RetTy; 13415 CurBlock->TheDecl->setBlockMissingReturnType(false); 13416 CurBlock->HasImplicitReturnType = false; 13417 } 13418 13419 // Push block parameters from the declarator if we had them. 13420 SmallVector<ParmVarDecl*, 8> Params; 13421 if (ExplicitSignature) { 13422 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13423 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13424 if (Param->getIdentifier() == nullptr && 13425 !Param->isImplicit() && 13426 !Param->isInvalidDecl() && 13427 !getLangOpts().CPlusPlus) 13428 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13429 Params.push_back(Param); 13430 } 13431 13432 // Fake up parameter variables if we have a typedef, like 13433 // ^ fntype { ... } 13434 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13435 for (const auto &I : Fn->param_types()) { 13436 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13437 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13438 Params.push_back(Param); 13439 } 13440 } 13441 13442 // Set the parameters on the block decl. 13443 if (!Params.empty()) { 13444 CurBlock->TheDecl->setParams(Params); 13445 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13446 /*CheckParameterNames=*/false); 13447 } 13448 13449 // Finally we can process decl attributes. 13450 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13451 13452 // Put the parameter variables in scope. 13453 for (auto AI : CurBlock->TheDecl->parameters()) { 13454 AI->setOwningFunction(CurBlock->TheDecl); 13455 13456 // If this has an identifier, add it to the scope stack. 13457 if (AI->getIdentifier()) { 13458 CheckShadow(CurBlock->TheScope, AI); 13459 13460 PushOnScopeChains(AI, CurBlock->TheScope); 13461 } 13462 } 13463 } 13464 13465 /// ActOnBlockError - If there is an error parsing a block, this callback 13466 /// is invoked to pop the information about the block from the action impl. 13467 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13468 // Leave the expression-evaluation context. 13469 DiscardCleanupsInEvaluationContext(); 13470 PopExpressionEvaluationContext(); 13471 13472 // Pop off CurBlock, handle nested blocks. 13473 PopDeclContext(); 13474 PopFunctionScopeInfo(); 13475 } 13476 13477 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13478 /// literal was successfully completed. ^(int x){...} 13479 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13480 Stmt *Body, Scope *CurScope) { 13481 // If blocks are disabled, emit an error. 13482 if (!LangOpts.Blocks) 13483 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13484 13485 // Leave the expression-evaluation context. 13486 if (hasAnyUnrecoverableErrorsInThisFunction()) 13487 DiscardCleanupsInEvaluationContext(); 13488 assert(!Cleanup.exprNeedsCleanups() && 13489 "cleanups within block not correctly bound!"); 13490 PopExpressionEvaluationContext(); 13491 13492 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13493 BlockDecl *BD = BSI->TheDecl; 13494 13495 if (BSI->HasImplicitReturnType) 13496 deduceClosureReturnType(*BSI); 13497 13498 PopDeclContext(); 13499 13500 QualType RetTy = Context.VoidTy; 13501 if (!BSI->ReturnType.isNull()) 13502 RetTy = BSI->ReturnType; 13503 13504 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13505 QualType BlockTy; 13506 13507 // Set the captured variables on the block. 13508 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13509 SmallVector<BlockDecl::Capture, 4> Captures; 13510 for (Capture &Cap : BSI->Captures) { 13511 if (Cap.isThisCapture()) 13512 continue; 13513 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13514 Cap.isNested(), Cap.getInitExpr()); 13515 Captures.push_back(NewCap); 13516 } 13517 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13518 13519 // If the user wrote a function type in some form, try to use that. 13520 if (!BSI->FunctionType.isNull()) { 13521 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13522 13523 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13524 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13525 13526 // Turn protoless block types into nullary block types. 13527 if (isa<FunctionNoProtoType>(FTy)) { 13528 FunctionProtoType::ExtProtoInfo EPI; 13529 EPI.ExtInfo = Ext; 13530 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13531 13532 // Otherwise, if we don't need to change anything about the function type, 13533 // preserve its sugar structure. 13534 } else if (FTy->getReturnType() == RetTy && 13535 (!NoReturn || FTy->getNoReturnAttr())) { 13536 BlockTy = BSI->FunctionType; 13537 13538 // Otherwise, make the minimal modifications to the function type. 13539 } else { 13540 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13541 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13542 EPI.TypeQuals = 0; // FIXME: silently? 13543 EPI.ExtInfo = Ext; 13544 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13545 } 13546 13547 // If we don't have a function type, just build one from nothing. 13548 } else { 13549 FunctionProtoType::ExtProtoInfo EPI; 13550 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13551 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13552 } 13553 13554 DiagnoseUnusedParameters(BD->parameters()); 13555 BlockTy = Context.getBlockPointerType(BlockTy); 13556 13557 // If needed, diagnose invalid gotos and switches in the block. 13558 if (getCurFunction()->NeedsScopeChecking() && 13559 !PP.isCodeCompletionEnabled()) 13560 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13561 13562 BD->setBody(cast<CompoundStmt>(Body)); 13563 13564 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13565 DiagnoseUnguardedAvailabilityViolations(BD); 13566 13567 // Try to apply the named return value optimization. We have to check again 13568 // if we can do this, though, because blocks keep return statements around 13569 // to deduce an implicit return type. 13570 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13571 !BD->isDependentContext()) 13572 computeNRVO(Body, BSI); 13573 13574 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13575 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13576 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13577 13578 // If the block isn't obviously global, i.e. it captures anything at 13579 // all, then we need to do a few things in the surrounding context: 13580 if (Result->getBlockDecl()->hasCaptures()) { 13581 // First, this expression has a new cleanup object. 13582 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13583 Cleanup.setExprNeedsCleanups(true); 13584 13585 // It also gets a branch-protected scope if any of the captured 13586 // variables needs destruction. 13587 for (const auto &CI : Result->getBlockDecl()->captures()) { 13588 const VarDecl *var = CI.getVariable(); 13589 if (var->getType().isDestructedType() != QualType::DK_none) { 13590 setFunctionHasBranchProtectedScope(); 13591 break; 13592 } 13593 } 13594 } 13595 13596 if (getCurFunction()) 13597 getCurFunction()->addBlock(BD); 13598 13599 return Result; 13600 } 13601 13602 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13603 SourceLocation RPLoc) { 13604 TypeSourceInfo *TInfo; 13605 GetTypeFromParser(Ty, &TInfo); 13606 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13607 } 13608 13609 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13610 Expr *E, TypeSourceInfo *TInfo, 13611 SourceLocation RPLoc) { 13612 Expr *OrigExpr = E; 13613 bool IsMS = false; 13614 13615 // CUDA device code does not support varargs. 13616 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13617 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13618 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13619 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13620 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13621 } 13622 } 13623 13624 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13625 // as Microsoft ABI on an actual Microsoft platform, where 13626 // __builtin_ms_va_list and __builtin_va_list are the same.) 13627 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13628 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13629 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13630 if (Context.hasSameType(MSVaListType, E->getType())) { 13631 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13632 return ExprError(); 13633 IsMS = true; 13634 } 13635 } 13636 13637 // Get the va_list type 13638 QualType VaListType = Context.getBuiltinVaListType(); 13639 if (!IsMS) { 13640 if (VaListType->isArrayType()) { 13641 // Deal with implicit array decay; for example, on x86-64, 13642 // va_list is an array, but it's supposed to decay to 13643 // a pointer for va_arg. 13644 VaListType = Context.getArrayDecayedType(VaListType); 13645 // Make sure the input expression also decays appropriately. 13646 ExprResult Result = UsualUnaryConversions(E); 13647 if (Result.isInvalid()) 13648 return ExprError(); 13649 E = Result.get(); 13650 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13651 // If va_list is a record type and we are compiling in C++ mode, 13652 // check the argument using reference binding. 13653 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13654 Context, Context.getLValueReferenceType(VaListType), false); 13655 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13656 if (Init.isInvalid()) 13657 return ExprError(); 13658 E = Init.getAs<Expr>(); 13659 } else { 13660 // Otherwise, the va_list argument must be an l-value because 13661 // it is modified by va_arg. 13662 if (!E->isTypeDependent() && 13663 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13664 return ExprError(); 13665 } 13666 } 13667 13668 if (!IsMS && !E->isTypeDependent() && 13669 !Context.hasSameType(VaListType, E->getType())) 13670 return ExprError( 13671 Diag(E->getBeginLoc(), 13672 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13673 << OrigExpr->getType() << E->getSourceRange()); 13674 13675 if (!TInfo->getType()->isDependentType()) { 13676 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13677 diag::err_second_parameter_to_va_arg_incomplete, 13678 TInfo->getTypeLoc())) 13679 return ExprError(); 13680 13681 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13682 TInfo->getType(), 13683 diag::err_second_parameter_to_va_arg_abstract, 13684 TInfo->getTypeLoc())) 13685 return ExprError(); 13686 13687 if (!TInfo->getType().isPODType(Context)) { 13688 Diag(TInfo->getTypeLoc().getBeginLoc(), 13689 TInfo->getType()->isObjCLifetimeType() 13690 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13691 : diag::warn_second_parameter_to_va_arg_not_pod) 13692 << TInfo->getType() 13693 << TInfo->getTypeLoc().getSourceRange(); 13694 } 13695 13696 // Check for va_arg where arguments of the given type will be promoted 13697 // (i.e. this va_arg is guaranteed to have undefined behavior). 13698 QualType PromoteType; 13699 if (TInfo->getType()->isPromotableIntegerType()) { 13700 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13701 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13702 PromoteType = QualType(); 13703 } 13704 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13705 PromoteType = Context.DoubleTy; 13706 if (!PromoteType.isNull()) 13707 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13708 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13709 << TInfo->getType() 13710 << PromoteType 13711 << TInfo->getTypeLoc().getSourceRange()); 13712 } 13713 13714 QualType T = TInfo->getType().getNonLValueExprType(Context); 13715 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13716 } 13717 13718 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13719 // The type of __null will be int or long, depending on the size of 13720 // pointers on the target. 13721 QualType Ty; 13722 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13723 if (pw == Context.getTargetInfo().getIntWidth()) 13724 Ty = Context.IntTy; 13725 else if (pw == Context.getTargetInfo().getLongWidth()) 13726 Ty = Context.LongTy; 13727 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13728 Ty = Context.LongLongTy; 13729 else { 13730 llvm_unreachable("I don't know size of pointer!"); 13731 } 13732 13733 return new (Context) GNUNullExpr(Ty, TokenLoc); 13734 } 13735 13736 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13737 bool Diagnose) { 13738 if (!getLangOpts().ObjC1) 13739 return false; 13740 13741 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13742 if (!PT) 13743 return false; 13744 13745 if (!PT->isObjCIdType()) { 13746 // Check if the destination is the 'NSString' interface. 13747 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13748 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13749 return false; 13750 } 13751 13752 // Ignore any parens, implicit casts (should only be 13753 // array-to-pointer decays), and not-so-opaque values. The last is 13754 // important for making this trigger for property assignments. 13755 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13756 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13757 if (OV->getSourceExpr()) 13758 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13759 13760 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13761 if (!SL || !SL->isAscii()) 13762 return false; 13763 if (Diagnose) { 13764 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13765 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13766 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13767 } 13768 return true; 13769 } 13770 13771 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13772 const Expr *SrcExpr) { 13773 if (!DstType->isFunctionPointerType() || 13774 !SrcExpr->getType()->isFunctionType()) 13775 return false; 13776 13777 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13778 if (!DRE) 13779 return false; 13780 13781 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13782 if (!FD) 13783 return false; 13784 13785 return !S.checkAddressOfFunctionIsAvailable(FD, 13786 /*Complain=*/true, 13787 SrcExpr->getBeginLoc()); 13788 } 13789 13790 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13791 SourceLocation Loc, 13792 QualType DstType, QualType SrcType, 13793 Expr *SrcExpr, AssignmentAction Action, 13794 bool *Complained) { 13795 if (Complained) 13796 *Complained = false; 13797 13798 // Decode the result (notice that AST's are still created for extensions). 13799 bool CheckInferredResultType = false; 13800 bool isInvalid = false; 13801 unsigned DiagKind = 0; 13802 FixItHint Hint; 13803 ConversionFixItGenerator ConvHints; 13804 bool MayHaveConvFixit = false; 13805 bool MayHaveFunctionDiff = false; 13806 const ObjCInterfaceDecl *IFace = nullptr; 13807 const ObjCProtocolDecl *PDecl = nullptr; 13808 13809 switch (ConvTy) { 13810 case Compatible: 13811 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13812 return false; 13813 13814 case PointerToInt: 13815 DiagKind = diag::ext_typecheck_convert_pointer_int; 13816 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13817 MayHaveConvFixit = true; 13818 break; 13819 case IntToPointer: 13820 DiagKind = diag::ext_typecheck_convert_int_pointer; 13821 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13822 MayHaveConvFixit = true; 13823 break; 13824 case IncompatiblePointer: 13825 if (Action == AA_Passing_CFAudited) 13826 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13827 else if (SrcType->isFunctionPointerType() && 13828 DstType->isFunctionPointerType()) 13829 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13830 else 13831 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13832 13833 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13834 SrcType->isObjCObjectPointerType(); 13835 if (Hint.isNull() && !CheckInferredResultType) { 13836 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13837 } 13838 else if (CheckInferredResultType) { 13839 SrcType = SrcType.getUnqualifiedType(); 13840 DstType = DstType.getUnqualifiedType(); 13841 } 13842 MayHaveConvFixit = true; 13843 break; 13844 case IncompatiblePointerSign: 13845 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13846 break; 13847 case FunctionVoidPointer: 13848 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13849 break; 13850 case IncompatiblePointerDiscardsQualifiers: { 13851 // Perform array-to-pointer decay if necessary. 13852 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13853 13854 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13855 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13856 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13857 DiagKind = diag::err_typecheck_incompatible_address_space; 13858 break; 13859 13860 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13861 DiagKind = diag::err_typecheck_incompatible_ownership; 13862 break; 13863 } 13864 13865 llvm_unreachable("unknown error case for discarding qualifiers!"); 13866 // fallthrough 13867 } 13868 case CompatiblePointerDiscardsQualifiers: 13869 // If the qualifiers lost were because we were applying the 13870 // (deprecated) C++ conversion from a string literal to a char* 13871 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13872 // Ideally, this check would be performed in 13873 // checkPointerTypesForAssignment. However, that would require a 13874 // bit of refactoring (so that the second argument is an 13875 // expression, rather than a type), which should be done as part 13876 // of a larger effort to fix checkPointerTypesForAssignment for 13877 // C++ semantics. 13878 if (getLangOpts().CPlusPlus && 13879 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13880 return false; 13881 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13882 break; 13883 case IncompatibleNestedPointerQualifiers: 13884 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13885 break; 13886 case IntToBlockPointer: 13887 DiagKind = diag::err_int_to_block_pointer; 13888 break; 13889 case IncompatibleBlockPointer: 13890 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13891 break; 13892 case IncompatibleObjCQualifiedId: { 13893 if (SrcType->isObjCQualifiedIdType()) { 13894 const ObjCObjectPointerType *srcOPT = 13895 SrcType->getAs<ObjCObjectPointerType>(); 13896 for (auto *srcProto : srcOPT->quals()) { 13897 PDecl = srcProto; 13898 break; 13899 } 13900 if (const ObjCInterfaceType *IFaceT = 13901 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13902 IFace = IFaceT->getDecl(); 13903 } 13904 else if (DstType->isObjCQualifiedIdType()) { 13905 const ObjCObjectPointerType *dstOPT = 13906 DstType->getAs<ObjCObjectPointerType>(); 13907 for (auto *dstProto : dstOPT->quals()) { 13908 PDecl = dstProto; 13909 break; 13910 } 13911 if (const ObjCInterfaceType *IFaceT = 13912 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13913 IFace = IFaceT->getDecl(); 13914 } 13915 DiagKind = diag::warn_incompatible_qualified_id; 13916 break; 13917 } 13918 case IncompatibleVectors: 13919 DiagKind = diag::warn_incompatible_vectors; 13920 break; 13921 case IncompatibleObjCWeakRef: 13922 DiagKind = diag::err_arc_weak_unavailable_assign; 13923 break; 13924 case Incompatible: 13925 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13926 if (Complained) 13927 *Complained = true; 13928 return true; 13929 } 13930 13931 DiagKind = diag::err_typecheck_convert_incompatible; 13932 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13933 MayHaveConvFixit = true; 13934 isInvalid = true; 13935 MayHaveFunctionDiff = true; 13936 break; 13937 } 13938 13939 QualType FirstType, SecondType; 13940 switch (Action) { 13941 case AA_Assigning: 13942 case AA_Initializing: 13943 // The destination type comes first. 13944 FirstType = DstType; 13945 SecondType = SrcType; 13946 break; 13947 13948 case AA_Returning: 13949 case AA_Passing: 13950 case AA_Passing_CFAudited: 13951 case AA_Converting: 13952 case AA_Sending: 13953 case AA_Casting: 13954 // The source type comes first. 13955 FirstType = SrcType; 13956 SecondType = DstType; 13957 break; 13958 } 13959 13960 PartialDiagnostic FDiag = PDiag(DiagKind); 13961 if (Action == AA_Passing_CFAudited) 13962 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13963 else 13964 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13965 13966 // If we can fix the conversion, suggest the FixIts. 13967 assert(ConvHints.isNull() || Hint.isNull()); 13968 if (!ConvHints.isNull()) { 13969 for (FixItHint &H : ConvHints.Hints) 13970 FDiag << H; 13971 } else { 13972 FDiag << Hint; 13973 } 13974 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13975 13976 if (MayHaveFunctionDiff) 13977 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13978 13979 Diag(Loc, FDiag); 13980 if (DiagKind == diag::warn_incompatible_qualified_id && 13981 PDecl && IFace && !IFace->hasDefinition()) 13982 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13983 << IFace << PDecl; 13984 13985 if (SecondType == Context.OverloadTy) 13986 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13987 FirstType, /*TakingAddress=*/true); 13988 13989 if (CheckInferredResultType) 13990 EmitRelatedResultTypeNote(SrcExpr); 13991 13992 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13993 EmitRelatedResultTypeNoteForReturn(DstType); 13994 13995 if (Complained) 13996 *Complained = true; 13997 return isInvalid; 13998 } 13999 14000 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14001 llvm::APSInt *Result) { 14002 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14003 public: 14004 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14005 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14006 } 14007 } Diagnoser; 14008 14009 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14010 } 14011 14012 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14013 llvm::APSInt *Result, 14014 unsigned DiagID, 14015 bool AllowFold) { 14016 class IDDiagnoser : public VerifyICEDiagnoser { 14017 unsigned DiagID; 14018 14019 public: 14020 IDDiagnoser(unsigned DiagID) 14021 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14022 14023 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14024 S.Diag(Loc, DiagID) << SR; 14025 } 14026 } Diagnoser(DiagID); 14027 14028 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14029 } 14030 14031 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14032 SourceRange SR) { 14033 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14034 } 14035 14036 ExprResult 14037 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14038 VerifyICEDiagnoser &Diagnoser, 14039 bool AllowFold) { 14040 SourceLocation DiagLoc = E->getBeginLoc(); 14041 14042 if (getLangOpts().CPlusPlus11) { 14043 // C++11 [expr.const]p5: 14044 // If an expression of literal class type is used in a context where an 14045 // integral constant expression is required, then that class type shall 14046 // have a single non-explicit conversion function to an integral or 14047 // unscoped enumeration type 14048 ExprResult Converted; 14049 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14050 public: 14051 CXX11ConvertDiagnoser(bool Silent) 14052 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14053 Silent, true) {} 14054 14055 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14056 QualType T) override { 14057 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14058 } 14059 14060 SemaDiagnosticBuilder diagnoseIncomplete( 14061 Sema &S, SourceLocation Loc, QualType T) override { 14062 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14063 } 14064 14065 SemaDiagnosticBuilder diagnoseExplicitConv( 14066 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14067 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14068 } 14069 14070 SemaDiagnosticBuilder noteExplicitConv( 14071 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14072 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14073 << ConvTy->isEnumeralType() << ConvTy; 14074 } 14075 14076 SemaDiagnosticBuilder diagnoseAmbiguous( 14077 Sema &S, SourceLocation Loc, QualType T) override { 14078 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14079 } 14080 14081 SemaDiagnosticBuilder noteAmbiguous( 14082 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14083 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14084 << ConvTy->isEnumeralType() << ConvTy; 14085 } 14086 14087 SemaDiagnosticBuilder diagnoseConversion( 14088 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14089 llvm_unreachable("conversion functions are permitted"); 14090 } 14091 } ConvertDiagnoser(Diagnoser.Suppress); 14092 14093 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14094 ConvertDiagnoser); 14095 if (Converted.isInvalid()) 14096 return Converted; 14097 E = Converted.get(); 14098 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14099 return ExprError(); 14100 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14101 // An ICE must be of integral or unscoped enumeration type. 14102 if (!Diagnoser.Suppress) 14103 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14104 return ExprError(); 14105 } 14106 14107 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14108 // in the non-ICE case. 14109 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14110 if (Result) 14111 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14112 return E; 14113 } 14114 14115 Expr::EvalResult EvalResult; 14116 SmallVector<PartialDiagnosticAt, 8> Notes; 14117 EvalResult.Diag = &Notes; 14118 14119 // Try to evaluate the expression, and produce diagnostics explaining why it's 14120 // not a constant expression as a side-effect. 14121 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14122 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14123 14124 // In C++11, we can rely on diagnostics being produced for any expression 14125 // which is not a constant expression. If no diagnostics were produced, then 14126 // this is a constant expression. 14127 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14128 if (Result) 14129 *Result = EvalResult.Val.getInt(); 14130 return E; 14131 } 14132 14133 // If our only note is the usual "invalid subexpression" note, just point 14134 // the caret at its location rather than producing an essentially 14135 // redundant note. 14136 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14137 diag::note_invalid_subexpr_in_const_expr) { 14138 DiagLoc = Notes[0].first; 14139 Notes.clear(); 14140 } 14141 14142 if (!Folded || !AllowFold) { 14143 if (!Diagnoser.Suppress) { 14144 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14145 for (const PartialDiagnosticAt &Note : Notes) 14146 Diag(Note.first, Note.second); 14147 } 14148 14149 return ExprError(); 14150 } 14151 14152 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14153 for (const PartialDiagnosticAt &Note : Notes) 14154 Diag(Note.first, Note.second); 14155 14156 if (Result) 14157 *Result = EvalResult.Val.getInt(); 14158 return E; 14159 } 14160 14161 namespace { 14162 // Handle the case where we conclude a expression which we speculatively 14163 // considered to be unevaluated is actually evaluated. 14164 class TransformToPE : public TreeTransform<TransformToPE> { 14165 typedef TreeTransform<TransformToPE> BaseTransform; 14166 14167 public: 14168 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14169 14170 // Make sure we redo semantic analysis 14171 bool AlwaysRebuild() { return true; } 14172 14173 // Make sure we handle LabelStmts correctly. 14174 // FIXME: This does the right thing, but maybe we need a more general 14175 // fix to TreeTransform? 14176 StmtResult TransformLabelStmt(LabelStmt *S) { 14177 S->getDecl()->setStmt(nullptr); 14178 return BaseTransform::TransformLabelStmt(S); 14179 } 14180 14181 // We need to special-case DeclRefExprs referring to FieldDecls which 14182 // are not part of a member pointer formation; normal TreeTransforming 14183 // doesn't catch this case because of the way we represent them in the AST. 14184 // FIXME: This is a bit ugly; is it really the best way to handle this 14185 // case? 14186 // 14187 // Error on DeclRefExprs referring to FieldDecls. 14188 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14189 if (isa<FieldDecl>(E->getDecl()) && 14190 !SemaRef.isUnevaluatedContext()) 14191 return SemaRef.Diag(E->getLocation(), 14192 diag::err_invalid_non_static_member_use) 14193 << E->getDecl() << E->getSourceRange(); 14194 14195 return BaseTransform::TransformDeclRefExpr(E); 14196 } 14197 14198 // Exception: filter out member pointer formation 14199 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14200 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14201 return E; 14202 14203 return BaseTransform::TransformUnaryOperator(E); 14204 } 14205 14206 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14207 // Lambdas never need to be transformed. 14208 return E; 14209 } 14210 }; 14211 } 14212 14213 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14214 assert(isUnevaluatedContext() && 14215 "Should only transform unevaluated expressions"); 14216 ExprEvalContexts.back().Context = 14217 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14218 if (isUnevaluatedContext()) 14219 return E; 14220 return TransformToPE(*this).TransformExpr(E); 14221 } 14222 14223 void 14224 Sema::PushExpressionEvaluationContext( 14225 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14226 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14227 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14228 LambdaContextDecl, ExprContext); 14229 Cleanup.reset(); 14230 if (!MaybeODRUseExprs.empty()) 14231 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14232 } 14233 14234 void 14235 Sema::PushExpressionEvaluationContext( 14236 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14237 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14238 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14239 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14240 } 14241 14242 void Sema::PopExpressionEvaluationContext() { 14243 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14244 unsigned NumTypos = Rec.NumTypos; 14245 14246 if (!Rec.Lambdas.empty()) { 14247 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14248 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14249 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14250 unsigned D; 14251 if (Rec.isUnevaluated()) { 14252 // C++11 [expr.prim.lambda]p2: 14253 // A lambda-expression shall not appear in an unevaluated operand 14254 // (Clause 5). 14255 D = diag::err_lambda_unevaluated_operand; 14256 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14257 // C++1y [expr.const]p2: 14258 // A conditional-expression e is a core constant expression unless the 14259 // evaluation of e, following the rules of the abstract machine, would 14260 // evaluate [...] a lambda-expression. 14261 D = diag::err_lambda_in_constant_expression; 14262 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14263 // C++17 [expr.prim.lamda]p2: 14264 // A lambda-expression shall not appear [...] in a template-argument. 14265 D = diag::err_lambda_in_invalid_context; 14266 } else 14267 llvm_unreachable("Couldn't infer lambda error message."); 14268 14269 for (const auto *L : Rec.Lambdas) 14270 Diag(L->getBeginLoc(), D); 14271 } else { 14272 // Mark the capture expressions odr-used. This was deferred 14273 // during lambda expression creation. 14274 for (auto *Lambda : Rec.Lambdas) { 14275 for (auto *C : Lambda->capture_inits()) 14276 MarkDeclarationsReferencedInExpr(C); 14277 } 14278 } 14279 } 14280 14281 // When are coming out of an unevaluated context, clear out any 14282 // temporaries that we may have created as part of the evaluation of 14283 // the expression in that context: they aren't relevant because they 14284 // will never be constructed. 14285 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14286 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14287 ExprCleanupObjects.end()); 14288 Cleanup = Rec.ParentCleanup; 14289 CleanupVarDeclMarking(); 14290 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14291 // Otherwise, merge the contexts together. 14292 } else { 14293 Cleanup.mergeFrom(Rec.ParentCleanup); 14294 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14295 Rec.SavedMaybeODRUseExprs.end()); 14296 } 14297 14298 // Pop the current expression evaluation context off the stack. 14299 ExprEvalContexts.pop_back(); 14300 14301 if (!ExprEvalContexts.empty()) 14302 ExprEvalContexts.back().NumTypos += NumTypos; 14303 else 14304 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14305 "last ExpressionEvaluationContextRecord"); 14306 } 14307 14308 void Sema::DiscardCleanupsInEvaluationContext() { 14309 ExprCleanupObjects.erase( 14310 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14311 ExprCleanupObjects.end()); 14312 Cleanup.reset(); 14313 MaybeODRUseExprs.clear(); 14314 } 14315 14316 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14317 if (!E->getType()->isVariablyModifiedType()) 14318 return E; 14319 return TransformToPotentiallyEvaluated(E); 14320 } 14321 14322 /// Are we within a context in which some evaluation could be performed (be it 14323 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14324 /// captured by C++'s idea of an "unevaluated context". 14325 static bool isEvaluatableContext(Sema &SemaRef) { 14326 switch (SemaRef.ExprEvalContexts.back().Context) { 14327 case Sema::ExpressionEvaluationContext::Unevaluated: 14328 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14329 // Expressions in this context are never evaluated. 14330 return false; 14331 14332 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14333 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14334 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14335 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14336 // Expressions in this context could be evaluated. 14337 return true; 14338 14339 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14340 // Referenced declarations will only be used if the construct in the 14341 // containing expression is used, at which point we'll be given another 14342 // turn to mark them. 14343 return false; 14344 } 14345 llvm_unreachable("Invalid context"); 14346 } 14347 14348 /// Are we within a context in which references to resolved functions or to 14349 /// variables result in odr-use? 14350 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14351 // An expression in a template is not really an expression until it's been 14352 // instantiated, so it doesn't trigger odr-use. 14353 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14354 return false; 14355 14356 switch (SemaRef.ExprEvalContexts.back().Context) { 14357 case Sema::ExpressionEvaluationContext::Unevaluated: 14358 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14359 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14360 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14361 return false; 14362 14363 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14364 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14365 return true; 14366 14367 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14368 return false; 14369 } 14370 llvm_unreachable("Invalid context"); 14371 } 14372 14373 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14374 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14375 return Func->isConstexpr() && 14376 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14377 } 14378 14379 /// Mark a function referenced, and check whether it is odr-used 14380 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14381 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14382 bool MightBeOdrUse) { 14383 assert(Func && "No function?"); 14384 14385 Func->setReferenced(); 14386 14387 // C++11 [basic.def.odr]p3: 14388 // A function whose name appears as a potentially-evaluated expression is 14389 // odr-used if it is the unique lookup result or the selected member of a 14390 // set of overloaded functions [...]. 14391 // 14392 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14393 // can just check that here. 14394 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14395 14396 // Determine whether we require a function definition to exist, per 14397 // C++11 [temp.inst]p3: 14398 // Unless a function template specialization has been explicitly 14399 // instantiated or explicitly specialized, the function template 14400 // specialization is implicitly instantiated when the specialization is 14401 // referenced in a context that requires a function definition to exist. 14402 // 14403 // That is either when this is an odr-use, or when a usage of a constexpr 14404 // function occurs within an evaluatable context. 14405 bool NeedDefinition = 14406 OdrUse || (isEvaluatableContext(*this) && 14407 isImplicitlyDefinableConstexprFunction(Func)); 14408 14409 // C++14 [temp.expl.spec]p6: 14410 // If a template [...] is explicitly specialized then that specialization 14411 // shall be declared before the first use of that specialization that would 14412 // cause an implicit instantiation to take place, in every translation unit 14413 // in which such a use occurs 14414 if (NeedDefinition && 14415 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14416 Func->getMemberSpecializationInfo())) 14417 checkSpecializationVisibility(Loc, Func); 14418 14419 // C++14 [except.spec]p17: 14420 // An exception-specification is considered to be needed when: 14421 // - the function is odr-used or, if it appears in an unevaluated operand, 14422 // would be odr-used if the expression were potentially-evaluated; 14423 // 14424 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14425 // function is a pure virtual function we're calling, and in that case the 14426 // function was selected by overload resolution and we need to resolve its 14427 // exception specification for a different reason. 14428 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14429 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14430 ResolveExceptionSpec(Loc, FPT); 14431 14432 // If we don't need to mark the function as used, and we don't need to 14433 // try to provide a definition, there's nothing more to do. 14434 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14435 (!NeedDefinition || Func->getBody())) 14436 return; 14437 14438 // Note that this declaration has been used. 14439 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14440 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14441 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14442 if (Constructor->isDefaultConstructor()) { 14443 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14444 return; 14445 DefineImplicitDefaultConstructor(Loc, Constructor); 14446 } else if (Constructor->isCopyConstructor()) { 14447 DefineImplicitCopyConstructor(Loc, Constructor); 14448 } else if (Constructor->isMoveConstructor()) { 14449 DefineImplicitMoveConstructor(Loc, Constructor); 14450 } 14451 } else if (Constructor->getInheritedConstructor()) { 14452 DefineInheritingConstructor(Loc, Constructor); 14453 } 14454 } else if (CXXDestructorDecl *Destructor = 14455 dyn_cast<CXXDestructorDecl>(Func)) { 14456 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14457 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14458 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14459 return; 14460 DefineImplicitDestructor(Loc, Destructor); 14461 } 14462 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14463 MarkVTableUsed(Loc, Destructor->getParent()); 14464 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14465 if (MethodDecl->isOverloadedOperator() && 14466 MethodDecl->getOverloadedOperator() == OO_Equal) { 14467 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14468 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14469 if (MethodDecl->isCopyAssignmentOperator()) 14470 DefineImplicitCopyAssignment(Loc, MethodDecl); 14471 else if (MethodDecl->isMoveAssignmentOperator()) 14472 DefineImplicitMoveAssignment(Loc, MethodDecl); 14473 } 14474 } else if (isa<CXXConversionDecl>(MethodDecl) && 14475 MethodDecl->getParent()->isLambda()) { 14476 CXXConversionDecl *Conversion = 14477 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14478 if (Conversion->isLambdaToBlockPointerConversion()) 14479 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14480 else 14481 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14482 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14483 MarkVTableUsed(Loc, MethodDecl->getParent()); 14484 } 14485 14486 // Recursive functions should be marked when used from another function. 14487 // FIXME: Is this really right? 14488 if (CurContext == Func) return; 14489 14490 // Implicit instantiation of function templates and member functions of 14491 // class templates. 14492 if (Func->isImplicitlyInstantiable()) { 14493 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14494 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14495 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14496 if (FirstInstantiation) { 14497 PointOfInstantiation = Loc; 14498 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14499 } else if (TSK != TSK_ImplicitInstantiation) { 14500 // Use the point of use as the point of instantiation, instead of the 14501 // point of explicit instantiation (which we track as the actual point of 14502 // instantiation). This gives better backtraces in diagnostics. 14503 PointOfInstantiation = Loc; 14504 } 14505 14506 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14507 Func->isConstexpr()) { 14508 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14509 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14510 CodeSynthesisContexts.size()) 14511 PendingLocalImplicitInstantiations.push_back( 14512 std::make_pair(Func, PointOfInstantiation)); 14513 else if (Func->isConstexpr()) 14514 // Do not defer instantiations of constexpr functions, to avoid the 14515 // expression evaluator needing to call back into Sema if it sees a 14516 // call to such a function. 14517 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14518 else { 14519 Func->setInstantiationIsPending(true); 14520 PendingInstantiations.push_back(std::make_pair(Func, 14521 PointOfInstantiation)); 14522 // Notify the consumer that a function was implicitly instantiated. 14523 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14524 } 14525 } 14526 } else { 14527 // Walk redefinitions, as some of them may be instantiable. 14528 for (auto i : Func->redecls()) { 14529 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14530 MarkFunctionReferenced(Loc, i, OdrUse); 14531 } 14532 } 14533 14534 if (!OdrUse) return; 14535 14536 // Keep track of used but undefined functions. 14537 if (!Func->isDefined()) { 14538 if (mightHaveNonExternalLinkage(Func)) 14539 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14540 else if (Func->getMostRecentDecl()->isInlined() && 14541 !LangOpts.GNUInline && 14542 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14543 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14544 else if (isExternalWithNoLinkageType(Func)) 14545 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14546 } 14547 14548 Func->markUsed(Context); 14549 } 14550 14551 static void 14552 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14553 ValueDecl *var, DeclContext *DC) { 14554 DeclContext *VarDC = var->getDeclContext(); 14555 14556 // If the parameter still belongs to the translation unit, then 14557 // we're actually just using one parameter in the declaration of 14558 // the next. 14559 if (isa<ParmVarDecl>(var) && 14560 isa<TranslationUnitDecl>(VarDC)) 14561 return; 14562 14563 // For C code, don't diagnose about capture if we're not actually in code 14564 // right now; it's impossible to write a non-constant expression outside of 14565 // function context, so we'll get other (more useful) diagnostics later. 14566 // 14567 // For C++, things get a bit more nasty... it would be nice to suppress this 14568 // diagnostic for certain cases like using a local variable in an array bound 14569 // for a member of a local class, but the correct predicate is not obvious. 14570 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14571 return; 14572 14573 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14574 unsigned ContextKind = 3; // unknown 14575 if (isa<CXXMethodDecl>(VarDC) && 14576 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14577 ContextKind = 2; 14578 } else if (isa<FunctionDecl>(VarDC)) { 14579 ContextKind = 0; 14580 } else if (isa<BlockDecl>(VarDC)) { 14581 ContextKind = 1; 14582 } 14583 14584 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14585 << var << ValueKind << ContextKind << VarDC; 14586 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14587 << var; 14588 14589 // FIXME: Add additional diagnostic info about class etc. which prevents 14590 // capture. 14591 } 14592 14593 14594 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14595 bool &SubCapturesAreNested, 14596 QualType &CaptureType, 14597 QualType &DeclRefType) { 14598 // Check whether we've already captured it. 14599 if (CSI->CaptureMap.count(Var)) { 14600 // If we found a capture, any subcaptures are nested. 14601 SubCapturesAreNested = true; 14602 14603 // Retrieve the capture type for this variable. 14604 CaptureType = CSI->getCapture(Var).getCaptureType(); 14605 14606 // Compute the type of an expression that refers to this variable. 14607 DeclRefType = CaptureType.getNonReferenceType(); 14608 14609 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14610 // are mutable in the sense that user can change their value - they are 14611 // private instances of the captured declarations. 14612 const Capture &Cap = CSI->getCapture(Var); 14613 if (Cap.isCopyCapture() && 14614 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14615 !(isa<CapturedRegionScopeInfo>(CSI) && 14616 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14617 DeclRefType.addConst(); 14618 return true; 14619 } 14620 return false; 14621 } 14622 14623 // Only block literals, captured statements, and lambda expressions can 14624 // capture; other scopes don't work. 14625 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14626 SourceLocation Loc, 14627 const bool Diagnose, Sema &S) { 14628 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14629 return getLambdaAwareParentOfDeclContext(DC); 14630 else if (Var->hasLocalStorage()) { 14631 if (Diagnose) 14632 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14633 } 14634 return nullptr; 14635 } 14636 14637 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14638 // certain types of variables (unnamed, variably modified types etc.) 14639 // so check for eligibility. 14640 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14641 SourceLocation Loc, 14642 const bool Diagnose, Sema &S) { 14643 14644 bool IsBlock = isa<BlockScopeInfo>(CSI); 14645 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14646 14647 // Lambdas are not allowed to capture unnamed variables 14648 // (e.g. anonymous unions). 14649 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14650 // assuming that's the intent. 14651 if (IsLambda && !Var->getDeclName()) { 14652 if (Diagnose) { 14653 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14654 S.Diag(Var->getLocation(), diag::note_declared_at); 14655 } 14656 return false; 14657 } 14658 14659 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14660 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14661 if (Diagnose) { 14662 S.Diag(Loc, diag::err_ref_vm_type); 14663 S.Diag(Var->getLocation(), diag::note_previous_decl) 14664 << Var->getDeclName(); 14665 } 14666 return false; 14667 } 14668 // Prohibit structs with flexible array members too. 14669 // We cannot capture what is in the tail end of the struct. 14670 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14671 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14672 if (Diagnose) { 14673 if (IsBlock) 14674 S.Diag(Loc, diag::err_ref_flexarray_type); 14675 else 14676 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14677 << Var->getDeclName(); 14678 S.Diag(Var->getLocation(), diag::note_previous_decl) 14679 << Var->getDeclName(); 14680 } 14681 return false; 14682 } 14683 } 14684 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14685 // Lambdas and captured statements are not allowed to capture __block 14686 // variables; they don't support the expected semantics. 14687 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14688 if (Diagnose) { 14689 S.Diag(Loc, diag::err_capture_block_variable) 14690 << Var->getDeclName() << !IsLambda; 14691 S.Diag(Var->getLocation(), diag::note_previous_decl) 14692 << Var->getDeclName(); 14693 } 14694 return false; 14695 } 14696 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14697 if (S.getLangOpts().OpenCL && IsBlock && 14698 Var->getType()->isBlockPointerType()) { 14699 if (Diagnose) 14700 S.Diag(Loc, diag::err_opencl_block_ref_block); 14701 return false; 14702 } 14703 14704 return true; 14705 } 14706 14707 // Returns true if the capture by block was successful. 14708 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14709 SourceLocation Loc, 14710 const bool BuildAndDiagnose, 14711 QualType &CaptureType, 14712 QualType &DeclRefType, 14713 const bool Nested, 14714 Sema &S) { 14715 Expr *CopyExpr = nullptr; 14716 bool ByRef = false; 14717 14718 // Blocks are not allowed to capture arrays, excepting OpenCL. 14719 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 14720 // (decayed to pointers). 14721 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 14722 if (BuildAndDiagnose) { 14723 S.Diag(Loc, diag::err_ref_array_type); 14724 S.Diag(Var->getLocation(), diag::note_previous_decl) 14725 << Var->getDeclName(); 14726 } 14727 return false; 14728 } 14729 14730 // Forbid the block-capture of autoreleasing variables. 14731 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14732 if (BuildAndDiagnose) { 14733 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14734 << /*block*/ 0; 14735 S.Diag(Var->getLocation(), diag::note_previous_decl) 14736 << Var->getDeclName(); 14737 } 14738 return false; 14739 } 14740 14741 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14742 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14743 // This function finds out whether there is an AttributedType of kind 14744 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 14745 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 14746 // rather than being added implicitly by the compiler. 14747 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14748 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14749 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 14750 return true; 14751 14752 // Peel off AttributedTypes that are not of kind ObjCOwnership. 14753 Ty = AttrTy->getModifiedType(); 14754 } 14755 14756 return false; 14757 }; 14758 14759 QualType PointeeTy = PT->getPointeeType(); 14760 14761 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14762 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14763 !IsObjCOwnershipAttributedType(PointeeTy)) { 14764 if (BuildAndDiagnose) { 14765 SourceLocation VarLoc = Var->getLocation(); 14766 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14767 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14768 } 14769 } 14770 } 14771 14772 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14773 if (HasBlocksAttr || CaptureType->isReferenceType() || 14774 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14775 // Block capture by reference does not change the capture or 14776 // declaration reference types. 14777 ByRef = true; 14778 } else { 14779 // Block capture by copy introduces 'const'. 14780 CaptureType = CaptureType.getNonReferenceType().withConst(); 14781 DeclRefType = CaptureType; 14782 14783 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14784 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14785 // The capture logic needs the destructor, so make sure we mark it. 14786 // Usually this is unnecessary because most local variables have 14787 // their destructors marked at declaration time, but parameters are 14788 // an exception because it's technically only the call site that 14789 // actually requires the destructor. 14790 if (isa<ParmVarDecl>(Var)) 14791 S.FinalizeVarWithDestructor(Var, Record); 14792 14793 // Enter a new evaluation context to insulate the copy 14794 // full-expression. 14795 EnterExpressionEvaluationContext scope( 14796 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14797 14798 // According to the blocks spec, the capture of a variable from 14799 // the stack requires a const copy constructor. This is not true 14800 // of the copy/move done to move a __block variable to the heap. 14801 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14802 DeclRefType.withConst(), 14803 VK_LValue, Loc); 14804 14805 ExprResult Result 14806 = S.PerformCopyInitialization( 14807 InitializedEntity::InitializeBlock(Var->getLocation(), 14808 CaptureType, false), 14809 Loc, DeclRef); 14810 14811 // Build a full-expression copy expression if initialization 14812 // succeeded and used a non-trivial constructor. Recover from 14813 // errors by pretending that the copy isn't necessary. 14814 if (!Result.isInvalid() && 14815 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14816 ->isTrivial()) { 14817 Result = S.MaybeCreateExprWithCleanups(Result); 14818 CopyExpr = Result.get(); 14819 } 14820 } 14821 } 14822 } 14823 14824 // Actually capture the variable. 14825 if (BuildAndDiagnose) 14826 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14827 SourceLocation(), CaptureType, CopyExpr); 14828 14829 return true; 14830 14831 } 14832 14833 14834 /// Capture the given variable in the captured region. 14835 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14836 VarDecl *Var, 14837 SourceLocation Loc, 14838 const bool BuildAndDiagnose, 14839 QualType &CaptureType, 14840 QualType &DeclRefType, 14841 const bool RefersToCapturedVariable, 14842 Sema &S) { 14843 // By default, capture variables by reference. 14844 bool ByRef = true; 14845 // Using an LValue reference type is consistent with Lambdas (see below). 14846 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14847 if (S.isOpenMPCapturedDecl(Var)) { 14848 bool HasConst = DeclRefType.isConstQualified(); 14849 DeclRefType = DeclRefType.getUnqualifiedType(); 14850 // Don't lose diagnostics about assignments to const. 14851 if (HasConst) 14852 DeclRefType.addConst(); 14853 } 14854 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14855 } 14856 14857 if (ByRef) 14858 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14859 else 14860 CaptureType = DeclRefType; 14861 14862 Expr *CopyExpr = nullptr; 14863 if (BuildAndDiagnose) { 14864 // The current implementation assumes that all variables are captured 14865 // by references. Since there is no capture by copy, no expression 14866 // evaluation will be needed. 14867 RecordDecl *RD = RSI->TheRecordDecl; 14868 14869 FieldDecl *Field 14870 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14871 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14872 nullptr, false, ICIS_NoInit); 14873 Field->setImplicit(true); 14874 Field->setAccess(AS_private); 14875 RD->addDecl(Field); 14876 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14877 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14878 14879 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14880 DeclRefType, VK_LValue, Loc); 14881 Var->setReferenced(true); 14882 Var->markUsed(S.Context); 14883 } 14884 14885 // Actually capture the variable. 14886 if (BuildAndDiagnose) 14887 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14888 SourceLocation(), CaptureType, CopyExpr); 14889 14890 14891 return true; 14892 } 14893 14894 /// Create a field within the lambda class for the variable 14895 /// being captured. 14896 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14897 QualType FieldType, QualType DeclRefType, 14898 SourceLocation Loc, 14899 bool RefersToCapturedVariable) { 14900 CXXRecordDecl *Lambda = LSI->Lambda; 14901 14902 // Build the non-static data member. 14903 FieldDecl *Field 14904 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14905 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14906 nullptr, false, ICIS_NoInit); 14907 Field->setImplicit(true); 14908 Field->setAccess(AS_private); 14909 Lambda->addDecl(Field); 14910 } 14911 14912 /// Capture the given variable in the lambda. 14913 static bool captureInLambda(LambdaScopeInfo *LSI, 14914 VarDecl *Var, 14915 SourceLocation Loc, 14916 const bool BuildAndDiagnose, 14917 QualType &CaptureType, 14918 QualType &DeclRefType, 14919 const bool RefersToCapturedVariable, 14920 const Sema::TryCaptureKind Kind, 14921 SourceLocation EllipsisLoc, 14922 const bool IsTopScope, 14923 Sema &S) { 14924 14925 // Determine whether we are capturing by reference or by value. 14926 bool ByRef = false; 14927 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14928 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14929 } else { 14930 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14931 } 14932 14933 // Compute the type of the field that will capture this variable. 14934 if (ByRef) { 14935 // C++11 [expr.prim.lambda]p15: 14936 // An entity is captured by reference if it is implicitly or 14937 // explicitly captured but not captured by copy. It is 14938 // unspecified whether additional unnamed non-static data 14939 // members are declared in the closure type for entities 14940 // captured by reference. 14941 // 14942 // FIXME: It is not clear whether we want to build an lvalue reference 14943 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14944 // to do the former, while EDG does the latter. Core issue 1249 will 14945 // clarify, but for now we follow GCC because it's a more permissive and 14946 // easily defensible position. 14947 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14948 } else { 14949 // C++11 [expr.prim.lambda]p14: 14950 // For each entity captured by copy, an unnamed non-static 14951 // data member is declared in the closure type. The 14952 // declaration order of these members is unspecified. The type 14953 // of such a data member is the type of the corresponding 14954 // captured entity if the entity is not a reference to an 14955 // object, or the referenced type otherwise. [Note: If the 14956 // captured entity is a reference to a function, the 14957 // corresponding data member is also a reference to a 14958 // function. - end note ] 14959 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14960 if (!RefType->getPointeeType()->isFunctionType()) 14961 CaptureType = RefType->getPointeeType(); 14962 } 14963 14964 // Forbid the lambda copy-capture of autoreleasing variables. 14965 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14966 if (BuildAndDiagnose) { 14967 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14968 S.Diag(Var->getLocation(), diag::note_previous_decl) 14969 << Var->getDeclName(); 14970 } 14971 return false; 14972 } 14973 14974 // Make sure that by-copy captures are of a complete and non-abstract type. 14975 if (BuildAndDiagnose) { 14976 if (!CaptureType->isDependentType() && 14977 S.RequireCompleteType(Loc, CaptureType, 14978 diag::err_capture_of_incomplete_type, 14979 Var->getDeclName())) 14980 return false; 14981 14982 if (S.RequireNonAbstractType(Loc, CaptureType, 14983 diag::err_capture_of_abstract_type)) 14984 return false; 14985 } 14986 } 14987 14988 // Capture this variable in the lambda. 14989 if (BuildAndDiagnose) 14990 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14991 RefersToCapturedVariable); 14992 14993 // Compute the type of a reference to this captured variable. 14994 if (ByRef) 14995 DeclRefType = CaptureType.getNonReferenceType(); 14996 else { 14997 // C++ [expr.prim.lambda]p5: 14998 // The closure type for a lambda-expression has a public inline 14999 // function call operator [...]. This function call operator is 15000 // declared const (9.3.1) if and only if the lambda-expression's 15001 // parameter-declaration-clause is not followed by mutable. 15002 DeclRefType = CaptureType.getNonReferenceType(); 15003 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15004 DeclRefType.addConst(); 15005 } 15006 15007 // Add the capture. 15008 if (BuildAndDiagnose) 15009 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15010 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15011 15012 return true; 15013 } 15014 15015 bool Sema::tryCaptureVariable( 15016 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15017 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15018 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15019 // An init-capture is notionally from the context surrounding its 15020 // declaration, but its parent DC is the lambda class. 15021 DeclContext *VarDC = Var->getDeclContext(); 15022 if (Var->isInitCapture()) 15023 VarDC = VarDC->getParent(); 15024 15025 DeclContext *DC = CurContext; 15026 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15027 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15028 // We need to sync up the Declaration Context with the 15029 // FunctionScopeIndexToStopAt 15030 if (FunctionScopeIndexToStopAt) { 15031 unsigned FSIndex = FunctionScopes.size() - 1; 15032 while (FSIndex != MaxFunctionScopesIndex) { 15033 DC = getLambdaAwareParentOfDeclContext(DC); 15034 --FSIndex; 15035 } 15036 } 15037 15038 15039 // If the variable is declared in the current context, there is no need to 15040 // capture it. 15041 if (VarDC == DC) return true; 15042 15043 // Capture global variables if it is required to use private copy of this 15044 // variable. 15045 bool IsGlobal = !Var->hasLocalStorage(); 15046 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15047 return true; 15048 Var = Var->getCanonicalDecl(); 15049 15050 // Walk up the stack to determine whether we can capture the variable, 15051 // performing the "simple" checks that don't depend on type. We stop when 15052 // we've either hit the declared scope of the variable or find an existing 15053 // capture of that variable. We start from the innermost capturing-entity 15054 // (the DC) and ensure that all intervening capturing-entities 15055 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15056 // declcontext can either capture the variable or have already captured 15057 // the variable. 15058 CaptureType = Var->getType(); 15059 DeclRefType = CaptureType.getNonReferenceType(); 15060 bool Nested = false; 15061 bool Explicit = (Kind != TryCapture_Implicit); 15062 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15063 do { 15064 // Only block literals, captured statements, and lambda expressions can 15065 // capture; other scopes don't work. 15066 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15067 ExprLoc, 15068 BuildAndDiagnose, 15069 *this); 15070 // We need to check for the parent *first* because, if we *have* 15071 // private-captured a global variable, we need to recursively capture it in 15072 // intermediate blocks, lambdas, etc. 15073 if (!ParentDC) { 15074 if (IsGlobal) { 15075 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15076 break; 15077 } 15078 return true; 15079 } 15080 15081 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15082 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15083 15084 15085 // Check whether we've already captured it. 15086 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15087 DeclRefType)) { 15088 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15089 break; 15090 } 15091 // If we are instantiating a generic lambda call operator body, 15092 // we do not want to capture new variables. What was captured 15093 // during either a lambdas transformation or initial parsing 15094 // should be used. 15095 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15096 if (BuildAndDiagnose) { 15097 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15098 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15099 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15100 Diag(Var->getLocation(), diag::note_previous_decl) 15101 << Var->getDeclName(); 15102 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15103 } else 15104 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15105 } 15106 return true; 15107 } 15108 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15109 // certain types of variables (unnamed, variably modified types etc.) 15110 // so check for eligibility. 15111 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15112 return true; 15113 15114 // Try to capture variable-length arrays types. 15115 if (Var->getType()->isVariablyModifiedType()) { 15116 // We're going to walk down into the type and look for VLA 15117 // expressions. 15118 QualType QTy = Var->getType(); 15119 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15120 QTy = PVD->getOriginalType(); 15121 captureVariablyModifiedType(Context, QTy, CSI); 15122 } 15123 15124 if (getLangOpts().OpenMP) { 15125 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15126 // OpenMP private variables should not be captured in outer scope, so 15127 // just break here. Similarly, global variables that are captured in a 15128 // target region should not be captured outside the scope of the region. 15129 if (RSI->CapRegionKind == CR_OpenMP) { 15130 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15131 auto IsTargetCap = !IsOpenMPPrivateDecl && 15132 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15133 // When we detect target captures we are looking from inside the 15134 // target region, therefore we need to propagate the capture from the 15135 // enclosing region. Therefore, the capture is not initially nested. 15136 if (IsTargetCap) 15137 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15138 15139 if (IsTargetCap || IsOpenMPPrivateDecl) { 15140 Nested = !IsTargetCap; 15141 DeclRefType = DeclRefType.getUnqualifiedType(); 15142 CaptureType = Context.getLValueReferenceType(DeclRefType); 15143 break; 15144 } 15145 } 15146 } 15147 } 15148 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15149 // No capture-default, and this is not an explicit capture 15150 // so cannot capture this variable. 15151 if (BuildAndDiagnose) { 15152 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15153 Diag(Var->getLocation(), diag::note_previous_decl) 15154 << Var->getDeclName(); 15155 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15156 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15157 diag::note_lambda_decl); 15158 // FIXME: If we error out because an outer lambda can not implicitly 15159 // capture a variable that an inner lambda explicitly captures, we 15160 // should have the inner lambda do the explicit capture - because 15161 // it makes for cleaner diagnostics later. This would purely be done 15162 // so that the diagnostic does not misleadingly claim that a variable 15163 // can not be captured by a lambda implicitly even though it is captured 15164 // explicitly. Suggestion: 15165 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15166 // at the function head 15167 // - cache the StartingDeclContext - this must be a lambda 15168 // - captureInLambda in the innermost lambda the variable. 15169 } 15170 return true; 15171 } 15172 15173 FunctionScopesIndex--; 15174 DC = ParentDC; 15175 Explicit = false; 15176 } while (!VarDC->Equals(DC)); 15177 15178 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15179 // computing the type of the capture at each step, checking type-specific 15180 // requirements, and adding captures if requested. 15181 // If the variable had already been captured previously, we start capturing 15182 // at the lambda nested within that one. 15183 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15184 ++I) { 15185 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15186 15187 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15188 if (!captureInBlock(BSI, Var, ExprLoc, 15189 BuildAndDiagnose, CaptureType, 15190 DeclRefType, Nested, *this)) 15191 return true; 15192 Nested = true; 15193 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15194 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15195 BuildAndDiagnose, CaptureType, 15196 DeclRefType, Nested, *this)) 15197 return true; 15198 Nested = true; 15199 } else { 15200 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15201 if (!captureInLambda(LSI, Var, ExprLoc, 15202 BuildAndDiagnose, CaptureType, 15203 DeclRefType, Nested, Kind, EllipsisLoc, 15204 /*IsTopScope*/I == N - 1, *this)) 15205 return true; 15206 Nested = true; 15207 } 15208 } 15209 return false; 15210 } 15211 15212 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15213 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15214 QualType CaptureType; 15215 QualType DeclRefType; 15216 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15217 /*BuildAndDiagnose=*/true, CaptureType, 15218 DeclRefType, nullptr); 15219 } 15220 15221 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15222 QualType CaptureType; 15223 QualType DeclRefType; 15224 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15225 /*BuildAndDiagnose=*/false, CaptureType, 15226 DeclRefType, nullptr); 15227 } 15228 15229 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15230 QualType CaptureType; 15231 QualType DeclRefType; 15232 15233 // Determine whether we can capture this variable. 15234 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15235 /*BuildAndDiagnose=*/false, CaptureType, 15236 DeclRefType, nullptr)) 15237 return QualType(); 15238 15239 return DeclRefType; 15240 } 15241 15242 15243 15244 // If either the type of the variable or the initializer is dependent, 15245 // return false. Otherwise, determine whether the variable is a constant 15246 // expression. Use this if you need to know if a variable that might or 15247 // might not be dependent is truly a constant expression. 15248 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15249 ASTContext &Context) { 15250 15251 if (Var->getType()->isDependentType()) 15252 return false; 15253 const VarDecl *DefVD = nullptr; 15254 Var->getAnyInitializer(DefVD); 15255 if (!DefVD) 15256 return false; 15257 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15258 Expr *Init = cast<Expr>(Eval->Value); 15259 if (Init->isValueDependent()) 15260 return false; 15261 return IsVariableAConstantExpression(Var, Context); 15262 } 15263 15264 15265 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15266 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15267 // an object that satisfies the requirements for appearing in a 15268 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15269 // is immediately applied." This function handles the lvalue-to-rvalue 15270 // conversion part. 15271 MaybeODRUseExprs.erase(E->IgnoreParens()); 15272 15273 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15274 // to a variable that is a constant expression, and if so, identify it as 15275 // a reference to a variable that does not involve an odr-use of that 15276 // variable. 15277 if (LambdaScopeInfo *LSI = getCurLambda()) { 15278 Expr *SansParensExpr = E->IgnoreParens(); 15279 VarDecl *Var = nullptr; 15280 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15281 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15282 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15283 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15284 15285 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15286 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15287 } 15288 } 15289 15290 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15291 Res = CorrectDelayedTyposInExpr(Res); 15292 15293 if (!Res.isUsable()) 15294 return Res; 15295 15296 // If a constant-expression is a reference to a variable where we delay 15297 // deciding whether it is an odr-use, just assume we will apply the 15298 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15299 // (a non-type template argument), we have special handling anyway. 15300 UpdateMarkingForLValueToRValue(Res.get()); 15301 return Res; 15302 } 15303 15304 void Sema::CleanupVarDeclMarking() { 15305 for (Expr *E : MaybeODRUseExprs) { 15306 VarDecl *Var; 15307 SourceLocation Loc; 15308 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15309 Var = cast<VarDecl>(DRE->getDecl()); 15310 Loc = DRE->getLocation(); 15311 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15312 Var = cast<VarDecl>(ME->getMemberDecl()); 15313 Loc = ME->getMemberLoc(); 15314 } else { 15315 llvm_unreachable("Unexpected expression"); 15316 } 15317 15318 MarkVarDeclODRUsed(Var, Loc, *this, 15319 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15320 } 15321 15322 MaybeODRUseExprs.clear(); 15323 } 15324 15325 15326 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15327 VarDecl *Var, Expr *E) { 15328 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15329 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15330 Var->setReferenced(); 15331 15332 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15333 15334 bool OdrUseContext = isOdrUseContext(SemaRef); 15335 bool UsableInConstantExpr = 15336 Var->isUsableInConstantExpressions(SemaRef.Context); 15337 bool NeedDefinition = 15338 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15339 15340 VarTemplateSpecializationDecl *VarSpec = 15341 dyn_cast<VarTemplateSpecializationDecl>(Var); 15342 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15343 "Can't instantiate a partial template specialization."); 15344 15345 // If this might be a member specialization of a static data member, check 15346 // the specialization is visible. We already did the checks for variable 15347 // template specializations when we created them. 15348 if (NeedDefinition && TSK != TSK_Undeclared && 15349 !isa<VarTemplateSpecializationDecl>(Var)) 15350 SemaRef.checkSpecializationVisibility(Loc, Var); 15351 15352 // Perform implicit instantiation of static data members, static data member 15353 // templates of class templates, and variable template specializations. Delay 15354 // instantiations of variable templates, except for those that could be used 15355 // in a constant expression. 15356 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15357 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15358 // instantiation declaration if a variable is usable in a constant 15359 // expression (among other cases). 15360 bool TryInstantiating = 15361 TSK == TSK_ImplicitInstantiation || 15362 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15363 15364 if (TryInstantiating) { 15365 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15366 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15367 if (FirstInstantiation) { 15368 PointOfInstantiation = Loc; 15369 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15370 } 15371 15372 bool InstantiationDependent = false; 15373 bool IsNonDependent = 15374 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15375 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15376 : true; 15377 15378 // Do not instantiate specializations that are still type-dependent. 15379 if (IsNonDependent) { 15380 if (UsableInConstantExpr) { 15381 // Do not defer instantiations of variables that could be used in a 15382 // constant expression. 15383 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15384 } else if (FirstInstantiation || 15385 isa<VarTemplateSpecializationDecl>(Var)) { 15386 // FIXME: For a specialization of a variable template, we don't 15387 // distinguish between "declaration and type implicitly instantiated" 15388 // and "implicit instantiation of definition requested", so we have 15389 // no direct way to avoid enqueueing the pending instantiation 15390 // multiple times. 15391 SemaRef.PendingInstantiations 15392 .push_back(std::make_pair(Var, PointOfInstantiation)); 15393 } 15394 } 15395 } 15396 } 15397 15398 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15399 // the requirements for appearing in a constant expression (5.19) and, if 15400 // it is an object, the lvalue-to-rvalue conversion (4.1) 15401 // is immediately applied." We check the first part here, and 15402 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15403 // Note that we use the C++11 definition everywhere because nothing in 15404 // C++03 depends on whether we get the C++03 version correct. The second 15405 // part does not apply to references, since they are not objects. 15406 if (OdrUseContext && E && 15407 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15408 // A reference initialized by a constant expression can never be 15409 // odr-used, so simply ignore it. 15410 if (!Var->getType()->isReferenceType() || 15411 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15412 SemaRef.MaybeODRUseExprs.insert(E); 15413 } else if (OdrUseContext) { 15414 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15415 /*MaxFunctionScopeIndex ptr*/ nullptr); 15416 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15417 // If this is a dependent context, we don't need to mark variables as 15418 // odr-used, but we may still need to track them for lambda capture. 15419 // FIXME: Do we also need to do this inside dependent typeid expressions 15420 // (which are modeled as unevaluated at this point)? 15421 const bool RefersToEnclosingScope = 15422 (SemaRef.CurContext != Var->getDeclContext() && 15423 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15424 if (RefersToEnclosingScope) { 15425 LambdaScopeInfo *const LSI = 15426 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15427 if (LSI && (!LSI->CallOperator || 15428 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15429 // If a variable could potentially be odr-used, defer marking it so 15430 // until we finish analyzing the full expression for any 15431 // lvalue-to-rvalue 15432 // or discarded value conversions that would obviate odr-use. 15433 // Add it to the list of potential captures that will be analyzed 15434 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15435 // unless the variable is a reference that was initialized by a constant 15436 // expression (this will never need to be captured or odr-used). 15437 assert(E && "Capture variable should be used in an expression."); 15438 if (!Var->getType()->isReferenceType() || 15439 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15440 LSI->addPotentialCapture(E->IgnoreParens()); 15441 } 15442 } 15443 } 15444 } 15445 15446 /// Mark a variable referenced, and check whether it is odr-used 15447 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15448 /// used directly for normal expressions referring to VarDecl. 15449 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15450 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15451 } 15452 15453 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15454 Decl *D, Expr *E, bool MightBeOdrUse) { 15455 if (SemaRef.isInOpenMPDeclareTargetContext()) 15456 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15457 15458 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15459 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15460 return; 15461 } 15462 15463 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15464 15465 // If this is a call to a method via a cast, also mark the method in the 15466 // derived class used in case codegen can devirtualize the call. 15467 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15468 if (!ME) 15469 return; 15470 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15471 if (!MD) 15472 return; 15473 // Only attempt to devirtualize if this is truly a virtual call. 15474 bool IsVirtualCall = MD->isVirtual() && 15475 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15476 if (!IsVirtualCall) 15477 return; 15478 15479 // If it's possible to devirtualize the call, mark the called function 15480 // referenced. 15481 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15482 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15483 if (DM) 15484 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15485 } 15486 15487 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15488 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15489 // TODO: update this with DR# once a defect report is filed. 15490 // C++11 defect. The address of a pure member should not be an ODR use, even 15491 // if it's a qualified reference. 15492 bool OdrUse = true; 15493 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15494 if (Method->isVirtual() && 15495 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15496 OdrUse = false; 15497 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15498 } 15499 15500 /// Perform reference-marking and odr-use handling for a MemberExpr. 15501 void Sema::MarkMemberReferenced(MemberExpr *E) { 15502 // C++11 [basic.def.odr]p2: 15503 // A non-overloaded function whose name appears as a potentially-evaluated 15504 // expression or a member of a set of candidate functions, if selected by 15505 // overload resolution when referred to from a potentially-evaluated 15506 // expression, is odr-used, unless it is a pure virtual function and its 15507 // name is not explicitly qualified. 15508 bool MightBeOdrUse = true; 15509 if (E->performsVirtualDispatch(getLangOpts())) { 15510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15511 if (Method->isPure()) 15512 MightBeOdrUse = false; 15513 } 15514 SourceLocation Loc = 15515 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15516 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15517 } 15518 15519 /// Perform marking for a reference to an arbitrary declaration. It 15520 /// marks the declaration referenced, and performs odr-use checking for 15521 /// functions and variables. This method should not be used when building a 15522 /// normal expression which refers to a variable. 15523 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15524 bool MightBeOdrUse) { 15525 if (MightBeOdrUse) { 15526 if (auto *VD = dyn_cast<VarDecl>(D)) { 15527 MarkVariableReferenced(Loc, VD); 15528 return; 15529 } 15530 } 15531 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15532 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15533 return; 15534 } 15535 D->setReferenced(); 15536 } 15537 15538 namespace { 15539 // Mark all of the declarations used by a type as referenced. 15540 // FIXME: Not fully implemented yet! We need to have a better understanding 15541 // of when we're entering a context we should not recurse into. 15542 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15543 // TreeTransforms rebuilding the type in a new context. Rather than 15544 // duplicating the TreeTransform logic, we should consider reusing it here. 15545 // Currently that causes problems when rebuilding LambdaExprs. 15546 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15547 Sema &S; 15548 SourceLocation Loc; 15549 15550 public: 15551 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15552 15553 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15554 15555 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15556 }; 15557 } 15558 15559 bool MarkReferencedDecls::TraverseTemplateArgument( 15560 const TemplateArgument &Arg) { 15561 { 15562 // A non-type template argument is a constant-evaluated context. 15563 EnterExpressionEvaluationContext Evaluated( 15564 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15565 if (Arg.getKind() == TemplateArgument::Declaration) { 15566 if (Decl *D = Arg.getAsDecl()) 15567 S.MarkAnyDeclReferenced(Loc, D, true); 15568 } else if (Arg.getKind() == TemplateArgument::Expression) { 15569 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15570 } 15571 } 15572 15573 return Inherited::TraverseTemplateArgument(Arg); 15574 } 15575 15576 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15577 MarkReferencedDecls Marker(*this, Loc); 15578 Marker.TraverseType(T); 15579 } 15580 15581 namespace { 15582 /// Helper class that marks all of the declarations referenced by 15583 /// potentially-evaluated subexpressions as "referenced". 15584 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15585 Sema &S; 15586 bool SkipLocalVariables; 15587 15588 public: 15589 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15590 15591 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15592 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15593 15594 void VisitDeclRefExpr(DeclRefExpr *E) { 15595 // If we were asked not to visit local variables, don't. 15596 if (SkipLocalVariables) { 15597 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15598 if (VD->hasLocalStorage()) 15599 return; 15600 } 15601 15602 S.MarkDeclRefReferenced(E); 15603 } 15604 15605 void VisitMemberExpr(MemberExpr *E) { 15606 S.MarkMemberReferenced(E); 15607 Inherited::VisitMemberExpr(E); 15608 } 15609 15610 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15611 S.MarkFunctionReferenced( 15612 E->getBeginLoc(), 15613 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15614 Visit(E->getSubExpr()); 15615 } 15616 15617 void VisitCXXNewExpr(CXXNewExpr *E) { 15618 if (E->getOperatorNew()) 15619 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15620 if (E->getOperatorDelete()) 15621 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15622 Inherited::VisitCXXNewExpr(E); 15623 } 15624 15625 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15626 if (E->getOperatorDelete()) 15627 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15628 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15629 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15630 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15631 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15632 } 15633 15634 Inherited::VisitCXXDeleteExpr(E); 15635 } 15636 15637 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15638 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15639 Inherited::VisitCXXConstructExpr(E); 15640 } 15641 15642 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15643 Visit(E->getExpr()); 15644 } 15645 15646 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15647 Inherited::VisitImplicitCastExpr(E); 15648 15649 if (E->getCastKind() == CK_LValueToRValue) 15650 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15651 } 15652 }; 15653 } 15654 15655 /// Mark any declarations that appear within this expression or any 15656 /// potentially-evaluated subexpressions as "referenced". 15657 /// 15658 /// \param SkipLocalVariables If true, don't mark local variables as 15659 /// 'referenced'. 15660 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15661 bool SkipLocalVariables) { 15662 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15663 } 15664 15665 /// Emit a diagnostic that describes an effect on the run-time behavior 15666 /// of the program being compiled. 15667 /// 15668 /// This routine emits the given diagnostic when the code currently being 15669 /// type-checked is "potentially evaluated", meaning that there is a 15670 /// possibility that the code will actually be executable. Code in sizeof() 15671 /// expressions, code used only during overload resolution, etc., are not 15672 /// potentially evaluated. This routine will suppress such diagnostics or, 15673 /// in the absolutely nutty case of potentially potentially evaluated 15674 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15675 /// later. 15676 /// 15677 /// This routine should be used for all diagnostics that describe the run-time 15678 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15679 /// Failure to do so will likely result in spurious diagnostics or failures 15680 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15681 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15682 const PartialDiagnostic &PD) { 15683 switch (ExprEvalContexts.back().Context) { 15684 case ExpressionEvaluationContext::Unevaluated: 15685 case ExpressionEvaluationContext::UnevaluatedList: 15686 case ExpressionEvaluationContext::UnevaluatedAbstract: 15687 case ExpressionEvaluationContext::DiscardedStatement: 15688 // The argument will never be evaluated, so don't complain. 15689 break; 15690 15691 case ExpressionEvaluationContext::ConstantEvaluated: 15692 // Relevant diagnostics should be produced by constant evaluation. 15693 break; 15694 15695 case ExpressionEvaluationContext::PotentiallyEvaluated: 15696 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15697 if (Statement && getCurFunctionOrMethodDecl()) { 15698 FunctionScopes.back()->PossiblyUnreachableDiags. 15699 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15700 return true; 15701 } 15702 15703 // The initializer of a constexpr variable or of the first declaration of a 15704 // static data member is not syntactically a constant evaluated constant, 15705 // but nonetheless is always required to be a constant expression, so we 15706 // can skip diagnosing. 15707 // FIXME: Using the mangling context here is a hack. 15708 if (auto *VD = dyn_cast_or_null<VarDecl>( 15709 ExprEvalContexts.back().ManglingContextDecl)) { 15710 if (VD->isConstexpr() || 15711 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15712 break; 15713 // FIXME: For any other kind of variable, we should build a CFG for its 15714 // initializer and check whether the context in question is reachable. 15715 } 15716 15717 Diag(Loc, PD); 15718 return true; 15719 } 15720 15721 return false; 15722 } 15723 15724 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15725 CallExpr *CE, FunctionDecl *FD) { 15726 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15727 return false; 15728 15729 // If we're inside a decltype's expression, don't check for a valid return 15730 // type or construct temporaries until we know whether this is the last call. 15731 if (ExprEvalContexts.back().ExprContext == 15732 ExpressionEvaluationContextRecord::EK_Decltype) { 15733 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15734 return false; 15735 } 15736 15737 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15738 FunctionDecl *FD; 15739 CallExpr *CE; 15740 15741 public: 15742 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15743 : FD(FD), CE(CE) { } 15744 15745 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15746 if (!FD) { 15747 S.Diag(Loc, diag::err_call_incomplete_return) 15748 << T << CE->getSourceRange(); 15749 return; 15750 } 15751 15752 S.Diag(Loc, diag::err_call_function_incomplete_return) 15753 << CE->getSourceRange() << FD->getDeclName() << T; 15754 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15755 << FD->getDeclName(); 15756 } 15757 } Diagnoser(FD, CE); 15758 15759 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15760 return true; 15761 15762 return false; 15763 } 15764 15765 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15766 // will prevent this condition from triggering, which is what we want. 15767 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15768 SourceLocation Loc; 15769 15770 unsigned diagnostic = diag::warn_condition_is_assignment; 15771 bool IsOrAssign = false; 15772 15773 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15774 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15775 return; 15776 15777 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15778 15779 // Greylist some idioms by putting them into a warning subcategory. 15780 if (ObjCMessageExpr *ME 15781 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15782 Selector Sel = ME->getSelector(); 15783 15784 // self = [<foo> init...] 15785 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15786 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15787 15788 // <foo> = [<bar> nextObject] 15789 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15790 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15791 } 15792 15793 Loc = Op->getOperatorLoc(); 15794 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15795 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15796 return; 15797 15798 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15799 Loc = Op->getOperatorLoc(); 15800 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15801 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15802 else { 15803 // Not an assignment. 15804 return; 15805 } 15806 15807 Diag(Loc, diagnostic) << E->getSourceRange(); 15808 15809 SourceLocation Open = E->getBeginLoc(); 15810 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15811 Diag(Loc, diag::note_condition_assign_silence) 15812 << FixItHint::CreateInsertion(Open, "(") 15813 << FixItHint::CreateInsertion(Close, ")"); 15814 15815 if (IsOrAssign) 15816 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15817 << FixItHint::CreateReplacement(Loc, "!="); 15818 else 15819 Diag(Loc, diag::note_condition_assign_to_comparison) 15820 << FixItHint::CreateReplacement(Loc, "=="); 15821 } 15822 15823 /// Redundant parentheses over an equality comparison can indicate 15824 /// that the user intended an assignment used as condition. 15825 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15826 // Don't warn if the parens came from a macro. 15827 SourceLocation parenLoc = ParenE->getBeginLoc(); 15828 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15829 return; 15830 // Don't warn for dependent expressions. 15831 if (ParenE->isTypeDependent()) 15832 return; 15833 15834 Expr *E = ParenE->IgnoreParens(); 15835 15836 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15837 if (opE->getOpcode() == BO_EQ && 15838 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15839 == Expr::MLV_Valid) { 15840 SourceLocation Loc = opE->getOperatorLoc(); 15841 15842 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15843 SourceRange ParenERange = ParenE->getSourceRange(); 15844 Diag(Loc, diag::note_equality_comparison_silence) 15845 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15846 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15847 Diag(Loc, diag::note_equality_comparison_to_assign) 15848 << FixItHint::CreateReplacement(Loc, "="); 15849 } 15850 } 15851 15852 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15853 bool IsConstexpr) { 15854 DiagnoseAssignmentAsCondition(E); 15855 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15856 DiagnoseEqualityWithExtraParens(parenE); 15857 15858 ExprResult result = CheckPlaceholderExpr(E); 15859 if (result.isInvalid()) return ExprError(); 15860 E = result.get(); 15861 15862 if (!E->isTypeDependent()) { 15863 if (getLangOpts().CPlusPlus) 15864 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15865 15866 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15867 if (ERes.isInvalid()) 15868 return ExprError(); 15869 E = ERes.get(); 15870 15871 QualType T = E->getType(); 15872 if (!T->isScalarType()) { // C99 6.8.4.1p1 15873 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15874 << T << E->getSourceRange(); 15875 return ExprError(); 15876 } 15877 CheckBoolLikeConversion(E, Loc); 15878 } 15879 15880 return E; 15881 } 15882 15883 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15884 Expr *SubExpr, ConditionKind CK) { 15885 // Empty conditions are valid in for-statements. 15886 if (!SubExpr) 15887 return ConditionResult(); 15888 15889 ExprResult Cond; 15890 switch (CK) { 15891 case ConditionKind::Boolean: 15892 Cond = CheckBooleanCondition(Loc, SubExpr); 15893 break; 15894 15895 case ConditionKind::ConstexprIf: 15896 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15897 break; 15898 15899 case ConditionKind::Switch: 15900 Cond = CheckSwitchCondition(Loc, SubExpr); 15901 break; 15902 } 15903 if (Cond.isInvalid()) 15904 return ConditionError(); 15905 15906 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15907 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15908 if (!FullExpr.get()) 15909 return ConditionError(); 15910 15911 return ConditionResult(*this, nullptr, FullExpr, 15912 CK == ConditionKind::ConstexprIf); 15913 } 15914 15915 namespace { 15916 /// A visitor for rebuilding a call to an __unknown_any expression 15917 /// to have an appropriate type. 15918 struct RebuildUnknownAnyFunction 15919 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15920 15921 Sema &S; 15922 15923 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15924 15925 ExprResult VisitStmt(Stmt *S) { 15926 llvm_unreachable("unexpected statement!"); 15927 } 15928 15929 ExprResult VisitExpr(Expr *E) { 15930 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15931 << E->getSourceRange(); 15932 return ExprError(); 15933 } 15934 15935 /// Rebuild an expression which simply semantically wraps another 15936 /// expression which it shares the type and value kind of. 15937 template <class T> ExprResult rebuildSugarExpr(T *E) { 15938 ExprResult SubResult = Visit(E->getSubExpr()); 15939 if (SubResult.isInvalid()) return ExprError(); 15940 15941 Expr *SubExpr = SubResult.get(); 15942 E->setSubExpr(SubExpr); 15943 E->setType(SubExpr->getType()); 15944 E->setValueKind(SubExpr->getValueKind()); 15945 assert(E->getObjectKind() == OK_Ordinary); 15946 return E; 15947 } 15948 15949 ExprResult VisitParenExpr(ParenExpr *E) { 15950 return rebuildSugarExpr(E); 15951 } 15952 15953 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15954 return rebuildSugarExpr(E); 15955 } 15956 15957 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15958 ExprResult SubResult = Visit(E->getSubExpr()); 15959 if (SubResult.isInvalid()) return ExprError(); 15960 15961 Expr *SubExpr = SubResult.get(); 15962 E->setSubExpr(SubExpr); 15963 E->setType(S.Context.getPointerType(SubExpr->getType())); 15964 assert(E->getValueKind() == VK_RValue); 15965 assert(E->getObjectKind() == OK_Ordinary); 15966 return E; 15967 } 15968 15969 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15970 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15971 15972 E->setType(VD->getType()); 15973 15974 assert(E->getValueKind() == VK_RValue); 15975 if (S.getLangOpts().CPlusPlus && 15976 !(isa<CXXMethodDecl>(VD) && 15977 cast<CXXMethodDecl>(VD)->isInstance())) 15978 E->setValueKind(VK_LValue); 15979 15980 return E; 15981 } 15982 15983 ExprResult VisitMemberExpr(MemberExpr *E) { 15984 return resolveDecl(E, E->getMemberDecl()); 15985 } 15986 15987 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15988 return resolveDecl(E, E->getDecl()); 15989 } 15990 }; 15991 } 15992 15993 /// Given a function expression of unknown-any type, try to rebuild it 15994 /// to have a function type. 15995 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15996 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15997 if (Result.isInvalid()) return ExprError(); 15998 return S.DefaultFunctionArrayConversion(Result.get()); 15999 } 16000 16001 namespace { 16002 /// A visitor for rebuilding an expression of type __unknown_anytype 16003 /// into one which resolves the type directly on the referring 16004 /// expression. Strict preservation of the original source 16005 /// structure is not a goal. 16006 struct RebuildUnknownAnyExpr 16007 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16008 16009 Sema &S; 16010 16011 /// The current destination type. 16012 QualType DestType; 16013 16014 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16015 : S(S), DestType(CastType) {} 16016 16017 ExprResult VisitStmt(Stmt *S) { 16018 llvm_unreachable("unexpected statement!"); 16019 } 16020 16021 ExprResult VisitExpr(Expr *E) { 16022 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16023 << E->getSourceRange(); 16024 return ExprError(); 16025 } 16026 16027 ExprResult VisitCallExpr(CallExpr *E); 16028 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16029 16030 /// Rebuild an expression which simply semantically wraps another 16031 /// expression which it shares the type and value kind of. 16032 template <class T> ExprResult rebuildSugarExpr(T *E) { 16033 ExprResult SubResult = Visit(E->getSubExpr()); 16034 if (SubResult.isInvalid()) return ExprError(); 16035 Expr *SubExpr = SubResult.get(); 16036 E->setSubExpr(SubExpr); 16037 E->setType(SubExpr->getType()); 16038 E->setValueKind(SubExpr->getValueKind()); 16039 assert(E->getObjectKind() == OK_Ordinary); 16040 return E; 16041 } 16042 16043 ExprResult VisitParenExpr(ParenExpr *E) { 16044 return rebuildSugarExpr(E); 16045 } 16046 16047 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16048 return rebuildSugarExpr(E); 16049 } 16050 16051 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16052 const PointerType *Ptr = DestType->getAs<PointerType>(); 16053 if (!Ptr) { 16054 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16055 << E->getSourceRange(); 16056 return ExprError(); 16057 } 16058 16059 if (isa<CallExpr>(E->getSubExpr())) { 16060 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16061 << E->getSourceRange(); 16062 return ExprError(); 16063 } 16064 16065 assert(E->getValueKind() == VK_RValue); 16066 assert(E->getObjectKind() == OK_Ordinary); 16067 E->setType(DestType); 16068 16069 // Build the sub-expression as if it were an object of the pointee type. 16070 DestType = Ptr->getPointeeType(); 16071 ExprResult SubResult = Visit(E->getSubExpr()); 16072 if (SubResult.isInvalid()) return ExprError(); 16073 E->setSubExpr(SubResult.get()); 16074 return E; 16075 } 16076 16077 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16078 16079 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16080 16081 ExprResult VisitMemberExpr(MemberExpr *E) { 16082 return resolveDecl(E, E->getMemberDecl()); 16083 } 16084 16085 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16086 return resolveDecl(E, E->getDecl()); 16087 } 16088 }; 16089 } 16090 16091 /// Rebuilds a call expression which yielded __unknown_anytype. 16092 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16093 Expr *CalleeExpr = E->getCallee(); 16094 16095 enum FnKind { 16096 FK_MemberFunction, 16097 FK_FunctionPointer, 16098 FK_BlockPointer 16099 }; 16100 16101 FnKind Kind; 16102 QualType CalleeType = CalleeExpr->getType(); 16103 if (CalleeType == S.Context.BoundMemberTy) { 16104 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16105 Kind = FK_MemberFunction; 16106 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16107 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16108 CalleeType = Ptr->getPointeeType(); 16109 Kind = FK_FunctionPointer; 16110 } else { 16111 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16112 Kind = FK_BlockPointer; 16113 } 16114 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16115 16116 // Verify that this is a legal result type of a function. 16117 if (DestType->isArrayType() || DestType->isFunctionType()) { 16118 unsigned diagID = diag::err_func_returning_array_function; 16119 if (Kind == FK_BlockPointer) 16120 diagID = diag::err_block_returning_array_function; 16121 16122 S.Diag(E->getExprLoc(), diagID) 16123 << DestType->isFunctionType() << DestType; 16124 return ExprError(); 16125 } 16126 16127 // Otherwise, go ahead and set DestType as the call's result. 16128 E->setType(DestType.getNonLValueExprType(S.Context)); 16129 E->setValueKind(Expr::getValueKindForType(DestType)); 16130 assert(E->getObjectKind() == OK_Ordinary); 16131 16132 // Rebuild the function type, replacing the result type with DestType. 16133 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16134 if (Proto) { 16135 // __unknown_anytype(...) is a special case used by the debugger when 16136 // it has no idea what a function's signature is. 16137 // 16138 // We want to build this call essentially under the K&R 16139 // unprototyped rules, but making a FunctionNoProtoType in C++ 16140 // would foul up all sorts of assumptions. However, we cannot 16141 // simply pass all arguments as variadic arguments, nor can we 16142 // portably just call the function under a non-variadic type; see 16143 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16144 // However, it turns out that in practice it is generally safe to 16145 // call a function declared as "A foo(B,C,D);" under the prototype 16146 // "A foo(B,C,D,...);". The only known exception is with the 16147 // Windows ABI, where any variadic function is implicitly cdecl 16148 // regardless of its normal CC. Therefore we change the parameter 16149 // types to match the types of the arguments. 16150 // 16151 // This is a hack, but it is far superior to moving the 16152 // corresponding target-specific code from IR-gen to Sema/AST. 16153 16154 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16155 SmallVector<QualType, 8> ArgTypes; 16156 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16157 ArgTypes.reserve(E->getNumArgs()); 16158 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16159 Expr *Arg = E->getArg(i); 16160 QualType ArgType = Arg->getType(); 16161 if (E->isLValue()) { 16162 ArgType = S.Context.getLValueReferenceType(ArgType); 16163 } else if (E->isXValue()) { 16164 ArgType = S.Context.getRValueReferenceType(ArgType); 16165 } 16166 ArgTypes.push_back(ArgType); 16167 } 16168 ParamTypes = ArgTypes; 16169 } 16170 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16171 Proto->getExtProtoInfo()); 16172 } else { 16173 DestType = S.Context.getFunctionNoProtoType(DestType, 16174 FnType->getExtInfo()); 16175 } 16176 16177 // Rebuild the appropriate pointer-to-function type. 16178 switch (Kind) { 16179 case FK_MemberFunction: 16180 // Nothing to do. 16181 break; 16182 16183 case FK_FunctionPointer: 16184 DestType = S.Context.getPointerType(DestType); 16185 break; 16186 16187 case FK_BlockPointer: 16188 DestType = S.Context.getBlockPointerType(DestType); 16189 break; 16190 } 16191 16192 // Finally, we can recurse. 16193 ExprResult CalleeResult = Visit(CalleeExpr); 16194 if (!CalleeResult.isUsable()) return ExprError(); 16195 E->setCallee(CalleeResult.get()); 16196 16197 // Bind a temporary if necessary. 16198 return S.MaybeBindToTemporary(E); 16199 } 16200 16201 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16202 // Verify that this is a legal result type of a call. 16203 if (DestType->isArrayType() || DestType->isFunctionType()) { 16204 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16205 << DestType->isFunctionType() << DestType; 16206 return ExprError(); 16207 } 16208 16209 // Rewrite the method result type if available. 16210 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16211 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16212 Method->setReturnType(DestType); 16213 } 16214 16215 // Change the type of the message. 16216 E->setType(DestType.getNonReferenceType()); 16217 E->setValueKind(Expr::getValueKindForType(DestType)); 16218 16219 return S.MaybeBindToTemporary(E); 16220 } 16221 16222 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16223 // The only case we should ever see here is a function-to-pointer decay. 16224 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16225 assert(E->getValueKind() == VK_RValue); 16226 assert(E->getObjectKind() == OK_Ordinary); 16227 16228 E->setType(DestType); 16229 16230 // Rebuild the sub-expression as the pointee (function) type. 16231 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16232 16233 ExprResult Result = Visit(E->getSubExpr()); 16234 if (!Result.isUsable()) return ExprError(); 16235 16236 E->setSubExpr(Result.get()); 16237 return E; 16238 } else if (E->getCastKind() == CK_LValueToRValue) { 16239 assert(E->getValueKind() == VK_RValue); 16240 assert(E->getObjectKind() == OK_Ordinary); 16241 16242 assert(isa<BlockPointerType>(E->getType())); 16243 16244 E->setType(DestType); 16245 16246 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16247 DestType = S.Context.getLValueReferenceType(DestType); 16248 16249 ExprResult Result = Visit(E->getSubExpr()); 16250 if (!Result.isUsable()) return ExprError(); 16251 16252 E->setSubExpr(Result.get()); 16253 return E; 16254 } else { 16255 llvm_unreachable("Unhandled cast type!"); 16256 } 16257 } 16258 16259 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16260 ExprValueKind ValueKind = VK_LValue; 16261 QualType Type = DestType; 16262 16263 // We know how to make this work for certain kinds of decls: 16264 16265 // - functions 16266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16267 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16268 DestType = Ptr->getPointeeType(); 16269 ExprResult Result = resolveDecl(E, VD); 16270 if (Result.isInvalid()) return ExprError(); 16271 return S.ImpCastExprToType(Result.get(), Type, 16272 CK_FunctionToPointerDecay, VK_RValue); 16273 } 16274 16275 if (!Type->isFunctionType()) { 16276 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16277 << VD << E->getSourceRange(); 16278 return ExprError(); 16279 } 16280 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16281 // We must match the FunctionDecl's type to the hack introduced in 16282 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16283 // type. See the lengthy commentary in that routine. 16284 QualType FDT = FD->getType(); 16285 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16286 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16287 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16288 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16289 SourceLocation Loc = FD->getLocation(); 16290 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16291 FD->getDeclContext(), 16292 Loc, Loc, FD->getNameInfo().getName(), 16293 DestType, FD->getTypeSourceInfo(), 16294 SC_None, false/*isInlineSpecified*/, 16295 FD->hasPrototype(), 16296 false/*isConstexprSpecified*/); 16297 16298 if (FD->getQualifier()) 16299 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16300 16301 SmallVector<ParmVarDecl*, 16> Params; 16302 for (const auto &AI : FT->param_types()) { 16303 ParmVarDecl *Param = 16304 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16305 Param->setScopeInfo(0, Params.size()); 16306 Params.push_back(Param); 16307 } 16308 NewFD->setParams(Params); 16309 DRE->setDecl(NewFD); 16310 VD = DRE->getDecl(); 16311 } 16312 } 16313 16314 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16315 if (MD->isInstance()) { 16316 ValueKind = VK_RValue; 16317 Type = S.Context.BoundMemberTy; 16318 } 16319 16320 // Function references aren't l-values in C. 16321 if (!S.getLangOpts().CPlusPlus) 16322 ValueKind = VK_RValue; 16323 16324 // - variables 16325 } else if (isa<VarDecl>(VD)) { 16326 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16327 Type = RefTy->getPointeeType(); 16328 } else if (Type->isFunctionType()) { 16329 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16330 << VD << E->getSourceRange(); 16331 return ExprError(); 16332 } 16333 16334 // - nothing else 16335 } else { 16336 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16337 << VD << E->getSourceRange(); 16338 return ExprError(); 16339 } 16340 16341 // Modifying the declaration like this is friendly to IR-gen but 16342 // also really dangerous. 16343 VD->setType(DestType); 16344 E->setType(Type); 16345 E->setValueKind(ValueKind); 16346 return E; 16347 } 16348 16349 /// Check a cast of an unknown-any type. We intentionally only 16350 /// trigger this for C-style casts. 16351 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16352 Expr *CastExpr, CastKind &CastKind, 16353 ExprValueKind &VK, CXXCastPath &Path) { 16354 // The type we're casting to must be either void or complete. 16355 if (!CastType->isVoidType() && 16356 RequireCompleteType(TypeRange.getBegin(), CastType, 16357 diag::err_typecheck_cast_to_incomplete)) 16358 return ExprError(); 16359 16360 // Rewrite the casted expression from scratch. 16361 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16362 if (!result.isUsable()) return ExprError(); 16363 16364 CastExpr = result.get(); 16365 VK = CastExpr->getValueKind(); 16366 CastKind = CK_NoOp; 16367 16368 return CastExpr; 16369 } 16370 16371 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16372 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16373 } 16374 16375 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16376 Expr *arg, QualType ¶mType) { 16377 // If the syntactic form of the argument is not an explicit cast of 16378 // any sort, just do default argument promotion. 16379 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16380 if (!castArg) { 16381 ExprResult result = DefaultArgumentPromotion(arg); 16382 if (result.isInvalid()) return ExprError(); 16383 paramType = result.get()->getType(); 16384 return result; 16385 } 16386 16387 // Otherwise, use the type that was written in the explicit cast. 16388 assert(!arg->hasPlaceholderType()); 16389 paramType = castArg->getTypeAsWritten(); 16390 16391 // Copy-initialize a parameter of that type. 16392 InitializedEntity entity = 16393 InitializedEntity::InitializeParameter(Context, paramType, 16394 /*consumed*/ false); 16395 return PerformCopyInitialization(entity, callLoc, arg); 16396 } 16397 16398 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16399 Expr *orig = E; 16400 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16401 while (true) { 16402 E = E->IgnoreParenImpCasts(); 16403 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16404 E = call->getCallee(); 16405 diagID = diag::err_uncasted_call_of_unknown_any; 16406 } else { 16407 break; 16408 } 16409 } 16410 16411 SourceLocation loc; 16412 NamedDecl *d; 16413 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16414 loc = ref->getLocation(); 16415 d = ref->getDecl(); 16416 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16417 loc = mem->getMemberLoc(); 16418 d = mem->getMemberDecl(); 16419 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16420 diagID = diag::err_uncasted_call_of_unknown_any; 16421 loc = msg->getSelectorStartLoc(); 16422 d = msg->getMethodDecl(); 16423 if (!d) { 16424 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16425 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16426 << orig->getSourceRange(); 16427 return ExprError(); 16428 } 16429 } else { 16430 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16431 << E->getSourceRange(); 16432 return ExprError(); 16433 } 16434 16435 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16436 16437 // Never recoverable. 16438 return ExprError(); 16439 } 16440 16441 /// Check for operands with placeholder types and complain if found. 16442 /// Returns ExprError() if there was an error and no recovery was possible. 16443 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16444 if (!getLangOpts().CPlusPlus) { 16445 // C cannot handle TypoExpr nodes on either side of a binop because it 16446 // doesn't handle dependent types properly, so make sure any TypoExprs have 16447 // been dealt with before checking the operands. 16448 ExprResult Result = CorrectDelayedTyposInExpr(E); 16449 if (!Result.isUsable()) return ExprError(); 16450 E = Result.get(); 16451 } 16452 16453 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16454 if (!placeholderType) return E; 16455 16456 switch (placeholderType->getKind()) { 16457 16458 // Overloaded expressions. 16459 case BuiltinType::Overload: { 16460 // Try to resolve a single function template specialization. 16461 // This is obligatory. 16462 ExprResult Result = E; 16463 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16464 return Result; 16465 16466 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16467 // leaves Result unchanged on failure. 16468 Result = E; 16469 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16470 return Result; 16471 16472 // If that failed, try to recover with a call. 16473 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16474 /*complain*/ true); 16475 return Result; 16476 } 16477 16478 // Bound member functions. 16479 case BuiltinType::BoundMember: { 16480 ExprResult result = E; 16481 const Expr *BME = E->IgnoreParens(); 16482 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16483 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16484 if (isa<CXXPseudoDestructorExpr>(BME)) { 16485 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16486 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16487 if (ME->getMemberNameInfo().getName().getNameKind() == 16488 DeclarationName::CXXDestructorName) 16489 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16490 } 16491 tryToRecoverWithCall(result, PD, 16492 /*complain*/ true); 16493 return result; 16494 } 16495 16496 // ARC unbridged casts. 16497 case BuiltinType::ARCUnbridgedCast: { 16498 Expr *realCast = stripARCUnbridgedCast(E); 16499 diagnoseARCUnbridgedCast(realCast); 16500 return realCast; 16501 } 16502 16503 // Expressions of unknown type. 16504 case BuiltinType::UnknownAny: 16505 return diagnoseUnknownAnyExpr(*this, E); 16506 16507 // Pseudo-objects. 16508 case BuiltinType::PseudoObject: 16509 return checkPseudoObjectRValue(E); 16510 16511 case BuiltinType::BuiltinFn: { 16512 // Accept __noop without parens by implicitly converting it to a call expr. 16513 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16514 if (DRE) { 16515 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16516 if (FD->getBuiltinID() == Builtin::BI__noop) { 16517 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16518 CK_BuiltinFnToFnPtr).get(); 16519 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16520 VK_RValue, SourceLocation()); 16521 } 16522 } 16523 16524 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16525 return ExprError(); 16526 } 16527 16528 // Expressions of unknown type. 16529 case BuiltinType::OMPArraySection: 16530 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16531 return ExprError(); 16532 16533 // Everything else should be impossible. 16534 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16535 case BuiltinType::Id: 16536 #include "clang/Basic/OpenCLImageTypes.def" 16537 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16538 #define PLACEHOLDER_TYPE(Id, SingletonId) 16539 #include "clang/AST/BuiltinTypes.def" 16540 break; 16541 } 16542 16543 llvm_unreachable("invalid placeholder type!"); 16544 } 16545 16546 bool Sema::CheckCaseExpression(Expr *E) { 16547 if (E->isTypeDependent()) 16548 return true; 16549 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16550 return E->getType()->isIntegralOrEnumerationType(); 16551 return false; 16552 } 16553 16554 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16555 ExprResult 16556 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16557 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16558 "Unknown Objective-C Boolean value!"); 16559 QualType BoolT = Context.ObjCBuiltinBoolTy; 16560 if (!Context.getBOOLDecl()) { 16561 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16562 Sema::LookupOrdinaryName); 16563 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16564 NamedDecl *ND = Result.getFoundDecl(); 16565 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16566 Context.setBOOLDecl(TD); 16567 } 16568 } 16569 if (Context.getBOOLDecl()) 16570 BoolT = Context.getBOOLType(); 16571 return new (Context) 16572 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16573 } 16574 16575 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16576 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16577 SourceLocation RParen) { 16578 16579 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16580 16581 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16582 [&](const AvailabilitySpec &Spec) { 16583 return Spec.getPlatform() == Platform; 16584 }); 16585 16586 VersionTuple Version; 16587 if (Spec != AvailSpecs.end()) 16588 Version = Spec->getVersion(); 16589 16590 // The use of `@available` in the enclosing function should be analyzed to 16591 // warn when it's used inappropriately (i.e. not if(@available)). 16592 if (getCurFunctionOrMethodDecl()) 16593 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16594 else if (getCurBlock() || getCurLambda()) 16595 getCurFunction()->HasPotentialAvailabilityViolations = true; 16596 16597 return new (Context) 16598 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16599 } 16600