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/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) { 83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 84 if (DC && !DC->hasAttr<UnusedAttr>()) 85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 86 } 87 } 88 } 89 90 /// \brief Emit a note explaining that this function is deleted. 91 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 92 assert(Decl->isDeleted()); 93 94 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 95 96 if (Method && Method->isDeleted() && Method->isDefaulted()) { 97 // If the method was explicitly defaulted, point at that declaration. 98 if (!Method->isImplicit()) 99 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 100 101 // Try to diagnose why this special member function was implicitly 102 // deleted. This might fail, if that reason no longer applies. 103 CXXSpecialMember CSM = getSpecialMember(Method); 104 if (CSM != CXXInvalid) 105 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 106 107 return; 108 } 109 110 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 111 if (Ctor && Ctor->isInheritingConstructor()) 112 return NoteDeletedInheritingConstructor(Ctor); 113 114 Diag(Decl->getLocation(), diag::note_availability_specified_here) 115 << Decl << true; 116 } 117 118 /// \brief Determine whether a FunctionDecl was ever declared with an 119 /// explicit storage class. 120 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 121 for (auto I : D->redecls()) { 122 if (I->getStorageClass() != SC_None) 123 return true; 124 } 125 return false; 126 } 127 128 /// \brief Check whether we're in an extern inline function and referring to a 129 /// variable or function with internal linkage (C11 6.7.4p3). 130 /// 131 /// This is only a warning because we used to silently accept this code, but 132 /// in many cases it will not behave correctly. This is not enabled in C++ mode 133 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 134 /// and so while there may still be user mistakes, most of the time we can't 135 /// prove that there are errors. 136 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 137 const NamedDecl *D, 138 SourceLocation Loc) { 139 // This is disabled under C++; there are too many ways for this to fire in 140 // contexts where the warning is a false positive, or where it is technically 141 // correct but benign. 142 if (S.getLangOpts().CPlusPlus) 143 return; 144 145 // Check if this is an inlined function or method. 146 FunctionDecl *Current = S.getCurFunctionDecl(); 147 if (!Current) 148 return; 149 if (!Current->isInlined()) 150 return; 151 if (!Current->isExternallyVisible()) 152 return; 153 154 // Check if the decl has internal linkage. 155 if (D->getFormalLinkage() != InternalLinkage) 156 return; 157 158 // Downgrade from ExtWarn to Extension if 159 // (1) the supposedly external inline function is in the main file, 160 // and probably won't be included anywhere else. 161 // (2) the thing we're referencing is a pure function. 162 // (3) the thing we're referencing is another inline function. 163 // This last can give us false negatives, but it's better than warning on 164 // wrappers for simple C library functions. 165 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 166 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 167 if (!DowngradeWarning && UsedFn) 168 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 169 170 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 171 : diag::ext_internal_in_extern_inline) 172 << /*IsVar=*/!UsedFn << D; 173 174 S.MaybeSuggestAddingStaticToDecl(Current); 175 176 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 177 << D; 178 } 179 180 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 181 const FunctionDecl *First = Cur->getFirstDecl(); 182 183 // Suggest "static" on the function, if possible. 184 if (!hasAnyExplicitStorageClass(First)) { 185 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 186 Diag(DeclBegin, diag::note_convert_inline_to_static) 187 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 188 } 189 } 190 191 /// \brief Determine whether the use of this declaration is valid, and 192 /// emit any corresponding diagnostics. 193 /// 194 /// This routine diagnoses various problems with referencing 195 /// declarations that can occur when using a declaration. For example, 196 /// it might warn if a deprecated or unavailable declaration is being 197 /// used, or produce an error (and return true) if a C++0x deleted 198 /// function is being used. 199 /// 200 /// \returns true if there was an error (this declaration cannot be 201 /// referenced), false otherwise. 202 /// 203 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 204 const ObjCInterfaceDecl *UnknownObjCClass, 205 bool ObjCPropertyAccess, 206 bool AvoidPartialAvailabilityChecks) { 207 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 208 // If there were any diagnostics suppressed by template argument deduction, 209 // emit them now. 210 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 211 if (Pos != SuppressedDiagnostics.end()) { 212 for (const PartialDiagnosticAt &Suppressed : Pos->second) 213 Diag(Suppressed.first, Suppressed.second); 214 215 // Clear out the list of suppressed diagnostics, so that we don't emit 216 // them again for this specialization. However, we don't obsolete this 217 // entry from the table, because we want to avoid ever emitting these 218 // diagnostics again. 219 Pos->second.clear(); 220 } 221 222 // C++ [basic.start.main]p3: 223 // The function 'main' shall not be used within a program. 224 if (cast<FunctionDecl>(D)->isMain()) 225 Diag(Loc, diag::ext_main_used); 226 } 227 228 // See if this is an auto-typed variable whose initializer we are parsing. 229 if (ParsingInitForAutoVars.count(D)) { 230 if (isa<BindingDecl>(D)) { 231 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 232 << D->getDeclName(); 233 } else { 234 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 235 << D->getDeclName() << cast<VarDecl>(D)->getType(); 236 } 237 return true; 238 } 239 240 // See if this is a deleted function. 241 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 242 if (FD->isDeleted()) { 243 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 244 if (Ctor && Ctor->isInheritingConstructor()) 245 Diag(Loc, diag::err_deleted_inherited_ctor_use) 246 << Ctor->getParent() 247 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 248 else 249 Diag(Loc, diag::err_deleted_function_use); 250 NoteDeletedFunction(FD); 251 return true; 252 } 253 254 // If the function has a deduced return type, and we can't deduce it, 255 // then we can't use it either. 256 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 257 DeduceReturnType(FD, Loc)) 258 return true; 259 260 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 261 return true; 262 } 263 264 auto getReferencedObjCProp = [](const NamedDecl *D) -> 265 const ObjCPropertyDecl * { 266 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 267 return MD->findPropertyDecl(); 268 return nullptr; 269 }; 270 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 271 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 272 return true; 273 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 274 return true; 275 } 276 277 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 278 // Only the variables omp_in and omp_out are allowed in the combiner. 279 // Only the variables omp_priv and omp_orig are allowed in the 280 // initializer-clause. 281 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 282 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 283 isa<VarDecl>(D)) { 284 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 285 << getCurFunction()->HasOMPDeclareReductionCombiner; 286 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 287 return true; 288 } 289 290 DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess, 291 AvoidPartialAvailabilityChecks); 292 293 DiagnoseUnusedOfDecl(*this, D, Loc); 294 295 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 296 297 return false; 298 } 299 300 /// \brief Retrieve the message suffix that should be added to a 301 /// diagnostic complaining about the given function being deleted or 302 /// unavailable. 303 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 304 std::string Message; 305 if (FD->getAvailability(&Message)) 306 return ": " + Message; 307 308 return std::string(); 309 } 310 311 /// DiagnoseSentinelCalls - This routine checks whether a call or 312 /// message-send is to a declaration with the sentinel attribute, and 313 /// if so, it checks that the requirements of the sentinel are 314 /// satisfied. 315 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 316 ArrayRef<Expr *> Args) { 317 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 318 if (!attr) 319 return; 320 321 // The number of formal parameters of the declaration. 322 unsigned numFormalParams; 323 324 // The kind of declaration. This is also an index into a %select in 325 // the diagnostic. 326 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 327 328 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 329 numFormalParams = MD->param_size(); 330 calleeType = CT_Method; 331 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 332 numFormalParams = FD->param_size(); 333 calleeType = CT_Function; 334 } else if (isa<VarDecl>(D)) { 335 QualType type = cast<ValueDecl>(D)->getType(); 336 const FunctionType *fn = nullptr; 337 if (const PointerType *ptr = type->getAs<PointerType>()) { 338 fn = ptr->getPointeeType()->getAs<FunctionType>(); 339 if (!fn) return; 340 calleeType = CT_Function; 341 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 342 fn = ptr->getPointeeType()->castAs<FunctionType>(); 343 calleeType = CT_Block; 344 } else { 345 return; 346 } 347 348 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 349 numFormalParams = proto->getNumParams(); 350 } else { 351 numFormalParams = 0; 352 } 353 } else { 354 return; 355 } 356 357 // "nullPos" is the number of formal parameters at the end which 358 // effectively count as part of the variadic arguments. This is 359 // useful if you would prefer to not have *any* formal parameters, 360 // but the language forces you to have at least one. 361 unsigned nullPos = attr->getNullPos(); 362 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 363 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 364 365 // The number of arguments which should follow the sentinel. 366 unsigned numArgsAfterSentinel = attr->getSentinel(); 367 368 // If there aren't enough arguments for all the formal parameters, 369 // the sentinel, and the args after the sentinel, complain. 370 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 371 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 372 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 373 return; 374 } 375 376 // Otherwise, find the sentinel expression. 377 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 378 if (!sentinelExpr) return; 379 if (sentinelExpr->isValueDependent()) return; 380 if (Context.isSentinelNullExpr(sentinelExpr)) return; 381 382 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 383 // or 'NULL' if those are actually defined in the context. Only use 384 // 'nil' for ObjC methods, where it's much more likely that the 385 // variadic arguments form a list of object pointers. 386 SourceLocation MissingNilLoc 387 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 388 std::string NullValue; 389 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 390 NullValue = "nil"; 391 else if (getLangOpts().CPlusPlus11) 392 NullValue = "nullptr"; 393 else if (PP.isMacroDefined("NULL")) 394 NullValue = "NULL"; 395 else 396 NullValue = "(void*) 0"; 397 398 if (MissingNilLoc.isInvalid()) 399 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 400 else 401 Diag(MissingNilLoc, diag::warn_missing_sentinel) 402 << int(calleeType) 403 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 404 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 405 } 406 407 SourceRange Sema::getExprRange(Expr *E) const { 408 return E ? E->getSourceRange() : SourceRange(); 409 } 410 411 //===----------------------------------------------------------------------===// 412 // Standard Promotions and Conversions 413 //===----------------------------------------------------------------------===// 414 415 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 416 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 417 // Handle any placeholder expressions which made it here. 418 if (E->getType()->isPlaceholderType()) { 419 ExprResult result = CheckPlaceholderExpr(E); 420 if (result.isInvalid()) return ExprError(); 421 E = result.get(); 422 } 423 424 QualType Ty = E->getType(); 425 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 426 427 if (Ty->isFunctionType()) { 428 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 429 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 430 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 431 return ExprError(); 432 433 E = ImpCastExprToType(E, Context.getPointerType(Ty), 434 CK_FunctionToPointerDecay).get(); 435 } else if (Ty->isArrayType()) { 436 // In C90 mode, arrays only promote to pointers if the array expression is 437 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 438 // type 'array of type' is converted to an expression that has type 'pointer 439 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 440 // that has type 'array of type' ...". The relevant change is "an lvalue" 441 // (C90) to "an expression" (C99). 442 // 443 // C++ 4.2p1: 444 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 445 // T" can be converted to an rvalue of type "pointer to T". 446 // 447 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 448 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 449 CK_ArrayToPointerDecay).get(); 450 } 451 return E; 452 } 453 454 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 455 // Check to see if we are dereferencing a null pointer. If so, 456 // and if not volatile-qualified, this is undefined behavior that the 457 // optimizer will delete, so warn about it. People sometimes try to use this 458 // to get a deterministic trap and are surprised by clang's behavior. This 459 // only handles the pattern "*null", which is a very syntactic check. 460 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 461 if (UO->getOpcode() == UO_Deref && 462 UO->getSubExpr()->IgnoreParenCasts()-> 463 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 464 !UO->getType().isVolatileQualified()) { 465 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 466 S.PDiag(diag::warn_indirection_through_null) 467 << UO->getSubExpr()->getSourceRange()); 468 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 469 S.PDiag(diag::note_indirection_through_null)); 470 } 471 } 472 473 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 474 SourceLocation AssignLoc, 475 const Expr* RHS) { 476 const ObjCIvarDecl *IV = OIRE->getDecl(); 477 if (!IV) 478 return; 479 480 DeclarationName MemberName = IV->getDeclName(); 481 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 482 if (!Member || !Member->isStr("isa")) 483 return; 484 485 const Expr *Base = OIRE->getBase(); 486 QualType BaseType = Base->getType(); 487 if (OIRE->isArrow()) 488 BaseType = BaseType->getPointeeType(); 489 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 490 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 491 ObjCInterfaceDecl *ClassDeclared = nullptr; 492 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 493 if (!ClassDeclared->getSuperClass() 494 && (*ClassDeclared->ivar_begin()) == IV) { 495 if (RHS) { 496 NamedDecl *ObjectSetClass = 497 S.LookupSingleName(S.TUScope, 498 &S.Context.Idents.get("object_setClass"), 499 SourceLocation(), S.LookupOrdinaryName); 500 if (ObjectSetClass) { 501 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 502 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 503 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 504 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 505 AssignLoc), ",") << 506 FixItHint::CreateInsertion(RHSLocEnd, ")"); 507 } 508 else 509 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 510 } else { 511 NamedDecl *ObjectGetClass = 512 S.LookupSingleName(S.TUScope, 513 &S.Context.Idents.get("object_getClass"), 514 SourceLocation(), S.LookupOrdinaryName); 515 if (ObjectGetClass) 516 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 517 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 518 FixItHint::CreateReplacement( 519 SourceRange(OIRE->getOpLoc(), 520 OIRE->getLocEnd()), ")"); 521 else 522 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 523 } 524 S.Diag(IV->getLocation(), diag::note_ivar_decl); 525 } 526 } 527 } 528 529 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 530 // Handle any placeholder expressions which made it here. 531 if (E->getType()->isPlaceholderType()) { 532 ExprResult result = CheckPlaceholderExpr(E); 533 if (result.isInvalid()) return ExprError(); 534 E = result.get(); 535 } 536 537 // C++ [conv.lval]p1: 538 // A glvalue of a non-function, non-array type T can be 539 // converted to a prvalue. 540 if (!E->isGLValue()) return E; 541 542 QualType T = E->getType(); 543 assert(!T.isNull() && "r-value conversion on typeless expression?"); 544 545 // We don't want to throw lvalue-to-rvalue casts on top of 546 // expressions of certain types in C++. 547 if (getLangOpts().CPlusPlus && 548 (E->getType() == Context.OverloadTy || 549 T->isDependentType() || 550 T->isRecordType())) 551 return E; 552 553 // The C standard is actually really unclear on this point, and 554 // DR106 tells us what the result should be but not why. It's 555 // generally best to say that void types just doesn't undergo 556 // lvalue-to-rvalue at all. Note that expressions of unqualified 557 // 'void' type are never l-values, but qualified void can be. 558 if (T->isVoidType()) 559 return E; 560 561 // OpenCL usually rejects direct accesses to values of 'half' type. 562 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 563 T->isHalfType()) { 564 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 565 << 0 << T; 566 return ExprError(); 567 } 568 569 CheckForNullPointerDereference(*this, E); 570 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 571 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 572 &Context.Idents.get("object_getClass"), 573 SourceLocation(), LookupOrdinaryName); 574 if (ObjectGetClass) 575 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 576 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 577 FixItHint::CreateReplacement( 578 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 579 else 580 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 581 } 582 else if (const ObjCIvarRefExpr *OIRE = 583 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 584 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 585 586 // C++ [conv.lval]p1: 587 // [...] If T is a non-class type, the type of the prvalue is the 588 // cv-unqualified version of T. Otherwise, the type of the 589 // rvalue is T. 590 // 591 // C99 6.3.2.1p2: 592 // If the lvalue has qualified type, the value has the unqualified 593 // version of the type of the lvalue; otherwise, the value has the 594 // type of the lvalue. 595 if (T.hasQualifiers()) 596 T = T.getUnqualifiedType(); 597 598 // Under the MS ABI, lock down the inheritance model now. 599 if (T->isMemberPointerType() && 600 Context.getTargetInfo().getCXXABI().isMicrosoft()) 601 (void)isCompleteType(E->getExprLoc(), T); 602 603 UpdateMarkingForLValueToRValue(E); 604 605 // Loading a __weak object implicitly retains the value, so we need a cleanup to 606 // balance that. 607 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 608 Cleanup.setExprNeedsCleanups(true); 609 610 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 611 nullptr, VK_RValue); 612 613 // C11 6.3.2.1p2: 614 // ... if the lvalue has atomic type, the value has the non-atomic version 615 // of the type of the lvalue ... 616 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 617 T = Atomic->getValueType().getUnqualifiedType(); 618 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 619 nullptr, VK_RValue); 620 } 621 622 return Res; 623 } 624 625 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 626 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 627 if (Res.isInvalid()) 628 return ExprError(); 629 Res = DefaultLvalueConversion(Res.get()); 630 if (Res.isInvalid()) 631 return ExprError(); 632 return Res; 633 } 634 635 /// CallExprUnaryConversions - a special case of an unary conversion 636 /// performed on a function designator of a call expression. 637 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 638 QualType Ty = E->getType(); 639 ExprResult Res = E; 640 // Only do implicit cast for a function type, but not for a pointer 641 // to function type. 642 if (Ty->isFunctionType()) { 643 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 644 CK_FunctionToPointerDecay).get(); 645 if (Res.isInvalid()) 646 return ExprError(); 647 } 648 Res = DefaultLvalueConversion(Res.get()); 649 if (Res.isInvalid()) 650 return ExprError(); 651 return Res.get(); 652 } 653 654 /// UsualUnaryConversions - Performs various conversions that are common to most 655 /// operators (C99 6.3). The conversions of array and function types are 656 /// sometimes suppressed. For example, the array->pointer conversion doesn't 657 /// apply if the array is an argument to the sizeof or address (&) operators. 658 /// In these instances, this routine should *not* be called. 659 ExprResult Sema::UsualUnaryConversions(Expr *E) { 660 // First, convert to an r-value. 661 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 662 if (Res.isInvalid()) 663 return ExprError(); 664 E = Res.get(); 665 666 QualType Ty = E->getType(); 667 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 668 669 // Half FP have to be promoted to float unless it is natively supported 670 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 671 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 672 673 // Try to perform integral promotions if the object has a theoretically 674 // promotable type. 675 if (Ty->isIntegralOrUnscopedEnumerationType()) { 676 // C99 6.3.1.1p2: 677 // 678 // The following may be used in an expression wherever an int or 679 // unsigned int may be used: 680 // - an object or expression with an integer type whose integer 681 // conversion rank is less than or equal to the rank of int 682 // and unsigned int. 683 // - A bit-field of type _Bool, int, signed int, or unsigned int. 684 // 685 // If an int can represent all values of the original type, the 686 // value is converted to an int; otherwise, it is converted to an 687 // unsigned int. These are called the integer promotions. All 688 // other types are unchanged by the integer promotions. 689 690 QualType PTy = Context.isPromotableBitField(E); 691 if (!PTy.isNull()) { 692 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 693 return E; 694 } 695 if (Ty->isPromotableIntegerType()) { 696 QualType PT = Context.getPromotedIntegerType(Ty); 697 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 698 return E; 699 } 700 } 701 return E; 702 } 703 704 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 705 /// do not have a prototype. Arguments that have type float or __fp16 706 /// are promoted to double. All other argument types are converted by 707 /// UsualUnaryConversions(). 708 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 709 QualType Ty = E->getType(); 710 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 711 712 ExprResult Res = UsualUnaryConversions(E); 713 if (Res.isInvalid()) 714 return ExprError(); 715 E = Res.get(); 716 717 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 718 // promote to double. 719 // Note that default argument promotion applies only to float (and 720 // half/fp16); it does not apply to _Float16. 721 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 722 if (BTy && (BTy->getKind() == BuiltinType::Half || 723 BTy->getKind() == BuiltinType::Float)) { 724 if (getLangOpts().OpenCL && 725 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 726 if (BTy->getKind() == BuiltinType::Half) { 727 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 728 } 729 } else { 730 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 731 } 732 } 733 734 // C++ performs lvalue-to-rvalue conversion as a default argument 735 // promotion, even on class types, but note: 736 // C++11 [conv.lval]p2: 737 // When an lvalue-to-rvalue conversion occurs in an unevaluated 738 // operand or a subexpression thereof the value contained in the 739 // referenced object is not accessed. Otherwise, if the glvalue 740 // has a class type, the conversion copy-initializes a temporary 741 // of type T from the glvalue and the result of the conversion 742 // is a prvalue for the temporary. 743 // FIXME: add some way to gate this entire thing for correctness in 744 // potentially potentially evaluated contexts. 745 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 746 ExprResult Temp = PerformCopyInitialization( 747 InitializedEntity::InitializeTemporary(E->getType()), 748 E->getExprLoc(), E); 749 if (Temp.isInvalid()) 750 return ExprError(); 751 E = Temp.get(); 752 } 753 754 return E; 755 } 756 757 /// Determine the degree of POD-ness for an expression. 758 /// Incomplete types are considered POD, since this check can be performed 759 /// when we're in an unevaluated context. 760 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 761 if (Ty->isIncompleteType()) { 762 // C++11 [expr.call]p7: 763 // After these conversions, if the argument does not have arithmetic, 764 // enumeration, pointer, pointer to member, or class type, the program 765 // is ill-formed. 766 // 767 // Since we've already performed array-to-pointer and function-to-pointer 768 // decay, the only such type in C++ is cv void. This also handles 769 // initializer lists as variadic arguments. 770 if (Ty->isVoidType()) 771 return VAK_Invalid; 772 773 if (Ty->isObjCObjectType()) 774 return VAK_Invalid; 775 return VAK_Valid; 776 } 777 778 if (Ty.isCXX98PODType(Context)) 779 return VAK_Valid; 780 781 // C++11 [expr.call]p7: 782 // Passing a potentially-evaluated argument of class type (Clause 9) 783 // having a non-trivial copy constructor, a non-trivial move constructor, 784 // or a non-trivial destructor, with no corresponding parameter, 785 // is conditionally-supported with implementation-defined semantics. 786 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 787 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 788 if (!Record->hasNonTrivialCopyConstructor() && 789 !Record->hasNonTrivialMoveConstructor() && 790 !Record->hasNonTrivialDestructor()) 791 return VAK_ValidInCXX11; 792 793 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 794 return VAK_Valid; 795 796 if (Ty->isObjCObjectType()) 797 return VAK_Invalid; 798 799 if (getLangOpts().MSVCCompat) 800 return VAK_MSVCUndefined; 801 802 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 803 // permitted to reject them. We should consider doing so. 804 return VAK_Undefined; 805 } 806 807 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 808 // Don't allow one to pass an Objective-C interface to a vararg. 809 const QualType &Ty = E->getType(); 810 VarArgKind VAK = isValidVarArgType(Ty); 811 812 // Complain about passing non-POD types through varargs. 813 switch (VAK) { 814 case VAK_ValidInCXX11: 815 DiagRuntimeBehavior( 816 E->getLocStart(), nullptr, 817 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 818 << Ty << CT); 819 // Fall through. 820 case VAK_Valid: 821 if (Ty->isRecordType()) { 822 // This is unlikely to be what the user intended. If the class has a 823 // 'c_str' member function, the user probably meant to call that. 824 DiagRuntimeBehavior(E->getLocStart(), nullptr, 825 PDiag(diag::warn_pass_class_arg_to_vararg) 826 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 827 } 828 break; 829 830 case VAK_Undefined: 831 case VAK_MSVCUndefined: 832 DiagRuntimeBehavior( 833 E->getLocStart(), nullptr, 834 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 835 << getLangOpts().CPlusPlus11 << Ty << CT); 836 break; 837 838 case VAK_Invalid: 839 if (Ty->isObjCObjectType()) 840 DiagRuntimeBehavior( 841 E->getLocStart(), nullptr, 842 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 843 << Ty << CT); 844 else 845 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 846 << isa<InitListExpr>(E) << Ty << CT; 847 break; 848 } 849 } 850 851 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 852 /// will create a trap if the resulting type is not a POD type. 853 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 854 FunctionDecl *FDecl) { 855 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 856 // Strip the unbridged-cast placeholder expression off, if applicable. 857 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 858 (CT == VariadicMethod || 859 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 860 E = stripARCUnbridgedCast(E); 861 862 // Otherwise, do normal placeholder checking. 863 } else { 864 ExprResult ExprRes = CheckPlaceholderExpr(E); 865 if (ExprRes.isInvalid()) 866 return ExprError(); 867 E = ExprRes.get(); 868 } 869 } 870 871 ExprResult ExprRes = DefaultArgumentPromotion(E); 872 if (ExprRes.isInvalid()) 873 return ExprError(); 874 E = ExprRes.get(); 875 876 // Diagnostics regarding non-POD argument types are 877 // emitted along with format string checking in Sema::CheckFunctionCall(). 878 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 879 // Turn this into a trap. 880 CXXScopeSpec SS; 881 SourceLocation TemplateKWLoc; 882 UnqualifiedId Name; 883 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 884 E->getLocStart()); 885 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 886 Name, true, false); 887 if (TrapFn.isInvalid()) 888 return ExprError(); 889 890 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 891 E->getLocStart(), None, 892 E->getLocEnd()); 893 if (Call.isInvalid()) 894 return ExprError(); 895 896 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 897 Call.get(), E); 898 if (Comma.isInvalid()) 899 return ExprError(); 900 return Comma.get(); 901 } 902 903 if (!getLangOpts().CPlusPlus && 904 RequireCompleteType(E->getExprLoc(), E->getType(), 905 diag::err_call_incomplete_argument)) 906 return ExprError(); 907 908 return E; 909 } 910 911 /// \brief Converts an integer to complex float type. Helper function of 912 /// UsualArithmeticConversions() 913 /// 914 /// \return false if the integer expression is an integer type and is 915 /// successfully converted to the complex type. 916 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 917 ExprResult &ComplexExpr, 918 QualType IntTy, 919 QualType ComplexTy, 920 bool SkipCast) { 921 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 922 if (SkipCast) return false; 923 if (IntTy->isIntegerType()) { 924 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 925 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 926 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 927 CK_FloatingRealToComplex); 928 } else { 929 assert(IntTy->isComplexIntegerType()); 930 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 931 CK_IntegralComplexToFloatingComplex); 932 } 933 return false; 934 } 935 936 /// \brief Handle arithmetic conversion with complex types. Helper function of 937 /// UsualArithmeticConversions() 938 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 939 ExprResult &RHS, QualType LHSType, 940 QualType RHSType, 941 bool IsCompAssign) { 942 // if we have an integer operand, the result is the complex type. 943 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 944 /*skipCast*/false)) 945 return LHSType; 946 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 947 /*skipCast*/IsCompAssign)) 948 return RHSType; 949 950 // This handles complex/complex, complex/float, or float/complex. 951 // When both operands are complex, the shorter operand is converted to the 952 // type of the longer, and that is the type of the result. This corresponds 953 // to what is done when combining two real floating-point operands. 954 // The fun begins when size promotion occur across type domains. 955 // From H&S 6.3.4: When one operand is complex and the other is a real 956 // floating-point type, the less precise type is converted, within it's 957 // real or complex domain, to the precision of the other type. For example, 958 // when combining a "long double" with a "double _Complex", the 959 // "double _Complex" is promoted to "long double _Complex". 960 961 // Compute the rank of the two types, regardless of whether they are complex. 962 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 963 964 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 965 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 966 QualType LHSElementType = 967 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 968 QualType RHSElementType = 969 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 970 971 QualType ResultType = S.Context.getComplexType(LHSElementType); 972 if (Order < 0) { 973 // Promote the precision of the LHS if not an assignment. 974 ResultType = S.Context.getComplexType(RHSElementType); 975 if (!IsCompAssign) { 976 if (LHSComplexType) 977 LHS = 978 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 979 else 980 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 981 } 982 } else if (Order > 0) { 983 // Promote the precision of the RHS. 984 if (RHSComplexType) 985 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 986 else 987 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 988 } 989 return ResultType; 990 } 991 992 /// \brief Handle arithmetic conversion from integer to float. Helper function 993 /// of UsualArithmeticConversions() 994 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 995 ExprResult &IntExpr, 996 QualType FloatTy, QualType IntTy, 997 bool ConvertFloat, bool ConvertInt) { 998 if (IntTy->isIntegerType()) { 999 if (ConvertInt) 1000 // Convert intExpr to the lhs floating point type. 1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1002 CK_IntegralToFloating); 1003 return FloatTy; 1004 } 1005 1006 // Convert both sides to the appropriate complex float. 1007 assert(IntTy->isComplexIntegerType()); 1008 QualType result = S.Context.getComplexType(FloatTy); 1009 1010 // _Complex int -> _Complex float 1011 if (ConvertInt) 1012 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1013 CK_IntegralComplexToFloatingComplex); 1014 1015 // float -> _Complex float 1016 if (ConvertFloat) 1017 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1018 CK_FloatingRealToComplex); 1019 1020 return result; 1021 } 1022 1023 /// \brief Handle arithmethic conversion with floating point types. Helper 1024 /// function of UsualArithmeticConversions() 1025 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1026 ExprResult &RHS, QualType LHSType, 1027 QualType RHSType, bool IsCompAssign) { 1028 bool LHSFloat = LHSType->isRealFloatingType(); 1029 bool RHSFloat = RHSType->isRealFloatingType(); 1030 1031 // If we have two real floating types, convert the smaller operand 1032 // to the bigger result. 1033 if (LHSFloat && RHSFloat) { 1034 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1035 if (order > 0) { 1036 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1037 return LHSType; 1038 } 1039 1040 assert(order < 0 && "illegal float comparison"); 1041 if (!IsCompAssign) 1042 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1043 return RHSType; 1044 } 1045 1046 if (LHSFloat) { 1047 // Half FP has to be promoted to float unless it is natively supported 1048 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1049 LHSType = S.Context.FloatTy; 1050 1051 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1052 /*convertFloat=*/!IsCompAssign, 1053 /*convertInt=*/ true); 1054 } 1055 assert(RHSFloat); 1056 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1057 /*convertInt=*/ true, 1058 /*convertFloat=*/!IsCompAssign); 1059 } 1060 1061 /// \brief Diagnose attempts to convert between __float128 and long double if 1062 /// there is no support for such conversion. Helper function of 1063 /// UsualArithmeticConversions(). 1064 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1065 QualType RHSType) { 1066 /* No issue converting if at least one of the types is not a floating point 1067 type or the two types have the same rank. 1068 */ 1069 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1070 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1071 return false; 1072 1073 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1074 "The remaining types must be floating point types."); 1075 1076 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1077 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1078 1079 QualType LHSElemType = LHSComplex ? 1080 LHSComplex->getElementType() : LHSType; 1081 QualType RHSElemType = RHSComplex ? 1082 RHSComplex->getElementType() : RHSType; 1083 1084 // No issue if the two types have the same representation 1085 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1086 &S.Context.getFloatTypeSemantics(RHSElemType)) 1087 return false; 1088 1089 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1090 RHSElemType == S.Context.LongDoubleTy); 1091 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1092 RHSElemType == S.Context.Float128Ty); 1093 1094 /* We've handled the situation where __float128 and long double have the same 1095 representation. The only other allowable conversion is if long double is 1096 really just double. 1097 */ 1098 return Float128AndLongDouble && 1099 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1100 &llvm::APFloat::IEEEdouble()); 1101 } 1102 1103 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1104 1105 namespace { 1106 /// These helper callbacks are placed in an anonymous namespace to 1107 /// permit their use as function template parameters. 1108 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1109 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1110 } 1111 1112 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1113 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1114 CK_IntegralComplexCast); 1115 } 1116 } 1117 1118 /// \brief Handle integer arithmetic conversions. Helper function of 1119 /// UsualArithmeticConversions() 1120 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1121 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1122 ExprResult &RHS, QualType LHSType, 1123 QualType RHSType, bool IsCompAssign) { 1124 // The rules for this case are in C99 6.3.1.8 1125 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1126 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1127 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1128 if (LHSSigned == RHSSigned) { 1129 // Same signedness; use the higher-ranked type 1130 if (order >= 0) { 1131 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1132 return LHSType; 1133 } else if (!IsCompAssign) 1134 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1135 return RHSType; 1136 } else if (order != (LHSSigned ? 1 : -1)) { 1137 // The unsigned type has greater than or equal rank to the 1138 // signed type, so use the unsigned type 1139 if (RHSSigned) { 1140 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1141 return LHSType; 1142 } else if (!IsCompAssign) 1143 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1144 return RHSType; 1145 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1146 // The two types are different widths; if we are here, that 1147 // means the signed type is larger than the unsigned type, so 1148 // use the signed type. 1149 if (LHSSigned) { 1150 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1151 return LHSType; 1152 } else if (!IsCompAssign) 1153 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1154 return RHSType; 1155 } else { 1156 // The signed type is higher-ranked than the unsigned type, 1157 // but isn't actually any bigger (like unsigned int and long 1158 // on most 32-bit systems). Use the unsigned type corresponding 1159 // to the signed type. 1160 QualType result = 1161 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1162 RHS = (*doRHSCast)(S, RHS.get(), result); 1163 if (!IsCompAssign) 1164 LHS = (*doLHSCast)(S, LHS.get(), result); 1165 return result; 1166 } 1167 } 1168 1169 /// \brief Handle conversions with GCC complex int extension. Helper function 1170 /// of UsualArithmeticConversions() 1171 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1172 ExprResult &RHS, QualType LHSType, 1173 QualType RHSType, 1174 bool IsCompAssign) { 1175 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1176 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1177 1178 if (LHSComplexInt && RHSComplexInt) { 1179 QualType LHSEltType = LHSComplexInt->getElementType(); 1180 QualType RHSEltType = RHSComplexInt->getElementType(); 1181 QualType ScalarType = 1182 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1183 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1184 1185 return S.Context.getComplexType(ScalarType); 1186 } 1187 1188 if (LHSComplexInt) { 1189 QualType LHSEltType = LHSComplexInt->getElementType(); 1190 QualType ScalarType = 1191 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1192 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1193 QualType ComplexType = S.Context.getComplexType(ScalarType); 1194 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1195 CK_IntegralRealToComplex); 1196 1197 return ComplexType; 1198 } 1199 1200 assert(RHSComplexInt); 1201 1202 QualType RHSEltType = RHSComplexInt->getElementType(); 1203 QualType ScalarType = 1204 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1205 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1206 QualType ComplexType = S.Context.getComplexType(ScalarType); 1207 1208 if (!IsCompAssign) 1209 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1210 CK_IntegralRealToComplex); 1211 return ComplexType; 1212 } 1213 1214 /// UsualArithmeticConversions - Performs various conversions that are common to 1215 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1216 /// routine returns the first non-arithmetic type found. The client is 1217 /// responsible for emitting appropriate error diagnostics. 1218 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1219 bool IsCompAssign) { 1220 if (!IsCompAssign) { 1221 LHS = UsualUnaryConversions(LHS.get()); 1222 if (LHS.isInvalid()) 1223 return QualType(); 1224 } 1225 1226 RHS = UsualUnaryConversions(RHS.get()); 1227 if (RHS.isInvalid()) 1228 return QualType(); 1229 1230 // For conversion purposes, we ignore any qualifiers. 1231 // For example, "const float" and "float" are equivalent. 1232 QualType LHSType = 1233 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1234 QualType RHSType = 1235 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1236 1237 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1238 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1239 LHSType = AtomicLHS->getValueType(); 1240 1241 // If both types are identical, no conversion is needed. 1242 if (LHSType == RHSType) 1243 return LHSType; 1244 1245 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1246 // The caller can deal with this (e.g. pointer + int). 1247 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1248 return QualType(); 1249 1250 // Apply unary and bitfield promotions to the LHS's type. 1251 QualType LHSUnpromotedType = LHSType; 1252 if (LHSType->isPromotableIntegerType()) 1253 LHSType = Context.getPromotedIntegerType(LHSType); 1254 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1255 if (!LHSBitfieldPromoteTy.isNull()) 1256 LHSType = LHSBitfieldPromoteTy; 1257 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1258 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1259 1260 // If both types are identical, no conversion is needed. 1261 if (LHSType == RHSType) 1262 return LHSType; 1263 1264 // At this point, we have two different arithmetic types. 1265 1266 // Diagnose attempts to convert between __float128 and long double where 1267 // such conversions currently can't be handled. 1268 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1269 return QualType(); 1270 1271 // Handle complex types first (C99 6.3.1.8p1). 1272 if (LHSType->isComplexType() || RHSType->isComplexType()) 1273 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1274 IsCompAssign); 1275 1276 // Now handle "real" floating types (i.e. float, double, long double). 1277 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1278 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1279 IsCompAssign); 1280 1281 // Handle GCC complex int extension. 1282 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1283 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1284 IsCompAssign); 1285 1286 // Finally, we have two differing integer types. 1287 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1288 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1289 } 1290 1291 1292 //===----------------------------------------------------------------------===// 1293 // Semantic Analysis for various Expression Types 1294 //===----------------------------------------------------------------------===// 1295 1296 1297 ExprResult 1298 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1299 SourceLocation DefaultLoc, 1300 SourceLocation RParenLoc, 1301 Expr *ControllingExpr, 1302 ArrayRef<ParsedType> ArgTypes, 1303 ArrayRef<Expr *> ArgExprs) { 1304 unsigned NumAssocs = ArgTypes.size(); 1305 assert(NumAssocs == ArgExprs.size()); 1306 1307 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1308 for (unsigned i = 0; i < NumAssocs; ++i) { 1309 if (ArgTypes[i]) 1310 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1311 else 1312 Types[i] = nullptr; 1313 } 1314 1315 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1316 ControllingExpr, 1317 llvm::makeArrayRef(Types, NumAssocs), 1318 ArgExprs); 1319 delete [] Types; 1320 return ER; 1321 } 1322 1323 ExprResult 1324 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1325 SourceLocation DefaultLoc, 1326 SourceLocation RParenLoc, 1327 Expr *ControllingExpr, 1328 ArrayRef<TypeSourceInfo *> Types, 1329 ArrayRef<Expr *> Exprs) { 1330 unsigned NumAssocs = Types.size(); 1331 assert(NumAssocs == Exprs.size()); 1332 1333 // Decay and strip qualifiers for the controlling expression type, and handle 1334 // placeholder type replacement. See committee discussion from WG14 DR423. 1335 { 1336 EnterExpressionEvaluationContext Unevaluated( 1337 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1338 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1339 if (R.isInvalid()) 1340 return ExprError(); 1341 ControllingExpr = R.get(); 1342 } 1343 1344 // The controlling expression is an unevaluated operand, so side effects are 1345 // likely unintended. 1346 if (!inTemplateInstantiation() && 1347 ControllingExpr->HasSideEffects(Context, false)) 1348 Diag(ControllingExpr->getExprLoc(), 1349 diag::warn_side_effects_unevaluated_context); 1350 1351 bool TypeErrorFound = false, 1352 IsResultDependent = ControllingExpr->isTypeDependent(), 1353 ContainsUnexpandedParameterPack 1354 = ControllingExpr->containsUnexpandedParameterPack(); 1355 1356 for (unsigned i = 0; i < NumAssocs; ++i) { 1357 if (Exprs[i]->containsUnexpandedParameterPack()) 1358 ContainsUnexpandedParameterPack = true; 1359 1360 if (Types[i]) { 1361 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1362 ContainsUnexpandedParameterPack = true; 1363 1364 if (Types[i]->getType()->isDependentType()) { 1365 IsResultDependent = true; 1366 } else { 1367 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1368 // complete object type other than a variably modified type." 1369 unsigned D = 0; 1370 if (Types[i]->getType()->isIncompleteType()) 1371 D = diag::err_assoc_type_incomplete; 1372 else if (!Types[i]->getType()->isObjectType()) 1373 D = diag::err_assoc_type_nonobject; 1374 else if (Types[i]->getType()->isVariablyModifiedType()) 1375 D = diag::err_assoc_type_variably_modified; 1376 1377 if (D != 0) { 1378 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1379 << Types[i]->getTypeLoc().getSourceRange() 1380 << Types[i]->getType(); 1381 TypeErrorFound = true; 1382 } 1383 1384 // C11 6.5.1.1p2 "No two generic associations in the same generic 1385 // selection shall specify compatible types." 1386 for (unsigned j = i+1; j < NumAssocs; ++j) 1387 if (Types[j] && !Types[j]->getType()->isDependentType() && 1388 Context.typesAreCompatible(Types[i]->getType(), 1389 Types[j]->getType())) { 1390 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1391 diag::err_assoc_compatible_types) 1392 << Types[j]->getTypeLoc().getSourceRange() 1393 << Types[j]->getType() 1394 << Types[i]->getType(); 1395 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1396 diag::note_compat_assoc) 1397 << Types[i]->getTypeLoc().getSourceRange() 1398 << Types[i]->getType(); 1399 TypeErrorFound = true; 1400 } 1401 } 1402 } 1403 } 1404 if (TypeErrorFound) 1405 return ExprError(); 1406 1407 // If we determined that the generic selection is result-dependent, don't 1408 // try to compute the result expression. 1409 if (IsResultDependent) 1410 return new (Context) GenericSelectionExpr( 1411 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1412 ContainsUnexpandedParameterPack); 1413 1414 SmallVector<unsigned, 1> CompatIndices; 1415 unsigned DefaultIndex = -1U; 1416 for (unsigned i = 0; i < NumAssocs; ++i) { 1417 if (!Types[i]) 1418 DefaultIndex = i; 1419 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1420 Types[i]->getType())) 1421 CompatIndices.push_back(i); 1422 } 1423 1424 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1425 // type compatible with at most one of the types named in its generic 1426 // association list." 1427 if (CompatIndices.size() > 1) { 1428 // We strip parens here because the controlling expression is typically 1429 // parenthesized in macro definitions. 1430 ControllingExpr = ControllingExpr->IgnoreParens(); 1431 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1432 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1433 << (unsigned) CompatIndices.size(); 1434 for (unsigned I : CompatIndices) { 1435 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1436 diag::note_compat_assoc) 1437 << Types[I]->getTypeLoc().getSourceRange() 1438 << Types[I]->getType(); 1439 } 1440 return ExprError(); 1441 } 1442 1443 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1444 // its controlling expression shall have type compatible with exactly one of 1445 // the types named in its generic association list." 1446 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1447 // We strip parens here because the controlling expression is typically 1448 // parenthesized in macro definitions. 1449 ControllingExpr = ControllingExpr->IgnoreParens(); 1450 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1451 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1452 return ExprError(); 1453 } 1454 1455 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1456 // type name that is compatible with the type of the controlling expression, 1457 // then the result expression of the generic selection is the expression 1458 // in that generic association. Otherwise, the result expression of the 1459 // generic selection is the expression in the default generic association." 1460 unsigned ResultIndex = 1461 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1462 1463 return new (Context) GenericSelectionExpr( 1464 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1465 ContainsUnexpandedParameterPack, ResultIndex); 1466 } 1467 1468 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1469 /// location of the token and the offset of the ud-suffix within it. 1470 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1471 unsigned Offset) { 1472 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1473 S.getLangOpts()); 1474 } 1475 1476 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1477 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1478 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1479 IdentifierInfo *UDSuffix, 1480 SourceLocation UDSuffixLoc, 1481 ArrayRef<Expr*> Args, 1482 SourceLocation LitEndLoc) { 1483 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1484 1485 QualType ArgTy[2]; 1486 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1487 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1488 if (ArgTy[ArgIdx]->isArrayType()) 1489 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1490 } 1491 1492 DeclarationName OpName = 1493 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1494 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1495 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1496 1497 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1498 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1499 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1500 /*AllowStringTemplate*/ false, 1501 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1502 return ExprError(); 1503 1504 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1505 } 1506 1507 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1508 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1509 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1510 /// multiple tokens. However, the common case is that StringToks points to one 1511 /// string. 1512 /// 1513 ExprResult 1514 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1515 assert(!StringToks.empty() && "Must have at least one string!"); 1516 1517 StringLiteralParser Literal(StringToks, PP); 1518 if (Literal.hadError) 1519 return ExprError(); 1520 1521 SmallVector<SourceLocation, 4> StringTokLocs; 1522 for (const Token &Tok : StringToks) 1523 StringTokLocs.push_back(Tok.getLocation()); 1524 1525 QualType CharTy = Context.CharTy; 1526 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1527 if (Literal.isWide()) { 1528 CharTy = Context.getWideCharType(); 1529 Kind = StringLiteral::Wide; 1530 } else if (Literal.isUTF8()) { 1531 Kind = StringLiteral::UTF8; 1532 } else if (Literal.isUTF16()) { 1533 CharTy = Context.Char16Ty; 1534 Kind = StringLiteral::UTF16; 1535 } else if (Literal.isUTF32()) { 1536 CharTy = Context.Char32Ty; 1537 Kind = StringLiteral::UTF32; 1538 } else if (Literal.isPascal()) { 1539 CharTy = Context.UnsignedCharTy; 1540 } 1541 1542 QualType CharTyConst = CharTy; 1543 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1544 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1545 CharTyConst.addConst(); 1546 1547 // Get an array type for the string, according to C99 6.4.5. This includes 1548 // the nul terminator character as well as the string length for pascal 1549 // strings. 1550 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1551 llvm::APInt(32, Literal.GetNumStringChars()+1), 1552 ArrayType::Normal, 0); 1553 1554 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1555 if (getLangOpts().OpenCL) { 1556 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1557 } 1558 1559 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1560 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1561 Kind, Literal.Pascal, StrTy, 1562 &StringTokLocs[0], 1563 StringTokLocs.size()); 1564 if (Literal.getUDSuffix().empty()) 1565 return Lit; 1566 1567 // We're building a user-defined literal. 1568 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1569 SourceLocation UDSuffixLoc = 1570 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1571 Literal.getUDSuffixOffset()); 1572 1573 // Make sure we're allowed user-defined literals here. 1574 if (!UDLScope) 1575 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1576 1577 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1578 // operator "" X (str, len) 1579 QualType SizeType = Context.getSizeType(); 1580 1581 DeclarationName OpName = 1582 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1583 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1584 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1585 1586 QualType ArgTy[] = { 1587 Context.getArrayDecayedType(StrTy), SizeType 1588 }; 1589 1590 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1591 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1592 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1593 /*AllowStringTemplate*/ true, 1594 /*DiagnoseMissing*/ true)) { 1595 1596 case LOLR_Cooked: { 1597 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1598 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1599 StringTokLocs[0]); 1600 Expr *Args[] = { Lit, LenArg }; 1601 1602 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1603 } 1604 1605 case LOLR_StringTemplate: { 1606 TemplateArgumentListInfo ExplicitArgs; 1607 1608 unsigned CharBits = Context.getIntWidth(CharTy); 1609 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1610 llvm::APSInt Value(CharBits, CharIsUnsigned); 1611 1612 TemplateArgument TypeArg(CharTy); 1613 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1614 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1615 1616 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1617 Value = Lit->getCodeUnit(I); 1618 TemplateArgument Arg(Context, Value, CharTy); 1619 TemplateArgumentLocInfo ArgInfo; 1620 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1621 } 1622 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1623 &ExplicitArgs); 1624 } 1625 case LOLR_Raw: 1626 case LOLR_Template: 1627 case LOLR_ErrorNoDiagnostic: 1628 llvm_unreachable("unexpected literal operator lookup result"); 1629 case LOLR_Error: 1630 return ExprError(); 1631 } 1632 llvm_unreachable("unexpected literal operator lookup result"); 1633 } 1634 1635 ExprResult 1636 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1637 SourceLocation Loc, 1638 const CXXScopeSpec *SS) { 1639 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1640 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1641 } 1642 1643 /// BuildDeclRefExpr - Build an expression that references a 1644 /// declaration that does not require a closure capture. 1645 ExprResult 1646 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1647 const DeclarationNameInfo &NameInfo, 1648 const CXXScopeSpec *SS, NamedDecl *FoundD, 1649 const TemplateArgumentListInfo *TemplateArgs) { 1650 bool RefersToCapturedVariable = 1651 isa<VarDecl>(D) && 1652 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1653 1654 DeclRefExpr *E; 1655 if (isa<VarTemplateSpecializationDecl>(D)) { 1656 VarTemplateSpecializationDecl *VarSpec = 1657 cast<VarTemplateSpecializationDecl>(D); 1658 1659 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1660 : NestedNameSpecifierLoc(), 1661 VarSpec->getTemplateKeywordLoc(), D, 1662 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1663 FoundD, TemplateArgs); 1664 } else { 1665 assert(!TemplateArgs && "No template arguments for non-variable" 1666 " template specialization references"); 1667 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1668 : NestedNameSpecifierLoc(), 1669 SourceLocation(), D, RefersToCapturedVariable, 1670 NameInfo, Ty, VK, FoundD); 1671 } 1672 1673 MarkDeclRefReferenced(E); 1674 1675 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1676 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1677 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1678 recordUseOfEvaluatedWeak(E); 1679 1680 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1681 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1682 FD = IFD->getAnonField(); 1683 if (FD) { 1684 UnusedPrivateFields.remove(FD); 1685 // Just in case we're building an illegal pointer-to-member. 1686 if (FD->isBitField()) 1687 E->setObjectKind(OK_BitField); 1688 } 1689 1690 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1691 // designates a bit-field. 1692 if (auto *BD = dyn_cast<BindingDecl>(D)) 1693 if (auto *BE = BD->getBinding()) 1694 E->setObjectKind(BE->getObjectKind()); 1695 1696 return E; 1697 } 1698 1699 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1700 /// possibly a list of template arguments. 1701 /// 1702 /// If this produces template arguments, it is permitted to call 1703 /// DecomposeTemplateName. 1704 /// 1705 /// This actually loses a lot of source location information for 1706 /// non-standard name kinds; we should consider preserving that in 1707 /// some way. 1708 void 1709 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1710 TemplateArgumentListInfo &Buffer, 1711 DeclarationNameInfo &NameInfo, 1712 const TemplateArgumentListInfo *&TemplateArgs) { 1713 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1714 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1715 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1716 1717 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1718 Id.TemplateId->NumArgs); 1719 translateTemplateArguments(TemplateArgsPtr, Buffer); 1720 1721 TemplateName TName = Id.TemplateId->Template.get(); 1722 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1723 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1724 TemplateArgs = &Buffer; 1725 } else { 1726 NameInfo = GetNameFromUnqualifiedId(Id); 1727 TemplateArgs = nullptr; 1728 } 1729 } 1730 1731 static void emitEmptyLookupTypoDiagnostic( 1732 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1733 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1734 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1735 DeclContext *Ctx = 1736 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1737 if (!TC) { 1738 // Emit a special diagnostic for failed member lookups. 1739 // FIXME: computing the declaration context might fail here (?) 1740 if (Ctx) 1741 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1742 << SS.getRange(); 1743 else 1744 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1745 return; 1746 } 1747 1748 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1749 bool DroppedSpecifier = 1750 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1751 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1752 ? diag::note_implicit_param_decl 1753 : diag::note_previous_decl; 1754 if (!Ctx) 1755 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1756 SemaRef.PDiag(NoteID)); 1757 else 1758 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1759 << Typo << Ctx << DroppedSpecifier 1760 << SS.getRange(), 1761 SemaRef.PDiag(NoteID)); 1762 } 1763 1764 /// Diagnose an empty lookup. 1765 /// 1766 /// \return false if new lookup candidates were found 1767 bool 1768 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1769 std::unique_ptr<CorrectionCandidateCallback> CCC, 1770 TemplateArgumentListInfo *ExplicitTemplateArgs, 1771 ArrayRef<Expr *> Args, TypoExpr **Out) { 1772 DeclarationName Name = R.getLookupName(); 1773 1774 unsigned diagnostic = diag::err_undeclared_var_use; 1775 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1776 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1777 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1778 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1779 diagnostic = diag::err_undeclared_use; 1780 diagnostic_suggest = diag::err_undeclared_use_suggest; 1781 } 1782 1783 // If the original lookup was an unqualified lookup, fake an 1784 // unqualified lookup. This is useful when (for example) the 1785 // original lookup would not have found something because it was a 1786 // dependent name. 1787 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1788 while (DC) { 1789 if (isa<CXXRecordDecl>(DC)) { 1790 LookupQualifiedName(R, DC); 1791 1792 if (!R.empty()) { 1793 // Don't give errors about ambiguities in this lookup. 1794 R.suppressDiagnostics(); 1795 1796 // During a default argument instantiation the CurContext points 1797 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1798 // function parameter list, hence add an explicit check. 1799 bool isDefaultArgument = 1800 !CodeSynthesisContexts.empty() && 1801 CodeSynthesisContexts.back().Kind == 1802 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1803 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1804 bool isInstance = CurMethod && 1805 CurMethod->isInstance() && 1806 DC == CurMethod->getParent() && !isDefaultArgument; 1807 1808 // Give a code modification hint to insert 'this->'. 1809 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1810 // Actually quite difficult! 1811 if (getLangOpts().MSVCCompat) 1812 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1813 if (isInstance) { 1814 Diag(R.getNameLoc(), diagnostic) << Name 1815 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1816 CheckCXXThisCapture(R.getNameLoc()); 1817 } else { 1818 Diag(R.getNameLoc(), diagnostic) << Name; 1819 } 1820 1821 // Do we really want to note all of these? 1822 for (NamedDecl *D : R) 1823 Diag(D->getLocation(), diag::note_dependent_var_use); 1824 1825 // Return true if we are inside a default argument instantiation 1826 // and the found name refers to an instance member function, otherwise 1827 // the function calling DiagnoseEmptyLookup will try to create an 1828 // implicit member call and this is wrong for default argument. 1829 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1830 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1831 return true; 1832 } 1833 1834 // Tell the callee to try to recover. 1835 return false; 1836 } 1837 1838 R.clear(); 1839 } 1840 1841 // In Microsoft mode, if we are performing lookup from within a friend 1842 // function definition declared at class scope then we must set 1843 // DC to the lexical parent to be able to search into the parent 1844 // class. 1845 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1846 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1847 DC->getLexicalParent()->isRecord()) 1848 DC = DC->getLexicalParent(); 1849 else 1850 DC = DC->getParent(); 1851 } 1852 1853 // We didn't find anything, so try to correct for a typo. 1854 TypoCorrection Corrected; 1855 if (S && Out) { 1856 SourceLocation TypoLoc = R.getNameLoc(); 1857 assert(!ExplicitTemplateArgs && 1858 "Diagnosing an empty lookup with explicit template args!"); 1859 *Out = CorrectTypoDelayed( 1860 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1861 [=](const TypoCorrection &TC) { 1862 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1863 diagnostic, diagnostic_suggest); 1864 }, 1865 nullptr, CTK_ErrorRecovery); 1866 if (*Out) 1867 return true; 1868 } else if (S && (Corrected = 1869 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1870 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1871 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1872 bool DroppedSpecifier = 1873 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1874 R.setLookupName(Corrected.getCorrection()); 1875 1876 bool AcceptableWithRecovery = false; 1877 bool AcceptableWithoutRecovery = false; 1878 NamedDecl *ND = Corrected.getFoundDecl(); 1879 if (ND) { 1880 if (Corrected.isOverloaded()) { 1881 OverloadCandidateSet OCS(R.getNameLoc(), 1882 OverloadCandidateSet::CSK_Normal); 1883 OverloadCandidateSet::iterator Best; 1884 for (NamedDecl *CD : Corrected) { 1885 if (FunctionTemplateDecl *FTD = 1886 dyn_cast<FunctionTemplateDecl>(CD)) 1887 AddTemplateOverloadCandidate( 1888 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1889 Args, OCS); 1890 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1891 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1892 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1893 Args, OCS); 1894 } 1895 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1896 case OR_Success: 1897 ND = Best->FoundDecl; 1898 Corrected.setCorrectionDecl(ND); 1899 break; 1900 default: 1901 // FIXME: Arbitrarily pick the first declaration for the note. 1902 Corrected.setCorrectionDecl(ND); 1903 break; 1904 } 1905 } 1906 R.addDecl(ND); 1907 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1908 CXXRecordDecl *Record = nullptr; 1909 if (Corrected.getCorrectionSpecifier()) { 1910 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1911 Record = Ty->getAsCXXRecordDecl(); 1912 } 1913 if (!Record) 1914 Record = cast<CXXRecordDecl>( 1915 ND->getDeclContext()->getRedeclContext()); 1916 R.setNamingClass(Record); 1917 } 1918 1919 auto *UnderlyingND = ND->getUnderlyingDecl(); 1920 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1921 isa<FunctionTemplateDecl>(UnderlyingND); 1922 // FIXME: If we ended up with a typo for a type name or 1923 // Objective-C class name, we're in trouble because the parser 1924 // is in the wrong place to recover. Suggest the typo 1925 // correction, but don't make it a fix-it since we're not going 1926 // to recover well anyway. 1927 AcceptableWithoutRecovery = 1928 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1929 } else { 1930 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1931 // because we aren't able to recover. 1932 AcceptableWithoutRecovery = true; 1933 } 1934 1935 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1936 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1937 ? diag::note_implicit_param_decl 1938 : diag::note_previous_decl; 1939 if (SS.isEmpty()) 1940 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1941 PDiag(NoteID), AcceptableWithRecovery); 1942 else 1943 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1944 << Name << computeDeclContext(SS, false) 1945 << DroppedSpecifier << SS.getRange(), 1946 PDiag(NoteID), AcceptableWithRecovery); 1947 1948 // Tell the callee whether to try to recover. 1949 return !AcceptableWithRecovery; 1950 } 1951 } 1952 R.clear(); 1953 1954 // Emit a special diagnostic for failed member lookups. 1955 // FIXME: computing the declaration context might fail here (?) 1956 if (!SS.isEmpty()) { 1957 Diag(R.getNameLoc(), diag::err_no_member) 1958 << Name << computeDeclContext(SS, false) 1959 << SS.getRange(); 1960 return true; 1961 } 1962 1963 // Give up, we can't recover. 1964 Diag(R.getNameLoc(), diagnostic) << Name; 1965 return true; 1966 } 1967 1968 /// In Microsoft mode, if we are inside a template class whose parent class has 1969 /// dependent base classes, and we can't resolve an unqualified identifier, then 1970 /// assume the identifier is a member of a dependent base class. We can only 1971 /// recover successfully in static methods, instance methods, and other contexts 1972 /// where 'this' is available. This doesn't precisely match MSVC's 1973 /// instantiation model, but it's close enough. 1974 static Expr * 1975 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1976 DeclarationNameInfo &NameInfo, 1977 SourceLocation TemplateKWLoc, 1978 const TemplateArgumentListInfo *TemplateArgs) { 1979 // Only try to recover from lookup into dependent bases in static methods or 1980 // contexts where 'this' is available. 1981 QualType ThisType = S.getCurrentThisType(); 1982 const CXXRecordDecl *RD = nullptr; 1983 if (!ThisType.isNull()) 1984 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1985 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1986 RD = MD->getParent(); 1987 if (!RD || !RD->hasAnyDependentBases()) 1988 return nullptr; 1989 1990 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1991 // is available, suggest inserting 'this->' as a fixit. 1992 SourceLocation Loc = NameInfo.getLoc(); 1993 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1994 DB << NameInfo.getName() << RD; 1995 1996 if (!ThisType.isNull()) { 1997 DB << FixItHint::CreateInsertion(Loc, "this->"); 1998 return CXXDependentScopeMemberExpr::Create( 1999 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2000 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2001 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2002 } 2003 2004 // Synthesize a fake NNS that points to the derived class. This will 2005 // perform name lookup during template instantiation. 2006 CXXScopeSpec SS; 2007 auto *NNS = 2008 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2009 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2010 return DependentScopeDeclRefExpr::Create( 2011 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2012 TemplateArgs); 2013 } 2014 2015 ExprResult 2016 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2017 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2018 bool HasTrailingLParen, bool IsAddressOfOperand, 2019 std::unique_ptr<CorrectionCandidateCallback> CCC, 2020 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2021 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2022 "cannot be direct & operand and have a trailing lparen"); 2023 if (SS.isInvalid()) 2024 return ExprError(); 2025 2026 TemplateArgumentListInfo TemplateArgsBuffer; 2027 2028 // Decompose the UnqualifiedId into the following data. 2029 DeclarationNameInfo NameInfo; 2030 const TemplateArgumentListInfo *TemplateArgs; 2031 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2032 2033 DeclarationName Name = NameInfo.getName(); 2034 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2035 SourceLocation NameLoc = NameInfo.getLoc(); 2036 2037 if (II && II->isEditorPlaceholder()) { 2038 // FIXME: When typed placeholders are supported we can create a typed 2039 // placeholder expression node. 2040 return ExprError(); 2041 } 2042 2043 // C++ [temp.dep.expr]p3: 2044 // An id-expression is type-dependent if it contains: 2045 // -- an identifier that was declared with a dependent type, 2046 // (note: handled after lookup) 2047 // -- a template-id that is dependent, 2048 // (note: handled in BuildTemplateIdExpr) 2049 // -- a conversion-function-id that specifies a dependent type, 2050 // -- a nested-name-specifier that contains a class-name that 2051 // names a dependent type. 2052 // Determine whether this is a member of an unknown specialization; 2053 // we need to handle these differently. 2054 bool DependentID = false; 2055 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2056 Name.getCXXNameType()->isDependentType()) { 2057 DependentID = true; 2058 } else if (SS.isSet()) { 2059 if (DeclContext *DC = computeDeclContext(SS, false)) { 2060 if (RequireCompleteDeclContext(SS, DC)) 2061 return ExprError(); 2062 } else { 2063 DependentID = true; 2064 } 2065 } 2066 2067 if (DependentID) 2068 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2069 IsAddressOfOperand, TemplateArgs); 2070 2071 // Perform the required lookup. 2072 LookupResult R(*this, NameInfo, 2073 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2074 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2075 if (TemplateArgs) { 2076 // Lookup the template name again to correctly establish the context in 2077 // which it was found. This is really unfortunate as we already did the 2078 // lookup to determine that it was a template name in the first place. If 2079 // this becomes a performance hit, we can work harder to preserve those 2080 // results until we get here but it's likely not worth it. 2081 bool MemberOfUnknownSpecialization; 2082 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2083 MemberOfUnknownSpecialization); 2084 2085 if (MemberOfUnknownSpecialization || 2086 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2087 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2088 IsAddressOfOperand, TemplateArgs); 2089 } else { 2090 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2091 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2092 2093 // If the result might be in a dependent base class, this is a dependent 2094 // id-expression. 2095 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2096 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2097 IsAddressOfOperand, TemplateArgs); 2098 2099 // If this reference is in an Objective-C method, then we need to do 2100 // some special Objective-C lookup, too. 2101 if (IvarLookupFollowUp) { 2102 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2103 if (E.isInvalid()) 2104 return ExprError(); 2105 2106 if (Expr *Ex = E.getAs<Expr>()) 2107 return Ex; 2108 } 2109 } 2110 2111 if (R.isAmbiguous()) 2112 return ExprError(); 2113 2114 // This could be an implicitly declared function reference (legal in C90, 2115 // extension in C99, forbidden in C++). 2116 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2117 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2118 if (D) R.addDecl(D); 2119 } 2120 2121 // Determine whether this name might be a candidate for 2122 // argument-dependent lookup. 2123 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2124 2125 if (R.empty() && !ADL) { 2126 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2127 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2128 TemplateKWLoc, TemplateArgs)) 2129 return E; 2130 } 2131 2132 // Don't diagnose an empty lookup for inline assembly. 2133 if (IsInlineAsmIdentifier) 2134 return ExprError(); 2135 2136 // If this name wasn't predeclared and if this is not a function 2137 // call, diagnose the problem. 2138 TypoExpr *TE = nullptr; 2139 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2140 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2141 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2142 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2143 "Typo correction callback misconfigured"); 2144 if (CCC) { 2145 // Make sure the callback knows what the typo being diagnosed is. 2146 CCC->setTypoName(II); 2147 if (SS.isValid()) 2148 CCC->setTypoNNS(SS.getScopeRep()); 2149 } 2150 if (DiagnoseEmptyLookup(S, SS, R, 2151 CCC ? std::move(CCC) : std::move(DefaultValidator), 2152 nullptr, None, &TE)) { 2153 if (TE && KeywordReplacement) { 2154 auto &State = getTypoExprState(TE); 2155 auto BestTC = State.Consumer->getNextCorrection(); 2156 if (BestTC.isKeyword()) { 2157 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2158 if (State.DiagHandler) 2159 State.DiagHandler(BestTC); 2160 KeywordReplacement->startToken(); 2161 KeywordReplacement->setKind(II->getTokenID()); 2162 KeywordReplacement->setIdentifierInfo(II); 2163 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2164 // Clean up the state associated with the TypoExpr, since it has 2165 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2166 clearDelayedTypo(TE); 2167 // Signal that a correction to a keyword was performed by returning a 2168 // valid-but-null ExprResult. 2169 return (Expr*)nullptr; 2170 } 2171 State.Consumer->resetCorrectionStream(); 2172 } 2173 return TE ? TE : ExprError(); 2174 } 2175 2176 assert(!R.empty() && 2177 "DiagnoseEmptyLookup returned false but added no results"); 2178 2179 // If we found an Objective-C instance variable, let 2180 // LookupInObjCMethod build the appropriate expression to 2181 // reference the ivar. 2182 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2183 R.clear(); 2184 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2185 // In a hopelessly buggy code, Objective-C instance variable 2186 // lookup fails and no expression will be built to reference it. 2187 if (!E.isInvalid() && !E.get()) 2188 return ExprError(); 2189 return E; 2190 } 2191 } 2192 2193 // This is guaranteed from this point on. 2194 assert(!R.empty() || ADL); 2195 2196 // Check whether this might be a C++ implicit instance member access. 2197 // C++ [class.mfct.non-static]p3: 2198 // When an id-expression that is not part of a class member access 2199 // syntax and not used to form a pointer to member is used in the 2200 // body of a non-static member function of class X, if name lookup 2201 // resolves the name in the id-expression to a non-static non-type 2202 // member of some class C, the id-expression is transformed into a 2203 // class member access expression using (*this) as the 2204 // postfix-expression to the left of the . operator. 2205 // 2206 // But we don't actually need to do this for '&' operands if R 2207 // resolved to a function or overloaded function set, because the 2208 // expression is ill-formed if it actually works out to be a 2209 // non-static member function: 2210 // 2211 // C++ [expr.ref]p4: 2212 // Otherwise, if E1.E2 refers to a non-static member function. . . 2213 // [t]he expression can be used only as the left-hand operand of a 2214 // member function call. 2215 // 2216 // There are other safeguards against such uses, but it's important 2217 // to get this right here so that we don't end up making a 2218 // spuriously dependent expression if we're inside a dependent 2219 // instance method. 2220 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2221 bool MightBeImplicitMember; 2222 if (!IsAddressOfOperand) 2223 MightBeImplicitMember = true; 2224 else if (!SS.isEmpty()) 2225 MightBeImplicitMember = false; 2226 else if (R.isOverloadedResult()) 2227 MightBeImplicitMember = false; 2228 else if (R.isUnresolvableResult()) 2229 MightBeImplicitMember = true; 2230 else 2231 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2232 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2233 isa<MSPropertyDecl>(R.getFoundDecl()); 2234 2235 if (MightBeImplicitMember) 2236 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2237 R, TemplateArgs, S); 2238 } 2239 2240 if (TemplateArgs || TemplateKWLoc.isValid()) { 2241 2242 // In C++1y, if this is a variable template id, then check it 2243 // in BuildTemplateIdExpr(). 2244 // The single lookup result must be a variable template declaration. 2245 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2246 Id.TemplateId->Kind == TNK_Var_template) { 2247 assert(R.getAsSingle<VarTemplateDecl>() && 2248 "There should only be one declaration found."); 2249 } 2250 2251 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2252 } 2253 2254 return BuildDeclarationNameExpr(SS, R, ADL); 2255 } 2256 2257 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2258 /// declaration name, generally during template instantiation. 2259 /// There's a large number of things which don't need to be done along 2260 /// this path. 2261 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2262 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2263 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2264 DeclContext *DC = computeDeclContext(SS, false); 2265 if (!DC) 2266 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2267 NameInfo, /*TemplateArgs=*/nullptr); 2268 2269 if (RequireCompleteDeclContext(SS, DC)) 2270 return ExprError(); 2271 2272 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2273 LookupQualifiedName(R, DC); 2274 2275 if (R.isAmbiguous()) 2276 return ExprError(); 2277 2278 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2279 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2280 NameInfo, /*TemplateArgs=*/nullptr); 2281 2282 if (R.empty()) { 2283 Diag(NameInfo.getLoc(), diag::err_no_member) 2284 << NameInfo.getName() << DC << SS.getRange(); 2285 return ExprError(); 2286 } 2287 2288 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2289 // Diagnose a missing typename if this resolved unambiguously to a type in 2290 // a dependent context. If we can recover with a type, downgrade this to 2291 // a warning in Microsoft compatibility mode. 2292 unsigned DiagID = diag::err_typename_missing; 2293 if (RecoveryTSI && getLangOpts().MSVCCompat) 2294 DiagID = diag::ext_typename_missing; 2295 SourceLocation Loc = SS.getBeginLoc(); 2296 auto D = Diag(Loc, DiagID); 2297 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2298 << SourceRange(Loc, NameInfo.getEndLoc()); 2299 2300 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2301 // context. 2302 if (!RecoveryTSI) 2303 return ExprError(); 2304 2305 // Only issue the fixit if we're prepared to recover. 2306 D << FixItHint::CreateInsertion(Loc, "typename "); 2307 2308 // Recover by pretending this was an elaborated type. 2309 QualType Ty = Context.getTypeDeclType(TD); 2310 TypeLocBuilder TLB; 2311 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2312 2313 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2314 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2315 QTL.setElaboratedKeywordLoc(SourceLocation()); 2316 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2317 2318 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2319 2320 return ExprEmpty(); 2321 } 2322 2323 // Defend against this resolving to an implicit member access. We usually 2324 // won't get here if this might be a legitimate a class member (we end up in 2325 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2326 // a pointer-to-member or in an unevaluated context in C++11. 2327 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2328 return BuildPossibleImplicitMemberExpr(SS, 2329 /*TemplateKWLoc=*/SourceLocation(), 2330 R, /*TemplateArgs=*/nullptr, S); 2331 2332 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2333 } 2334 2335 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2336 /// detected that we're currently inside an ObjC method. Perform some 2337 /// additional lookup. 2338 /// 2339 /// Ideally, most of this would be done by lookup, but there's 2340 /// actually quite a lot of extra work involved. 2341 /// 2342 /// Returns a null sentinel to indicate trivial success. 2343 ExprResult 2344 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2345 IdentifierInfo *II, bool AllowBuiltinCreation) { 2346 SourceLocation Loc = Lookup.getNameLoc(); 2347 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2348 2349 // Check for error condition which is already reported. 2350 if (!CurMethod) 2351 return ExprError(); 2352 2353 // There are two cases to handle here. 1) scoped lookup could have failed, 2354 // in which case we should look for an ivar. 2) scoped lookup could have 2355 // found a decl, but that decl is outside the current instance method (i.e. 2356 // a global variable). In these two cases, we do a lookup for an ivar with 2357 // this name, if the lookup sucedes, we replace it our current decl. 2358 2359 // If we're in a class method, we don't normally want to look for 2360 // ivars. But if we don't find anything else, and there's an 2361 // ivar, that's an error. 2362 bool IsClassMethod = CurMethod->isClassMethod(); 2363 2364 bool LookForIvars; 2365 if (Lookup.empty()) 2366 LookForIvars = true; 2367 else if (IsClassMethod) 2368 LookForIvars = false; 2369 else 2370 LookForIvars = (Lookup.isSingleResult() && 2371 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2372 ObjCInterfaceDecl *IFace = nullptr; 2373 if (LookForIvars) { 2374 IFace = CurMethod->getClassInterface(); 2375 ObjCInterfaceDecl *ClassDeclared; 2376 ObjCIvarDecl *IV = nullptr; 2377 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2378 // Diagnose using an ivar in a class method. 2379 if (IsClassMethod) 2380 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2381 << IV->getDeclName()); 2382 2383 // If we're referencing an invalid decl, just return this as a silent 2384 // error node. The error diagnostic was already emitted on the decl. 2385 if (IV->isInvalidDecl()) 2386 return ExprError(); 2387 2388 // Check if referencing a field with __attribute__((deprecated)). 2389 if (DiagnoseUseOfDecl(IV, Loc)) 2390 return ExprError(); 2391 2392 // Diagnose the use of an ivar outside of the declaring class. 2393 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2394 !declaresSameEntity(ClassDeclared, IFace) && 2395 !getLangOpts().DebuggerSupport) 2396 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2397 2398 // FIXME: This should use a new expr for a direct reference, don't 2399 // turn this into Self->ivar, just return a BareIVarExpr or something. 2400 IdentifierInfo &II = Context.Idents.get("self"); 2401 UnqualifiedId SelfName; 2402 SelfName.setIdentifier(&II, SourceLocation()); 2403 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2404 CXXScopeSpec SelfScopeSpec; 2405 SourceLocation TemplateKWLoc; 2406 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2407 SelfName, false, false); 2408 if (SelfExpr.isInvalid()) 2409 return ExprError(); 2410 2411 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2412 if (SelfExpr.isInvalid()) 2413 return ExprError(); 2414 2415 MarkAnyDeclReferenced(Loc, IV, true); 2416 2417 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2418 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2419 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2420 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2421 2422 ObjCIvarRefExpr *Result = new (Context) 2423 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2424 IV->getLocation(), SelfExpr.get(), true, true); 2425 2426 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2427 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2428 recordUseOfEvaluatedWeak(Result); 2429 } 2430 if (getLangOpts().ObjCAutoRefCount) { 2431 if (CurContext->isClosure()) 2432 Diag(Loc, diag::warn_implicitly_retains_self) 2433 << FixItHint::CreateInsertion(Loc, "self->"); 2434 } 2435 2436 return Result; 2437 } 2438 } else if (CurMethod->isInstanceMethod()) { 2439 // We should warn if a local variable hides an ivar. 2440 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2441 ObjCInterfaceDecl *ClassDeclared; 2442 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2443 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2444 declaresSameEntity(IFace, ClassDeclared)) 2445 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2446 } 2447 } 2448 } else if (Lookup.isSingleResult() && 2449 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2450 // If accessing a stand-alone ivar in a class method, this is an error. 2451 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2452 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2453 << IV->getDeclName()); 2454 } 2455 2456 if (Lookup.empty() && II && AllowBuiltinCreation) { 2457 // FIXME. Consolidate this with similar code in LookupName. 2458 if (unsigned BuiltinID = II->getBuiltinID()) { 2459 if (!(getLangOpts().CPlusPlus && 2460 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2461 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2462 S, Lookup.isForRedeclaration(), 2463 Lookup.getNameLoc()); 2464 if (D) Lookup.addDecl(D); 2465 } 2466 } 2467 } 2468 // Sentinel value saying that we didn't do anything special. 2469 return ExprResult((Expr *)nullptr); 2470 } 2471 2472 /// \brief Cast a base object to a member's actual type. 2473 /// 2474 /// Logically this happens in three phases: 2475 /// 2476 /// * First we cast from the base type to the naming class. 2477 /// The naming class is the class into which we were looking 2478 /// when we found the member; it's the qualifier type if a 2479 /// qualifier was provided, and otherwise it's the base type. 2480 /// 2481 /// * Next we cast from the naming class to the declaring class. 2482 /// If the member we found was brought into a class's scope by 2483 /// a using declaration, this is that class; otherwise it's 2484 /// the class declaring the member. 2485 /// 2486 /// * Finally we cast from the declaring class to the "true" 2487 /// declaring class of the member. This conversion does not 2488 /// obey access control. 2489 ExprResult 2490 Sema::PerformObjectMemberConversion(Expr *From, 2491 NestedNameSpecifier *Qualifier, 2492 NamedDecl *FoundDecl, 2493 NamedDecl *Member) { 2494 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2495 if (!RD) 2496 return From; 2497 2498 QualType DestRecordType; 2499 QualType DestType; 2500 QualType FromRecordType; 2501 QualType FromType = From->getType(); 2502 bool PointerConversions = false; 2503 if (isa<FieldDecl>(Member)) { 2504 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2505 2506 if (FromType->getAs<PointerType>()) { 2507 DestType = Context.getPointerType(DestRecordType); 2508 FromRecordType = FromType->getPointeeType(); 2509 PointerConversions = true; 2510 } else { 2511 DestType = DestRecordType; 2512 FromRecordType = FromType; 2513 } 2514 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2515 if (Method->isStatic()) 2516 return From; 2517 2518 DestType = Method->getThisType(Context); 2519 DestRecordType = DestType->getPointeeType(); 2520 2521 if (FromType->getAs<PointerType>()) { 2522 FromRecordType = FromType->getPointeeType(); 2523 PointerConversions = true; 2524 } else { 2525 FromRecordType = FromType; 2526 DestType = DestRecordType; 2527 } 2528 } else { 2529 // No conversion necessary. 2530 return From; 2531 } 2532 2533 if (DestType->isDependentType() || FromType->isDependentType()) 2534 return From; 2535 2536 // If the unqualified types are the same, no conversion is necessary. 2537 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2538 return From; 2539 2540 SourceRange FromRange = From->getSourceRange(); 2541 SourceLocation FromLoc = FromRange.getBegin(); 2542 2543 ExprValueKind VK = From->getValueKind(); 2544 2545 // C++ [class.member.lookup]p8: 2546 // [...] Ambiguities can often be resolved by qualifying a name with its 2547 // class name. 2548 // 2549 // If the member was a qualified name and the qualified referred to a 2550 // specific base subobject type, we'll cast to that intermediate type 2551 // first and then to the object in which the member is declared. That allows 2552 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2553 // 2554 // class Base { public: int x; }; 2555 // class Derived1 : public Base { }; 2556 // class Derived2 : public Base { }; 2557 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2558 // 2559 // void VeryDerived::f() { 2560 // x = 17; // error: ambiguous base subobjects 2561 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2562 // } 2563 if (Qualifier && Qualifier->getAsType()) { 2564 QualType QType = QualType(Qualifier->getAsType(), 0); 2565 assert(QType->isRecordType() && "lookup done with non-record type"); 2566 2567 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2568 2569 // In C++98, the qualifier type doesn't actually have to be a base 2570 // type of the object type, in which case we just ignore it. 2571 // Otherwise build the appropriate casts. 2572 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2573 CXXCastPath BasePath; 2574 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2575 FromLoc, FromRange, &BasePath)) 2576 return ExprError(); 2577 2578 if (PointerConversions) 2579 QType = Context.getPointerType(QType); 2580 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2581 VK, &BasePath).get(); 2582 2583 FromType = QType; 2584 FromRecordType = QRecordType; 2585 2586 // If the qualifier type was the same as the destination type, 2587 // we're done. 2588 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2589 return From; 2590 } 2591 } 2592 2593 bool IgnoreAccess = false; 2594 2595 // If we actually found the member through a using declaration, cast 2596 // down to the using declaration's type. 2597 // 2598 // Pointer equality is fine here because only one declaration of a 2599 // class ever has member declarations. 2600 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2601 assert(isa<UsingShadowDecl>(FoundDecl)); 2602 QualType URecordType = Context.getTypeDeclType( 2603 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2604 2605 // We only need to do this if the naming-class to declaring-class 2606 // conversion is non-trivial. 2607 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2608 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2609 CXXCastPath BasePath; 2610 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2611 FromLoc, FromRange, &BasePath)) 2612 return ExprError(); 2613 2614 QualType UType = URecordType; 2615 if (PointerConversions) 2616 UType = Context.getPointerType(UType); 2617 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2618 VK, &BasePath).get(); 2619 FromType = UType; 2620 FromRecordType = URecordType; 2621 } 2622 2623 // We don't do access control for the conversion from the 2624 // declaring class to the true declaring class. 2625 IgnoreAccess = true; 2626 } 2627 2628 CXXCastPath BasePath; 2629 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2630 FromLoc, FromRange, &BasePath, 2631 IgnoreAccess)) 2632 return ExprError(); 2633 2634 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2635 VK, &BasePath); 2636 } 2637 2638 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2639 const LookupResult &R, 2640 bool HasTrailingLParen) { 2641 // Only when used directly as the postfix-expression of a call. 2642 if (!HasTrailingLParen) 2643 return false; 2644 2645 // Never if a scope specifier was provided. 2646 if (SS.isSet()) 2647 return false; 2648 2649 // Only in C++ or ObjC++. 2650 if (!getLangOpts().CPlusPlus) 2651 return false; 2652 2653 // Turn off ADL when we find certain kinds of declarations during 2654 // normal lookup: 2655 for (NamedDecl *D : R) { 2656 // C++0x [basic.lookup.argdep]p3: 2657 // -- a declaration of a class member 2658 // Since using decls preserve this property, we check this on the 2659 // original decl. 2660 if (D->isCXXClassMember()) 2661 return false; 2662 2663 // C++0x [basic.lookup.argdep]p3: 2664 // -- a block-scope function declaration that is not a 2665 // using-declaration 2666 // NOTE: we also trigger this for function templates (in fact, we 2667 // don't check the decl type at all, since all other decl types 2668 // turn off ADL anyway). 2669 if (isa<UsingShadowDecl>(D)) 2670 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2671 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2672 return false; 2673 2674 // C++0x [basic.lookup.argdep]p3: 2675 // -- a declaration that is neither a function or a function 2676 // template 2677 // And also for builtin functions. 2678 if (isa<FunctionDecl>(D)) { 2679 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2680 2681 // But also builtin functions. 2682 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2683 return false; 2684 } else if (!isa<FunctionTemplateDecl>(D)) 2685 return false; 2686 } 2687 2688 return true; 2689 } 2690 2691 2692 /// Diagnoses obvious problems with the use of the given declaration 2693 /// as an expression. This is only actually called for lookups that 2694 /// were not overloaded, and it doesn't promise that the declaration 2695 /// will in fact be used. 2696 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2697 if (D->isInvalidDecl()) 2698 return true; 2699 2700 if (isa<TypedefNameDecl>(D)) { 2701 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2702 return true; 2703 } 2704 2705 if (isa<ObjCInterfaceDecl>(D)) { 2706 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2707 return true; 2708 } 2709 2710 if (isa<NamespaceDecl>(D)) { 2711 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2712 return true; 2713 } 2714 2715 return false; 2716 } 2717 2718 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2719 LookupResult &R, bool NeedsADL, 2720 bool AcceptInvalidDecl) { 2721 // If this is a single, fully-resolved result and we don't need ADL, 2722 // just build an ordinary singleton decl ref. 2723 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2724 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2725 R.getRepresentativeDecl(), nullptr, 2726 AcceptInvalidDecl); 2727 2728 // We only need to check the declaration if there's exactly one 2729 // result, because in the overloaded case the results can only be 2730 // functions and function templates. 2731 if (R.isSingleResult() && 2732 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2733 return ExprError(); 2734 2735 // Otherwise, just build an unresolved lookup expression. Suppress 2736 // any lookup-related diagnostics; we'll hash these out later, when 2737 // we've picked a target. 2738 R.suppressDiagnostics(); 2739 2740 UnresolvedLookupExpr *ULE 2741 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2742 SS.getWithLocInContext(Context), 2743 R.getLookupNameInfo(), 2744 NeedsADL, R.isOverloadedResult(), 2745 R.begin(), R.end()); 2746 2747 return ULE; 2748 } 2749 2750 static void 2751 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2752 ValueDecl *var, DeclContext *DC); 2753 2754 /// \brief Complete semantic analysis for a reference to the given declaration. 2755 ExprResult Sema::BuildDeclarationNameExpr( 2756 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2757 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2758 bool AcceptInvalidDecl) { 2759 assert(D && "Cannot refer to a NULL declaration"); 2760 assert(!isa<FunctionTemplateDecl>(D) && 2761 "Cannot refer unambiguously to a function template"); 2762 2763 SourceLocation Loc = NameInfo.getLoc(); 2764 if (CheckDeclInExpr(*this, Loc, D)) 2765 return ExprError(); 2766 2767 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2768 // Specifically diagnose references to class templates that are missing 2769 // a template argument list. 2770 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2771 << Template << SS.getRange(); 2772 Diag(Template->getLocation(), diag::note_template_decl_here); 2773 return ExprError(); 2774 } 2775 2776 // Make sure that we're referring to a value. 2777 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2778 if (!VD) { 2779 Diag(Loc, diag::err_ref_non_value) 2780 << D << SS.getRange(); 2781 Diag(D->getLocation(), diag::note_declared_at); 2782 return ExprError(); 2783 } 2784 2785 // Check whether this declaration can be used. Note that we suppress 2786 // this check when we're going to perform argument-dependent lookup 2787 // on this function name, because this might not be the function 2788 // that overload resolution actually selects. 2789 if (DiagnoseUseOfDecl(VD, Loc)) 2790 return ExprError(); 2791 2792 // Only create DeclRefExpr's for valid Decl's. 2793 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2794 return ExprError(); 2795 2796 // Handle members of anonymous structs and unions. If we got here, 2797 // and the reference is to a class member indirect field, then this 2798 // must be the subject of a pointer-to-member expression. 2799 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2800 if (!indirectField->isCXXClassMember()) 2801 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2802 indirectField); 2803 2804 { 2805 QualType type = VD->getType(); 2806 if (type.isNull()) 2807 return ExprError(); 2808 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2809 // C++ [except.spec]p17: 2810 // An exception-specification is considered to be needed when: 2811 // - in an expression, the function is the unique lookup result or 2812 // the selected member of a set of overloaded functions. 2813 ResolveExceptionSpec(Loc, FPT); 2814 type = VD->getType(); 2815 } 2816 ExprValueKind valueKind = VK_RValue; 2817 2818 switch (D->getKind()) { 2819 // Ignore all the non-ValueDecl kinds. 2820 #define ABSTRACT_DECL(kind) 2821 #define VALUE(type, base) 2822 #define DECL(type, base) \ 2823 case Decl::type: 2824 #include "clang/AST/DeclNodes.inc" 2825 llvm_unreachable("invalid value decl kind"); 2826 2827 // These shouldn't make it here. 2828 case Decl::ObjCAtDefsField: 2829 case Decl::ObjCIvar: 2830 llvm_unreachable("forming non-member reference to ivar?"); 2831 2832 // Enum constants are always r-values and never references. 2833 // Unresolved using declarations are dependent. 2834 case Decl::EnumConstant: 2835 case Decl::UnresolvedUsingValue: 2836 case Decl::OMPDeclareReduction: 2837 valueKind = VK_RValue; 2838 break; 2839 2840 // Fields and indirect fields that got here must be for 2841 // pointer-to-member expressions; we just call them l-values for 2842 // internal consistency, because this subexpression doesn't really 2843 // exist in the high-level semantics. 2844 case Decl::Field: 2845 case Decl::IndirectField: 2846 assert(getLangOpts().CPlusPlus && 2847 "building reference to field in C?"); 2848 2849 // These can't have reference type in well-formed programs, but 2850 // for internal consistency we do this anyway. 2851 type = type.getNonReferenceType(); 2852 valueKind = VK_LValue; 2853 break; 2854 2855 // Non-type template parameters are either l-values or r-values 2856 // depending on the type. 2857 case Decl::NonTypeTemplateParm: { 2858 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2859 type = reftype->getPointeeType(); 2860 valueKind = VK_LValue; // even if the parameter is an r-value reference 2861 break; 2862 } 2863 2864 // For non-references, we need to strip qualifiers just in case 2865 // the template parameter was declared as 'const int' or whatever. 2866 valueKind = VK_RValue; 2867 type = type.getUnqualifiedType(); 2868 break; 2869 } 2870 2871 case Decl::Var: 2872 case Decl::VarTemplateSpecialization: 2873 case Decl::VarTemplatePartialSpecialization: 2874 case Decl::Decomposition: 2875 case Decl::OMPCapturedExpr: 2876 // In C, "extern void blah;" is valid and is an r-value. 2877 if (!getLangOpts().CPlusPlus && 2878 !type.hasQualifiers() && 2879 type->isVoidType()) { 2880 valueKind = VK_RValue; 2881 break; 2882 } 2883 // fallthrough 2884 2885 case Decl::ImplicitParam: 2886 case Decl::ParmVar: { 2887 // These are always l-values. 2888 valueKind = VK_LValue; 2889 type = type.getNonReferenceType(); 2890 2891 // FIXME: Does the addition of const really only apply in 2892 // potentially-evaluated contexts? Since the variable isn't actually 2893 // captured in an unevaluated context, it seems that the answer is no. 2894 if (!isUnevaluatedContext()) { 2895 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2896 if (!CapturedType.isNull()) 2897 type = CapturedType; 2898 } 2899 2900 break; 2901 } 2902 2903 case Decl::Binding: { 2904 // These are always lvalues. 2905 valueKind = VK_LValue; 2906 type = type.getNonReferenceType(); 2907 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2908 // decides how that's supposed to work. 2909 auto *BD = cast<BindingDecl>(VD); 2910 if (BD->getDeclContext()->isFunctionOrMethod() && 2911 BD->getDeclContext() != CurContext) 2912 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2913 break; 2914 } 2915 2916 case Decl::Function: { 2917 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2918 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2919 type = Context.BuiltinFnTy; 2920 valueKind = VK_RValue; 2921 break; 2922 } 2923 } 2924 2925 const FunctionType *fty = type->castAs<FunctionType>(); 2926 2927 // If we're referring to a function with an __unknown_anytype 2928 // result type, make the entire expression __unknown_anytype. 2929 if (fty->getReturnType() == Context.UnknownAnyTy) { 2930 type = Context.UnknownAnyTy; 2931 valueKind = VK_RValue; 2932 break; 2933 } 2934 2935 // Functions are l-values in C++. 2936 if (getLangOpts().CPlusPlus) { 2937 valueKind = VK_LValue; 2938 break; 2939 } 2940 2941 // C99 DR 316 says that, if a function type comes from a 2942 // function definition (without a prototype), that type is only 2943 // used for checking compatibility. Therefore, when referencing 2944 // the function, we pretend that we don't have the full function 2945 // type. 2946 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2947 isa<FunctionProtoType>(fty)) 2948 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2949 fty->getExtInfo()); 2950 2951 // Functions are r-values in C. 2952 valueKind = VK_RValue; 2953 break; 2954 } 2955 2956 case Decl::CXXDeductionGuide: 2957 llvm_unreachable("building reference to deduction guide"); 2958 2959 case Decl::MSProperty: 2960 valueKind = VK_LValue; 2961 break; 2962 2963 case Decl::CXXMethod: 2964 // If we're referring to a method with an __unknown_anytype 2965 // result type, make the entire expression __unknown_anytype. 2966 // This should only be possible with a type written directly. 2967 if (const FunctionProtoType *proto 2968 = dyn_cast<FunctionProtoType>(VD->getType())) 2969 if (proto->getReturnType() == Context.UnknownAnyTy) { 2970 type = Context.UnknownAnyTy; 2971 valueKind = VK_RValue; 2972 break; 2973 } 2974 2975 // C++ methods are l-values if static, r-values if non-static. 2976 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2977 valueKind = VK_LValue; 2978 break; 2979 } 2980 // fallthrough 2981 2982 case Decl::CXXConversion: 2983 case Decl::CXXDestructor: 2984 case Decl::CXXConstructor: 2985 valueKind = VK_RValue; 2986 break; 2987 } 2988 2989 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2990 TemplateArgs); 2991 } 2992 } 2993 2994 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2995 SmallString<32> &Target) { 2996 Target.resize(CharByteWidth * (Source.size() + 1)); 2997 char *ResultPtr = &Target[0]; 2998 const llvm::UTF8 *ErrorPtr; 2999 bool success = 3000 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3001 (void)success; 3002 assert(success); 3003 Target.resize(ResultPtr - &Target[0]); 3004 } 3005 3006 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3007 PredefinedExpr::IdentType IT) { 3008 // Pick the current block, lambda, captured statement or function. 3009 Decl *currentDecl = nullptr; 3010 if (const BlockScopeInfo *BSI = getCurBlock()) 3011 currentDecl = BSI->TheDecl; 3012 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3013 currentDecl = LSI->CallOperator; 3014 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3015 currentDecl = CSI->TheCapturedDecl; 3016 else 3017 currentDecl = getCurFunctionOrMethodDecl(); 3018 3019 if (!currentDecl) { 3020 Diag(Loc, diag::ext_predef_outside_function); 3021 currentDecl = Context.getTranslationUnitDecl(); 3022 } 3023 3024 QualType ResTy; 3025 StringLiteral *SL = nullptr; 3026 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3027 ResTy = Context.DependentTy; 3028 else { 3029 // Pre-defined identifiers are of type char[x], where x is the length of 3030 // the string. 3031 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3032 unsigned Length = Str.length(); 3033 3034 llvm::APInt LengthI(32, Length + 1); 3035 if (IT == PredefinedExpr::LFunction) { 3036 ResTy = Context.WideCharTy.withConst(); 3037 SmallString<32> RawChars; 3038 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3039 Str, RawChars); 3040 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3041 /*IndexTypeQuals*/ 0); 3042 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3043 /*Pascal*/ false, ResTy, Loc); 3044 } else { 3045 ResTy = Context.CharTy.withConst(); 3046 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3047 /*IndexTypeQuals*/ 0); 3048 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3049 /*Pascal*/ false, ResTy, Loc); 3050 } 3051 } 3052 3053 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3054 } 3055 3056 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3057 PredefinedExpr::IdentType IT; 3058 3059 switch (Kind) { 3060 default: llvm_unreachable("Unknown simple primary expr!"); 3061 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3062 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3063 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3064 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3065 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3066 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3067 } 3068 3069 return BuildPredefinedExpr(Loc, IT); 3070 } 3071 3072 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3073 SmallString<16> CharBuffer; 3074 bool Invalid = false; 3075 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3076 if (Invalid) 3077 return ExprError(); 3078 3079 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3080 PP, Tok.getKind()); 3081 if (Literal.hadError()) 3082 return ExprError(); 3083 3084 QualType Ty; 3085 if (Literal.isWide()) 3086 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3087 else if (Literal.isUTF16()) 3088 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3089 else if (Literal.isUTF32()) 3090 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3091 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3092 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3093 else 3094 Ty = Context.CharTy; // 'x' -> char in C++ 3095 3096 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3097 if (Literal.isWide()) 3098 Kind = CharacterLiteral::Wide; 3099 else if (Literal.isUTF16()) 3100 Kind = CharacterLiteral::UTF16; 3101 else if (Literal.isUTF32()) 3102 Kind = CharacterLiteral::UTF32; 3103 else if (Literal.isUTF8()) 3104 Kind = CharacterLiteral::UTF8; 3105 3106 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3107 Tok.getLocation()); 3108 3109 if (Literal.getUDSuffix().empty()) 3110 return Lit; 3111 3112 // We're building a user-defined literal. 3113 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3114 SourceLocation UDSuffixLoc = 3115 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3116 3117 // Make sure we're allowed user-defined literals here. 3118 if (!UDLScope) 3119 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3120 3121 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3122 // operator "" X (ch) 3123 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3124 Lit, Tok.getLocation()); 3125 } 3126 3127 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3128 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3129 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3130 Context.IntTy, Loc); 3131 } 3132 3133 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3134 QualType Ty, SourceLocation Loc) { 3135 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3136 3137 using llvm::APFloat; 3138 APFloat Val(Format); 3139 3140 APFloat::opStatus result = Literal.GetFloatValue(Val); 3141 3142 // Overflow is always an error, but underflow is only an error if 3143 // we underflowed to zero (APFloat reports denormals as underflow). 3144 if ((result & APFloat::opOverflow) || 3145 ((result & APFloat::opUnderflow) && Val.isZero())) { 3146 unsigned diagnostic; 3147 SmallString<20> buffer; 3148 if (result & APFloat::opOverflow) { 3149 diagnostic = diag::warn_float_overflow; 3150 APFloat::getLargest(Format).toString(buffer); 3151 } else { 3152 diagnostic = diag::warn_float_underflow; 3153 APFloat::getSmallest(Format).toString(buffer); 3154 } 3155 3156 S.Diag(Loc, diagnostic) 3157 << Ty 3158 << StringRef(buffer.data(), buffer.size()); 3159 } 3160 3161 bool isExact = (result == APFloat::opOK); 3162 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3163 } 3164 3165 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3166 assert(E && "Invalid expression"); 3167 3168 if (E->isValueDependent()) 3169 return false; 3170 3171 QualType QT = E->getType(); 3172 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3173 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3174 return true; 3175 } 3176 3177 llvm::APSInt ValueAPS; 3178 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3179 3180 if (R.isInvalid()) 3181 return true; 3182 3183 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3184 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3185 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3186 << ValueAPS.toString(10) << ValueIsPositive; 3187 return true; 3188 } 3189 3190 return false; 3191 } 3192 3193 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3194 // Fast path for a single digit (which is quite common). A single digit 3195 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3196 if (Tok.getLength() == 1) { 3197 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3198 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3199 } 3200 3201 SmallString<128> SpellingBuffer; 3202 // NumericLiteralParser wants to overread by one character. Add padding to 3203 // the buffer in case the token is copied to the buffer. If getSpelling() 3204 // returns a StringRef to the memory buffer, it should have a null char at 3205 // the EOF, so it is also safe. 3206 SpellingBuffer.resize(Tok.getLength() + 1); 3207 3208 // Get the spelling of the token, which eliminates trigraphs, etc. 3209 bool Invalid = false; 3210 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3211 if (Invalid) 3212 return ExprError(); 3213 3214 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3215 if (Literal.hadError) 3216 return ExprError(); 3217 3218 if (Literal.hasUDSuffix()) { 3219 // We're building a user-defined literal. 3220 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3221 SourceLocation UDSuffixLoc = 3222 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3223 3224 // Make sure we're allowed user-defined literals here. 3225 if (!UDLScope) 3226 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3227 3228 QualType CookedTy; 3229 if (Literal.isFloatingLiteral()) { 3230 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3231 // long double, the literal is treated as a call of the form 3232 // operator "" X (f L) 3233 CookedTy = Context.LongDoubleTy; 3234 } else { 3235 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3236 // unsigned long long, the literal is treated as a call of the form 3237 // operator "" X (n ULL) 3238 CookedTy = Context.UnsignedLongLongTy; 3239 } 3240 3241 DeclarationName OpName = 3242 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3243 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3244 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3245 3246 SourceLocation TokLoc = Tok.getLocation(); 3247 3248 // Perform literal operator lookup to determine if we're building a raw 3249 // literal or a cooked one. 3250 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3251 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3252 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3253 /*AllowStringTemplate*/ false, 3254 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3255 case LOLR_ErrorNoDiagnostic: 3256 // Lookup failure for imaginary constants isn't fatal, there's still the 3257 // GNU extension producing _Complex types. 3258 break; 3259 case LOLR_Error: 3260 return ExprError(); 3261 case LOLR_Cooked: { 3262 Expr *Lit; 3263 if (Literal.isFloatingLiteral()) { 3264 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3265 } else { 3266 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3267 if (Literal.GetIntegerValue(ResultVal)) 3268 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3269 << /* Unsigned */ 1; 3270 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3271 Tok.getLocation()); 3272 } 3273 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3274 } 3275 3276 case LOLR_Raw: { 3277 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3278 // literal is treated as a call of the form 3279 // operator "" X ("n") 3280 unsigned Length = Literal.getUDSuffixOffset(); 3281 QualType StrTy = Context.getConstantArrayType( 3282 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3283 ArrayType::Normal, 0); 3284 Expr *Lit = StringLiteral::Create( 3285 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3286 /*Pascal*/false, StrTy, &TokLoc, 1); 3287 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3288 } 3289 3290 case LOLR_Template: { 3291 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3292 // template), L is treated as a call fo the form 3293 // operator "" X <'c1', 'c2', ... 'ck'>() 3294 // where n is the source character sequence c1 c2 ... ck. 3295 TemplateArgumentListInfo ExplicitArgs; 3296 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3297 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3298 llvm::APSInt Value(CharBits, CharIsUnsigned); 3299 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3300 Value = TokSpelling[I]; 3301 TemplateArgument Arg(Context, Value, Context.CharTy); 3302 TemplateArgumentLocInfo ArgInfo; 3303 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3304 } 3305 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3306 &ExplicitArgs); 3307 } 3308 case LOLR_StringTemplate: 3309 llvm_unreachable("unexpected literal operator lookup result"); 3310 } 3311 } 3312 3313 Expr *Res; 3314 3315 if (Literal.isFloatingLiteral()) { 3316 QualType Ty; 3317 if (Literal.isHalf){ 3318 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3319 Ty = Context.HalfTy; 3320 else { 3321 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3322 return ExprError(); 3323 } 3324 } else if (Literal.isFloat) 3325 Ty = Context.FloatTy; 3326 else if (Literal.isLong) 3327 Ty = Context.LongDoubleTy; 3328 else if (Literal.isFloat16) 3329 Ty = Context.Float16Ty; 3330 else if (Literal.isFloat128) 3331 Ty = Context.Float128Ty; 3332 else 3333 Ty = Context.DoubleTy; 3334 3335 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3336 3337 if (Ty == Context.DoubleTy) { 3338 if (getLangOpts().SinglePrecisionConstants) { 3339 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3340 if (BTy->getKind() != BuiltinType::Float) { 3341 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3342 } 3343 } else if (getLangOpts().OpenCL && 3344 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3345 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3346 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3347 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3348 } 3349 } 3350 } else if (!Literal.isIntegerLiteral()) { 3351 return ExprError(); 3352 } else { 3353 QualType Ty; 3354 3355 // 'long long' is a C99 or C++11 feature. 3356 if (!getLangOpts().C99 && Literal.isLongLong) { 3357 if (getLangOpts().CPlusPlus) 3358 Diag(Tok.getLocation(), 3359 getLangOpts().CPlusPlus11 ? 3360 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3361 else 3362 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3363 } 3364 3365 // Get the value in the widest-possible width. 3366 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3367 llvm::APInt ResultVal(MaxWidth, 0); 3368 3369 if (Literal.GetIntegerValue(ResultVal)) { 3370 // If this value didn't fit into uintmax_t, error and force to ull. 3371 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3372 << /* Unsigned */ 1; 3373 Ty = Context.UnsignedLongLongTy; 3374 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3375 "long long is not intmax_t?"); 3376 } else { 3377 // If this value fits into a ULL, try to figure out what else it fits into 3378 // according to the rules of C99 6.4.4.1p5. 3379 3380 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3381 // be an unsigned int. 3382 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3383 3384 // Check from smallest to largest, picking the smallest type we can. 3385 unsigned Width = 0; 3386 3387 // Microsoft specific integer suffixes are explicitly sized. 3388 if (Literal.MicrosoftInteger) { 3389 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3390 Width = 8; 3391 Ty = Context.CharTy; 3392 } else { 3393 Width = Literal.MicrosoftInteger; 3394 Ty = Context.getIntTypeForBitwidth(Width, 3395 /*Signed=*/!Literal.isUnsigned); 3396 } 3397 } 3398 3399 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3400 // Are int/unsigned possibilities? 3401 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3402 3403 // Does it fit in a unsigned int? 3404 if (ResultVal.isIntN(IntSize)) { 3405 // Does it fit in a signed int? 3406 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3407 Ty = Context.IntTy; 3408 else if (AllowUnsigned) 3409 Ty = Context.UnsignedIntTy; 3410 Width = IntSize; 3411 } 3412 } 3413 3414 // Are long/unsigned long possibilities? 3415 if (Ty.isNull() && !Literal.isLongLong) { 3416 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3417 3418 // Does it fit in a unsigned long? 3419 if (ResultVal.isIntN(LongSize)) { 3420 // Does it fit in a signed long? 3421 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3422 Ty = Context.LongTy; 3423 else if (AllowUnsigned) 3424 Ty = Context.UnsignedLongTy; 3425 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3426 // is compatible. 3427 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3428 const unsigned LongLongSize = 3429 Context.getTargetInfo().getLongLongWidth(); 3430 Diag(Tok.getLocation(), 3431 getLangOpts().CPlusPlus 3432 ? Literal.isLong 3433 ? diag::warn_old_implicitly_unsigned_long_cxx 3434 : /*C++98 UB*/ diag:: 3435 ext_old_implicitly_unsigned_long_cxx 3436 : diag::warn_old_implicitly_unsigned_long) 3437 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3438 : /*will be ill-formed*/ 1); 3439 Ty = Context.UnsignedLongTy; 3440 } 3441 Width = LongSize; 3442 } 3443 } 3444 3445 // Check long long if needed. 3446 if (Ty.isNull()) { 3447 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3448 3449 // Does it fit in a unsigned long long? 3450 if (ResultVal.isIntN(LongLongSize)) { 3451 // Does it fit in a signed long long? 3452 // To be compatible with MSVC, hex integer literals ending with the 3453 // LL or i64 suffix are always signed in Microsoft mode. 3454 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3455 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3456 Ty = Context.LongLongTy; 3457 else if (AllowUnsigned) 3458 Ty = Context.UnsignedLongLongTy; 3459 Width = LongLongSize; 3460 } 3461 } 3462 3463 // If we still couldn't decide a type, we probably have something that 3464 // does not fit in a signed long long, but has no U suffix. 3465 if (Ty.isNull()) { 3466 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3467 Ty = Context.UnsignedLongLongTy; 3468 Width = Context.getTargetInfo().getLongLongWidth(); 3469 } 3470 3471 if (ResultVal.getBitWidth() != Width) 3472 ResultVal = ResultVal.trunc(Width); 3473 } 3474 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3475 } 3476 3477 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3478 if (Literal.isImaginary) { 3479 Res = new (Context) ImaginaryLiteral(Res, 3480 Context.getComplexType(Res->getType())); 3481 3482 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3483 } 3484 return Res; 3485 } 3486 3487 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3488 assert(E && "ActOnParenExpr() missing expr"); 3489 return new (Context) ParenExpr(L, R, E); 3490 } 3491 3492 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3493 SourceLocation Loc, 3494 SourceRange ArgRange) { 3495 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3496 // scalar or vector data type argument..." 3497 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3498 // type (C99 6.2.5p18) or void. 3499 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3500 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3501 << T << ArgRange; 3502 return true; 3503 } 3504 3505 assert((T->isVoidType() || !T->isIncompleteType()) && 3506 "Scalar types should always be complete"); 3507 return false; 3508 } 3509 3510 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3511 SourceLocation Loc, 3512 SourceRange ArgRange, 3513 UnaryExprOrTypeTrait TraitKind) { 3514 // Invalid types must be hard errors for SFINAE in C++. 3515 if (S.LangOpts.CPlusPlus) 3516 return true; 3517 3518 // C99 6.5.3.4p1: 3519 if (T->isFunctionType() && 3520 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3521 // sizeof(function)/alignof(function) is allowed as an extension. 3522 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3523 << TraitKind << ArgRange; 3524 return false; 3525 } 3526 3527 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3528 // this is an error (OpenCL v1.1 s6.3.k) 3529 if (T->isVoidType()) { 3530 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3531 : diag::ext_sizeof_alignof_void_type; 3532 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3533 return false; 3534 } 3535 3536 return true; 3537 } 3538 3539 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3540 SourceLocation Loc, 3541 SourceRange ArgRange, 3542 UnaryExprOrTypeTrait TraitKind) { 3543 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3544 // runtime doesn't allow it. 3545 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3546 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3547 << T << (TraitKind == UETT_SizeOf) 3548 << ArgRange; 3549 return true; 3550 } 3551 3552 return false; 3553 } 3554 3555 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3556 /// pointer type is equal to T) and emit a warning if it is. 3557 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3558 Expr *E) { 3559 // Don't warn if the operation changed the type. 3560 if (T != E->getType()) 3561 return; 3562 3563 // Now look for array decays. 3564 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3565 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3566 return; 3567 3568 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3569 << ICE->getType() 3570 << ICE->getSubExpr()->getType(); 3571 } 3572 3573 /// \brief Check the constraints on expression operands to unary type expression 3574 /// and type traits. 3575 /// 3576 /// Completes any types necessary and validates the constraints on the operand 3577 /// expression. The logic mostly mirrors the type-based overload, but may modify 3578 /// the expression as it completes the type for that expression through template 3579 /// instantiation, etc. 3580 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3581 UnaryExprOrTypeTrait ExprKind) { 3582 QualType ExprTy = E->getType(); 3583 assert(!ExprTy->isReferenceType()); 3584 3585 if (ExprKind == UETT_VecStep) 3586 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3587 E->getSourceRange()); 3588 3589 // Whitelist some types as extensions 3590 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3591 E->getSourceRange(), ExprKind)) 3592 return false; 3593 3594 // 'alignof' applied to an expression only requires the base element type of 3595 // the expression to be complete. 'sizeof' requires the expression's type to 3596 // be complete (and will attempt to complete it if it's an array of unknown 3597 // bound). 3598 if (ExprKind == UETT_AlignOf) { 3599 if (RequireCompleteType(E->getExprLoc(), 3600 Context.getBaseElementType(E->getType()), 3601 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3602 E->getSourceRange())) 3603 return true; 3604 } else { 3605 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3606 ExprKind, E->getSourceRange())) 3607 return true; 3608 } 3609 3610 // Completing the expression's type may have changed it. 3611 ExprTy = E->getType(); 3612 assert(!ExprTy->isReferenceType()); 3613 3614 if (ExprTy->isFunctionType()) { 3615 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3616 << ExprKind << E->getSourceRange(); 3617 return true; 3618 } 3619 3620 // The operand for sizeof and alignof is in an unevaluated expression context, 3621 // so side effects could result in unintended consequences. 3622 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3623 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3624 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3625 3626 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3627 E->getSourceRange(), ExprKind)) 3628 return true; 3629 3630 if (ExprKind == UETT_SizeOf) { 3631 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3632 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3633 QualType OType = PVD->getOriginalType(); 3634 QualType Type = PVD->getType(); 3635 if (Type->isPointerType() && OType->isArrayType()) { 3636 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3637 << Type << OType; 3638 Diag(PVD->getLocation(), diag::note_declared_at); 3639 } 3640 } 3641 } 3642 3643 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3644 // decays into a pointer and returns an unintended result. This is most 3645 // likely a typo for "sizeof(array) op x". 3646 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3647 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3648 BO->getLHS()); 3649 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3650 BO->getRHS()); 3651 } 3652 } 3653 3654 return false; 3655 } 3656 3657 /// \brief Check the constraints on operands to unary expression and type 3658 /// traits. 3659 /// 3660 /// This will complete any types necessary, and validate the various constraints 3661 /// on those operands. 3662 /// 3663 /// The UsualUnaryConversions() function is *not* called by this routine. 3664 /// C99 6.3.2.1p[2-4] all state: 3665 /// Except when it is the operand of the sizeof operator ... 3666 /// 3667 /// C++ [expr.sizeof]p4 3668 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3669 /// standard conversions are not applied to the operand of sizeof. 3670 /// 3671 /// This policy is followed for all of the unary trait expressions. 3672 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3673 SourceLocation OpLoc, 3674 SourceRange ExprRange, 3675 UnaryExprOrTypeTrait ExprKind) { 3676 if (ExprType->isDependentType()) 3677 return false; 3678 3679 // C++ [expr.sizeof]p2: 3680 // When applied to a reference or a reference type, the result 3681 // is the size of the referenced type. 3682 // C++11 [expr.alignof]p3: 3683 // When alignof is applied to a reference type, the result 3684 // shall be the alignment of the referenced type. 3685 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3686 ExprType = Ref->getPointeeType(); 3687 3688 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3689 // When alignof or _Alignof is applied to an array type, the result 3690 // is the alignment of the element type. 3691 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3692 ExprType = Context.getBaseElementType(ExprType); 3693 3694 if (ExprKind == UETT_VecStep) 3695 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3696 3697 // Whitelist some types as extensions 3698 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3699 ExprKind)) 3700 return false; 3701 3702 if (RequireCompleteType(OpLoc, ExprType, 3703 diag::err_sizeof_alignof_incomplete_type, 3704 ExprKind, ExprRange)) 3705 return true; 3706 3707 if (ExprType->isFunctionType()) { 3708 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3709 << ExprKind << ExprRange; 3710 return true; 3711 } 3712 3713 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3714 ExprKind)) 3715 return true; 3716 3717 return false; 3718 } 3719 3720 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3721 E = E->IgnoreParens(); 3722 3723 // Cannot know anything else if the expression is dependent. 3724 if (E->isTypeDependent()) 3725 return false; 3726 3727 if (E->getObjectKind() == OK_BitField) { 3728 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3729 << 1 << E->getSourceRange(); 3730 return true; 3731 } 3732 3733 ValueDecl *D = nullptr; 3734 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3735 D = DRE->getDecl(); 3736 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3737 D = ME->getMemberDecl(); 3738 } 3739 3740 // If it's a field, require the containing struct to have a 3741 // complete definition so that we can compute the layout. 3742 // 3743 // This can happen in C++11 onwards, either by naming the member 3744 // in a way that is not transformed into a member access expression 3745 // (in an unevaluated operand, for instance), or by naming the member 3746 // in a trailing-return-type. 3747 // 3748 // For the record, since __alignof__ on expressions is a GCC 3749 // extension, GCC seems to permit this but always gives the 3750 // nonsensical answer 0. 3751 // 3752 // We don't really need the layout here --- we could instead just 3753 // directly check for all the appropriate alignment-lowing 3754 // attributes --- but that would require duplicating a lot of 3755 // logic that just isn't worth duplicating for such a marginal 3756 // use-case. 3757 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3758 // Fast path this check, since we at least know the record has a 3759 // definition if we can find a member of it. 3760 if (!FD->getParent()->isCompleteDefinition()) { 3761 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3762 << E->getSourceRange(); 3763 return true; 3764 } 3765 3766 // Otherwise, if it's a field, and the field doesn't have 3767 // reference type, then it must have a complete type (or be a 3768 // flexible array member, which we explicitly want to 3769 // white-list anyway), which makes the following checks trivial. 3770 if (!FD->getType()->isReferenceType()) 3771 return false; 3772 } 3773 3774 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3775 } 3776 3777 bool Sema::CheckVecStepExpr(Expr *E) { 3778 E = E->IgnoreParens(); 3779 3780 // Cannot know anything else if the expression is dependent. 3781 if (E->isTypeDependent()) 3782 return false; 3783 3784 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3785 } 3786 3787 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3788 CapturingScopeInfo *CSI) { 3789 assert(T->isVariablyModifiedType()); 3790 assert(CSI != nullptr); 3791 3792 // We're going to walk down into the type and look for VLA expressions. 3793 do { 3794 const Type *Ty = T.getTypePtr(); 3795 switch (Ty->getTypeClass()) { 3796 #define TYPE(Class, Base) 3797 #define ABSTRACT_TYPE(Class, Base) 3798 #define NON_CANONICAL_TYPE(Class, Base) 3799 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3800 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3801 #include "clang/AST/TypeNodes.def" 3802 T = QualType(); 3803 break; 3804 // These types are never variably-modified. 3805 case Type::Builtin: 3806 case Type::Complex: 3807 case Type::Vector: 3808 case Type::ExtVector: 3809 case Type::Record: 3810 case Type::Enum: 3811 case Type::Elaborated: 3812 case Type::TemplateSpecialization: 3813 case Type::ObjCObject: 3814 case Type::ObjCInterface: 3815 case Type::ObjCObjectPointer: 3816 case Type::ObjCTypeParam: 3817 case Type::Pipe: 3818 llvm_unreachable("type class is never variably-modified!"); 3819 case Type::Adjusted: 3820 T = cast<AdjustedType>(Ty)->getOriginalType(); 3821 break; 3822 case Type::Decayed: 3823 T = cast<DecayedType>(Ty)->getPointeeType(); 3824 break; 3825 case Type::Pointer: 3826 T = cast<PointerType>(Ty)->getPointeeType(); 3827 break; 3828 case Type::BlockPointer: 3829 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3830 break; 3831 case Type::LValueReference: 3832 case Type::RValueReference: 3833 T = cast<ReferenceType>(Ty)->getPointeeType(); 3834 break; 3835 case Type::MemberPointer: 3836 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3837 break; 3838 case Type::ConstantArray: 3839 case Type::IncompleteArray: 3840 // Losing element qualification here is fine. 3841 T = cast<ArrayType>(Ty)->getElementType(); 3842 break; 3843 case Type::VariableArray: { 3844 // Losing element qualification here is fine. 3845 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3846 3847 // Unknown size indication requires no size computation. 3848 // Otherwise, evaluate and record it. 3849 if (auto Size = VAT->getSizeExpr()) { 3850 if (!CSI->isVLATypeCaptured(VAT)) { 3851 RecordDecl *CapRecord = nullptr; 3852 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3853 CapRecord = LSI->Lambda; 3854 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3855 CapRecord = CRSI->TheRecordDecl; 3856 } 3857 if (CapRecord) { 3858 auto ExprLoc = Size->getExprLoc(); 3859 auto SizeType = Context.getSizeType(); 3860 // Build the non-static data member. 3861 auto Field = 3862 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3863 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3864 /*BW*/ nullptr, /*Mutable*/ false, 3865 /*InitStyle*/ ICIS_NoInit); 3866 Field->setImplicit(true); 3867 Field->setAccess(AS_private); 3868 Field->setCapturedVLAType(VAT); 3869 CapRecord->addDecl(Field); 3870 3871 CSI->addVLATypeCapture(ExprLoc, SizeType); 3872 } 3873 } 3874 } 3875 T = VAT->getElementType(); 3876 break; 3877 } 3878 case Type::FunctionProto: 3879 case Type::FunctionNoProto: 3880 T = cast<FunctionType>(Ty)->getReturnType(); 3881 break; 3882 case Type::Paren: 3883 case Type::TypeOf: 3884 case Type::UnaryTransform: 3885 case Type::Attributed: 3886 case Type::SubstTemplateTypeParm: 3887 case Type::PackExpansion: 3888 // Keep walking after single level desugaring. 3889 T = T.getSingleStepDesugaredType(Context); 3890 break; 3891 case Type::Typedef: 3892 T = cast<TypedefType>(Ty)->desugar(); 3893 break; 3894 case Type::Decltype: 3895 T = cast<DecltypeType>(Ty)->desugar(); 3896 break; 3897 case Type::Auto: 3898 case Type::DeducedTemplateSpecialization: 3899 T = cast<DeducedType>(Ty)->getDeducedType(); 3900 break; 3901 case Type::TypeOfExpr: 3902 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3903 break; 3904 case Type::Atomic: 3905 T = cast<AtomicType>(Ty)->getValueType(); 3906 break; 3907 } 3908 } while (!T.isNull() && T->isVariablyModifiedType()); 3909 } 3910 3911 /// \brief Build a sizeof or alignof expression given a type operand. 3912 ExprResult 3913 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3914 SourceLocation OpLoc, 3915 UnaryExprOrTypeTrait ExprKind, 3916 SourceRange R) { 3917 if (!TInfo) 3918 return ExprError(); 3919 3920 QualType T = TInfo->getType(); 3921 3922 if (!T->isDependentType() && 3923 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3924 return ExprError(); 3925 3926 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3927 if (auto *TT = T->getAs<TypedefType>()) { 3928 for (auto I = FunctionScopes.rbegin(), 3929 E = std::prev(FunctionScopes.rend()); 3930 I != E; ++I) { 3931 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3932 if (CSI == nullptr) 3933 break; 3934 DeclContext *DC = nullptr; 3935 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3936 DC = LSI->CallOperator; 3937 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3938 DC = CRSI->TheCapturedDecl; 3939 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3940 DC = BSI->TheDecl; 3941 if (DC) { 3942 if (DC->containsDecl(TT->getDecl())) 3943 break; 3944 captureVariablyModifiedType(Context, T, CSI); 3945 } 3946 } 3947 } 3948 } 3949 3950 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3951 return new (Context) UnaryExprOrTypeTraitExpr( 3952 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3953 } 3954 3955 /// \brief Build a sizeof or alignof expression given an expression 3956 /// operand. 3957 ExprResult 3958 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3959 UnaryExprOrTypeTrait ExprKind) { 3960 ExprResult PE = CheckPlaceholderExpr(E); 3961 if (PE.isInvalid()) 3962 return ExprError(); 3963 3964 E = PE.get(); 3965 3966 // Verify that the operand is valid. 3967 bool isInvalid = false; 3968 if (E->isTypeDependent()) { 3969 // Delay type-checking for type-dependent expressions. 3970 } else if (ExprKind == UETT_AlignOf) { 3971 isInvalid = CheckAlignOfExpr(*this, E); 3972 } else if (ExprKind == UETT_VecStep) { 3973 isInvalid = CheckVecStepExpr(E); 3974 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3975 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3976 isInvalid = true; 3977 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3978 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3979 isInvalid = true; 3980 } else { 3981 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3982 } 3983 3984 if (isInvalid) 3985 return ExprError(); 3986 3987 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3988 PE = TransformToPotentiallyEvaluated(E); 3989 if (PE.isInvalid()) return ExprError(); 3990 E = PE.get(); 3991 } 3992 3993 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3994 return new (Context) UnaryExprOrTypeTraitExpr( 3995 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3996 } 3997 3998 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3999 /// expr and the same for @c alignof and @c __alignof 4000 /// Note that the ArgRange is invalid if isType is false. 4001 ExprResult 4002 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4003 UnaryExprOrTypeTrait ExprKind, bool IsType, 4004 void *TyOrEx, SourceRange ArgRange) { 4005 // If error parsing type, ignore. 4006 if (!TyOrEx) return ExprError(); 4007 4008 if (IsType) { 4009 TypeSourceInfo *TInfo; 4010 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4011 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4012 } 4013 4014 Expr *ArgEx = (Expr *)TyOrEx; 4015 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4016 return Result; 4017 } 4018 4019 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4020 bool IsReal) { 4021 if (V.get()->isTypeDependent()) 4022 return S.Context.DependentTy; 4023 4024 // _Real and _Imag are only l-values for normal l-values. 4025 if (V.get()->getObjectKind() != OK_Ordinary) { 4026 V = S.DefaultLvalueConversion(V.get()); 4027 if (V.isInvalid()) 4028 return QualType(); 4029 } 4030 4031 // These operators return the element type of a complex type. 4032 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4033 return CT->getElementType(); 4034 4035 // Otherwise they pass through real integer and floating point types here. 4036 if (V.get()->getType()->isArithmeticType()) 4037 return V.get()->getType(); 4038 4039 // Test for placeholders. 4040 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4041 if (PR.isInvalid()) return QualType(); 4042 if (PR.get() != V.get()) { 4043 V = PR; 4044 return CheckRealImagOperand(S, V, Loc, IsReal); 4045 } 4046 4047 // Reject anything else. 4048 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4049 << (IsReal ? "__real" : "__imag"); 4050 return QualType(); 4051 } 4052 4053 4054 4055 ExprResult 4056 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4057 tok::TokenKind Kind, Expr *Input) { 4058 UnaryOperatorKind Opc; 4059 switch (Kind) { 4060 default: llvm_unreachable("Unknown unary op!"); 4061 case tok::plusplus: Opc = UO_PostInc; break; 4062 case tok::minusminus: Opc = UO_PostDec; break; 4063 } 4064 4065 // Since this might is a postfix expression, get rid of ParenListExprs. 4066 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4067 if (Result.isInvalid()) return ExprError(); 4068 Input = Result.get(); 4069 4070 return BuildUnaryOp(S, OpLoc, Opc, Input); 4071 } 4072 4073 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4074 /// 4075 /// \return true on error 4076 static bool checkArithmeticOnObjCPointer(Sema &S, 4077 SourceLocation opLoc, 4078 Expr *op) { 4079 assert(op->getType()->isObjCObjectPointerType()); 4080 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4081 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4082 return false; 4083 4084 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4085 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4086 << op->getSourceRange(); 4087 return true; 4088 } 4089 4090 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4091 auto *BaseNoParens = Base->IgnoreParens(); 4092 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4093 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4094 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4095 } 4096 4097 ExprResult 4098 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4099 Expr *idx, SourceLocation rbLoc) { 4100 if (base && !base->getType().isNull() && 4101 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4102 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4103 /*Length=*/nullptr, rbLoc); 4104 4105 // Since this might be a postfix expression, get rid of ParenListExprs. 4106 if (isa<ParenListExpr>(base)) { 4107 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4108 if (result.isInvalid()) return ExprError(); 4109 base = result.get(); 4110 } 4111 4112 // Handle any non-overload placeholder types in the base and index 4113 // expressions. We can't handle overloads here because the other 4114 // operand might be an overloadable type, in which case the overload 4115 // resolution for the operator overload should get the first crack 4116 // at the overload. 4117 bool IsMSPropertySubscript = false; 4118 if (base->getType()->isNonOverloadPlaceholderType()) { 4119 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4120 if (!IsMSPropertySubscript) { 4121 ExprResult result = CheckPlaceholderExpr(base); 4122 if (result.isInvalid()) 4123 return ExprError(); 4124 base = result.get(); 4125 } 4126 } 4127 if (idx->getType()->isNonOverloadPlaceholderType()) { 4128 ExprResult result = CheckPlaceholderExpr(idx); 4129 if (result.isInvalid()) return ExprError(); 4130 idx = result.get(); 4131 } 4132 4133 // Build an unanalyzed expression if either operand is type-dependent. 4134 if (getLangOpts().CPlusPlus && 4135 (base->isTypeDependent() || idx->isTypeDependent())) { 4136 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4137 VK_LValue, OK_Ordinary, rbLoc); 4138 } 4139 4140 // MSDN, property (C++) 4141 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4142 // This attribute can also be used in the declaration of an empty array in a 4143 // class or structure definition. For example: 4144 // __declspec(property(get=GetX, put=PutX)) int x[]; 4145 // The above statement indicates that x[] can be used with one or more array 4146 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4147 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4148 if (IsMSPropertySubscript) { 4149 // Build MS property subscript expression if base is MS property reference 4150 // or MS property subscript. 4151 return new (Context) MSPropertySubscriptExpr( 4152 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4153 } 4154 4155 // Use C++ overloaded-operator rules if either operand has record 4156 // type. The spec says to do this if either type is *overloadable*, 4157 // but enum types can't declare subscript operators or conversion 4158 // operators, so there's nothing interesting for overload resolution 4159 // to do if there aren't any record types involved. 4160 // 4161 // ObjC pointers have their own subscripting logic that is not tied 4162 // to overload resolution and so should not take this path. 4163 if (getLangOpts().CPlusPlus && 4164 (base->getType()->isRecordType() || 4165 (!base->getType()->isObjCObjectPointerType() && 4166 idx->getType()->isRecordType()))) { 4167 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4168 } 4169 4170 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4171 } 4172 4173 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4174 Expr *LowerBound, 4175 SourceLocation ColonLoc, Expr *Length, 4176 SourceLocation RBLoc) { 4177 if (Base->getType()->isPlaceholderType() && 4178 !Base->getType()->isSpecificPlaceholderType( 4179 BuiltinType::OMPArraySection)) { 4180 ExprResult Result = CheckPlaceholderExpr(Base); 4181 if (Result.isInvalid()) 4182 return ExprError(); 4183 Base = Result.get(); 4184 } 4185 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4186 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4187 if (Result.isInvalid()) 4188 return ExprError(); 4189 Result = DefaultLvalueConversion(Result.get()); 4190 if (Result.isInvalid()) 4191 return ExprError(); 4192 LowerBound = Result.get(); 4193 } 4194 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4195 ExprResult Result = CheckPlaceholderExpr(Length); 4196 if (Result.isInvalid()) 4197 return ExprError(); 4198 Result = DefaultLvalueConversion(Result.get()); 4199 if (Result.isInvalid()) 4200 return ExprError(); 4201 Length = Result.get(); 4202 } 4203 4204 // Build an unanalyzed expression if either operand is type-dependent. 4205 if (Base->isTypeDependent() || 4206 (LowerBound && 4207 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4208 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4209 return new (Context) 4210 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4211 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4212 } 4213 4214 // Perform default conversions. 4215 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4216 QualType ResultTy; 4217 if (OriginalTy->isAnyPointerType()) { 4218 ResultTy = OriginalTy->getPointeeType(); 4219 } else if (OriginalTy->isArrayType()) { 4220 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4221 } else { 4222 return ExprError( 4223 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4224 << Base->getSourceRange()); 4225 } 4226 // C99 6.5.2.1p1 4227 if (LowerBound) { 4228 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4229 LowerBound); 4230 if (Res.isInvalid()) 4231 return ExprError(Diag(LowerBound->getExprLoc(), 4232 diag::err_omp_typecheck_section_not_integer) 4233 << 0 << LowerBound->getSourceRange()); 4234 LowerBound = Res.get(); 4235 4236 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4237 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4238 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4239 << 0 << LowerBound->getSourceRange(); 4240 } 4241 if (Length) { 4242 auto Res = 4243 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4244 if (Res.isInvalid()) 4245 return ExprError(Diag(Length->getExprLoc(), 4246 diag::err_omp_typecheck_section_not_integer) 4247 << 1 << Length->getSourceRange()); 4248 Length = Res.get(); 4249 4250 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4251 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4252 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4253 << 1 << Length->getSourceRange(); 4254 } 4255 4256 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4257 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4258 // type. Note that functions are not objects, and that (in C99 parlance) 4259 // incomplete types are not object types. 4260 if (ResultTy->isFunctionType()) { 4261 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4262 << ResultTy << Base->getSourceRange(); 4263 return ExprError(); 4264 } 4265 4266 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4267 diag::err_omp_section_incomplete_type, Base)) 4268 return ExprError(); 4269 4270 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4271 llvm::APSInt LowerBoundValue; 4272 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4273 // OpenMP 4.5, [2.4 Array Sections] 4274 // The array section must be a subset of the original array. 4275 if (LowerBoundValue.isNegative()) { 4276 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4277 << LowerBound->getSourceRange(); 4278 return ExprError(); 4279 } 4280 } 4281 } 4282 4283 if (Length) { 4284 llvm::APSInt LengthValue; 4285 if (Length->EvaluateAsInt(LengthValue, Context)) { 4286 // OpenMP 4.5, [2.4 Array Sections] 4287 // The length must evaluate to non-negative integers. 4288 if (LengthValue.isNegative()) { 4289 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4290 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4291 << Length->getSourceRange(); 4292 return ExprError(); 4293 } 4294 } 4295 } else if (ColonLoc.isValid() && 4296 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4297 !OriginalTy->isVariableArrayType()))) { 4298 // OpenMP 4.5, [2.4 Array Sections] 4299 // When the size of the array dimension is not known, the length must be 4300 // specified explicitly. 4301 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4302 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4303 return ExprError(); 4304 } 4305 4306 if (!Base->getType()->isSpecificPlaceholderType( 4307 BuiltinType::OMPArraySection)) { 4308 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4309 if (Result.isInvalid()) 4310 return ExprError(); 4311 Base = Result.get(); 4312 } 4313 return new (Context) 4314 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4315 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4316 } 4317 4318 ExprResult 4319 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4320 Expr *Idx, SourceLocation RLoc) { 4321 Expr *LHSExp = Base; 4322 Expr *RHSExp = Idx; 4323 4324 ExprValueKind VK = VK_LValue; 4325 ExprObjectKind OK = OK_Ordinary; 4326 4327 // Per C++ core issue 1213, the result is an xvalue if either operand is 4328 // a non-lvalue array, and an lvalue otherwise. 4329 if (getLangOpts().CPlusPlus11 && 4330 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4331 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4332 VK = VK_XValue; 4333 4334 // Perform default conversions. 4335 if (!LHSExp->getType()->getAs<VectorType>()) { 4336 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4337 if (Result.isInvalid()) 4338 return ExprError(); 4339 LHSExp = Result.get(); 4340 } 4341 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4342 if (Result.isInvalid()) 4343 return ExprError(); 4344 RHSExp = Result.get(); 4345 4346 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4347 4348 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4349 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4350 // in the subscript position. As a result, we need to derive the array base 4351 // and index from the expression types. 4352 Expr *BaseExpr, *IndexExpr; 4353 QualType ResultType; 4354 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4355 BaseExpr = LHSExp; 4356 IndexExpr = RHSExp; 4357 ResultType = Context.DependentTy; 4358 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4359 BaseExpr = LHSExp; 4360 IndexExpr = RHSExp; 4361 ResultType = PTy->getPointeeType(); 4362 } else if (const ObjCObjectPointerType *PTy = 4363 LHSTy->getAs<ObjCObjectPointerType>()) { 4364 BaseExpr = LHSExp; 4365 IndexExpr = RHSExp; 4366 4367 // Use custom logic if this should be the pseudo-object subscript 4368 // expression. 4369 if (!LangOpts.isSubscriptPointerArithmetic()) 4370 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4371 nullptr); 4372 4373 ResultType = PTy->getPointeeType(); 4374 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4375 // Handle the uncommon case of "123[Ptr]". 4376 BaseExpr = RHSExp; 4377 IndexExpr = LHSExp; 4378 ResultType = PTy->getPointeeType(); 4379 } else if (const ObjCObjectPointerType *PTy = 4380 RHSTy->getAs<ObjCObjectPointerType>()) { 4381 // Handle the uncommon case of "123[Ptr]". 4382 BaseExpr = RHSExp; 4383 IndexExpr = LHSExp; 4384 ResultType = PTy->getPointeeType(); 4385 if (!LangOpts.isSubscriptPointerArithmetic()) { 4386 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4387 << ResultType << BaseExpr->getSourceRange(); 4388 return ExprError(); 4389 } 4390 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4391 BaseExpr = LHSExp; // vectors: V[123] 4392 IndexExpr = RHSExp; 4393 VK = LHSExp->getValueKind(); 4394 if (VK != VK_RValue) 4395 OK = OK_VectorComponent; 4396 4397 // FIXME: need to deal with const... 4398 ResultType = VTy->getElementType(); 4399 } else if (LHSTy->isArrayType()) { 4400 // If we see an array that wasn't promoted by 4401 // DefaultFunctionArrayLvalueConversion, it must be an array that 4402 // wasn't promoted because of the C90 rule that doesn't 4403 // allow promoting non-lvalue arrays. Warn, then 4404 // force the promotion here. 4405 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4406 LHSExp->getSourceRange(); 4407 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4408 CK_ArrayToPointerDecay).get(); 4409 LHSTy = LHSExp->getType(); 4410 4411 BaseExpr = LHSExp; 4412 IndexExpr = RHSExp; 4413 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4414 } else if (RHSTy->isArrayType()) { 4415 // Same as previous, except for 123[f().a] case 4416 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4417 RHSExp->getSourceRange(); 4418 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4419 CK_ArrayToPointerDecay).get(); 4420 RHSTy = RHSExp->getType(); 4421 4422 BaseExpr = RHSExp; 4423 IndexExpr = LHSExp; 4424 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4425 } else { 4426 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4427 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4428 } 4429 // C99 6.5.2.1p1 4430 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4431 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4432 << IndexExpr->getSourceRange()); 4433 4434 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4435 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4436 && !IndexExpr->isTypeDependent()) 4437 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4438 4439 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4440 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4441 // type. Note that Functions are not objects, and that (in C99 parlance) 4442 // incomplete types are not object types. 4443 if (ResultType->isFunctionType()) { 4444 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4445 << ResultType << BaseExpr->getSourceRange(); 4446 return ExprError(); 4447 } 4448 4449 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4450 // GNU extension: subscripting on pointer to void 4451 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4452 << BaseExpr->getSourceRange(); 4453 4454 // C forbids expressions of unqualified void type from being l-values. 4455 // See IsCForbiddenLValueType. 4456 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4457 } else if (!ResultType->isDependentType() && 4458 RequireCompleteType(LLoc, ResultType, 4459 diag::err_subscript_incomplete_type, BaseExpr)) 4460 return ExprError(); 4461 4462 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4463 !ResultType.isCForbiddenLValueType()); 4464 4465 return new (Context) 4466 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4467 } 4468 4469 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4470 ParmVarDecl *Param) { 4471 if (Param->hasUnparsedDefaultArg()) { 4472 Diag(CallLoc, 4473 diag::err_use_of_default_argument_to_function_declared_later) << 4474 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4475 Diag(UnparsedDefaultArgLocs[Param], 4476 diag::note_default_argument_declared_here); 4477 return true; 4478 } 4479 4480 if (Param->hasUninstantiatedDefaultArg()) { 4481 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4482 4483 EnterExpressionEvaluationContext EvalContext( 4484 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4485 4486 // Instantiate the expression. 4487 // 4488 // FIXME: Pass in a correct Pattern argument, otherwise 4489 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4490 // 4491 // template<typename T> 4492 // struct A { 4493 // static int FooImpl(); 4494 // 4495 // template<typename Tp> 4496 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4497 // // template argument list [[T], [Tp]], should be [[Tp]]. 4498 // friend A<Tp> Foo(int a); 4499 // }; 4500 // 4501 // template<typename T> 4502 // A<T> Foo(int a = A<T>::FooImpl()); 4503 MultiLevelTemplateArgumentList MutiLevelArgList 4504 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4505 4506 InstantiatingTemplate Inst(*this, CallLoc, Param, 4507 MutiLevelArgList.getInnermost()); 4508 if (Inst.isInvalid()) 4509 return true; 4510 if (Inst.isAlreadyInstantiating()) { 4511 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4512 Param->setInvalidDecl(); 4513 return true; 4514 } 4515 4516 ExprResult Result; 4517 { 4518 // C++ [dcl.fct.default]p5: 4519 // The names in the [default argument] expression are bound, and 4520 // the semantic constraints are checked, at the point where the 4521 // default argument expression appears. 4522 ContextRAII SavedContext(*this, FD); 4523 LocalInstantiationScope Local(*this); 4524 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4525 /*DirectInit*/false); 4526 } 4527 if (Result.isInvalid()) 4528 return true; 4529 4530 // Check the expression as an initializer for the parameter. 4531 InitializedEntity Entity 4532 = InitializedEntity::InitializeParameter(Context, Param); 4533 InitializationKind Kind 4534 = InitializationKind::CreateCopy(Param->getLocation(), 4535 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4536 Expr *ResultE = Result.getAs<Expr>(); 4537 4538 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4539 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4540 if (Result.isInvalid()) 4541 return true; 4542 4543 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4544 Param->getOuterLocStart()); 4545 if (Result.isInvalid()) 4546 return true; 4547 4548 // Remember the instantiated default argument. 4549 Param->setDefaultArg(Result.getAs<Expr>()); 4550 if (ASTMutationListener *L = getASTMutationListener()) { 4551 L->DefaultArgumentInstantiated(Param); 4552 } 4553 } 4554 4555 // If the default argument expression is not set yet, we are building it now. 4556 if (!Param->hasInit()) { 4557 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4558 Param->setInvalidDecl(); 4559 return true; 4560 } 4561 4562 // If the default expression creates temporaries, we need to 4563 // push them to the current stack of expression temporaries so they'll 4564 // be properly destroyed. 4565 // FIXME: We should really be rebuilding the default argument with new 4566 // bound temporaries; see the comment in PR5810. 4567 // We don't need to do that with block decls, though, because 4568 // blocks in default argument expression can never capture anything. 4569 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4570 // Set the "needs cleanups" bit regardless of whether there are 4571 // any explicit objects. 4572 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4573 4574 // Append all the objects to the cleanup list. Right now, this 4575 // should always be a no-op, because blocks in default argument 4576 // expressions should never be able to capture anything. 4577 assert(!Init->getNumObjects() && 4578 "default argument expression has capturing blocks?"); 4579 } 4580 4581 // We already type-checked the argument, so we know it works. 4582 // Just mark all of the declarations in this potentially-evaluated expression 4583 // as being "referenced". 4584 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4585 /*SkipLocalVariables=*/true); 4586 return false; 4587 } 4588 4589 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4590 FunctionDecl *FD, ParmVarDecl *Param) { 4591 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4592 return ExprError(); 4593 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4594 } 4595 4596 Sema::VariadicCallType 4597 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4598 Expr *Fn) { 4599 if (Proto && Proto->isVariadic()) { 4600 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4601 return VariadicConstructor; 4602 else if (Fn && Fn->getType()->isBlockPointerType()) 4603 return VariadicBlock; 4604 else if (FDecl) { 4605 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4606 if (Method->isInstance()) 4607 return VariadicMethod; 4608 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4609 return VariadicMethod; 4610 return VariadicFunction; 4611 } 4612 return VariadicDoesNotApply; 4613 } 4614 4615 namespace { 4616 class FunctionCallCCC : public FunctionCallFilterCCC { 4617 public: 4618 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4619 unsigned NumArgs, MemberExpr *ME) 4620 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4621 FunctionName(FuncName) {} 4622 4623 bool ValidateCandidate(const TypoCorrection &candidate) override { 4624 if (!candidate.getCorrectionSpecifier() || 4625 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4626 return false; 4627 } 4628 4629 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4630 } 4631 4632 private: 4633 const IdentifierInfo *const FunctionName; 4634 }; 4635 } 4636 4637 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4638 FunctionDecl *FDecl, 4639 ArrayRef<Expr *> Args) { 4640 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4641 DeclarationName FuncName = FDecl->getDeclName(); 4642 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4643 4644 if (TypoCorrection Corrected = S.CorrectTypo( 4645 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4646 S.getScopeForContext(S.CurContext), nullptr, 4647 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4648 Args.size(), ME), 4649 Sema::CTK_ErrorRecovery)) { 4650 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4651 if (Corrected.isOverloaded()) { 4652 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4653 OverloadCandidateSet::iterator Best; 4654 for (NamedDecl *CD : Corrected) { 4655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4656 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4657 OCS); 4658 } 4659 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4660 case OR_Success: 4661 ND = Best->FoundDecl; 4662 Corrected.setCorrectionDecl(ND); 4663 break; 4664 default: 4665 break; 4666 } 4667 } 4668 ND = ND->getUnderlyingDecl(); 4669 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4670 return Corrected; 4671 } 4672 } 4673 return TypoCorrection(); 4674 } 4675 4676 /// ConvertArgumentsForCall - Converts the arguments specified in 4677 /// Args/NumArgs to the parameter types of the function FDecl with 4678 /// function prototype Proto. Call is the call expression itself, and 4679 /// Fn is the function expression. For a C++ member function, this 4680 /// routine does not attempt to convert the object argument. Returns 4681 /// true if the call is ill-formed. 4682 bool 4683 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4684 FunctionDecl *FDecl, 4685 const FunctionProtoType *Proto, 4686 ArrayRef<Expr *> Args, 4687 SourceLocation RParenLoc, 4688 bool IsExecConfig) { 4689 // Bail out early if calling a builtin with custom typechecking. 4690 if (FDecl) 4691 if (unsigned ID = FDecl->getBuiltinID()) 4692 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4693 return false; 4694 4695 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4696 // assignment, to the types of the corresponding parameter, ... 4697 unsigned NumParams = Proto->getNumParams(); 4698 bool Invalid = false; 4699 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4700 unsigned FnKind = Fn->getType()->isBlockPointerType() 4701 ? 1 /* block */ 4702 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4703 : 0 /* function */); 4704 4705 // If too few arguments are available (and we don't have default 4706 // arguments for the remaining parameters), don't make the call. 4707 if (Args.size() < NumParams) { 4708 if (Args.size() < MinArgs) { 4709 TypoCorrection TC; 4710 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4711 unsigned diag_id = 4712 MinArgs == NumParams && !Proto->isVariadic() 4713 ? diag::err_typecheck_call_too_few_args_suggest 4714 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4715 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4716 << static_cast<unsigned>(Args.size()) 4717 << TC.getCorrectionRange()); 4718 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4719 Diag(RParenLoc, 4720 MinArgs == NumParams && !Proto->isVariadic() 4721 ? diag::err_typecheck_call_too_few_args_one 4722 : diag::err_typecheck_call_too_few_args_at_least_one) 4723 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4724 else 4725 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4726 ? diag::err_typecheck_call_too_few_args 4727 : diag::err_typecheck_call_too_few_args_at_least) 4728 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4729 << Fn->getSourceRange(); 4730 4731 // Emit the location of the prototype. 4732 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4733 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4734 << FDecl; 4735 4736 return true; 4737 } 4738 Call->setNumArgs(Context, NumParams); 4739 } 4740 4741 // If too many are passed and not variadic, error on the extras and drop 4742 // them. 4743 if (Args.size() > NumParams) { 4744 if (!Proto->isVariadic()) { 4745 TypoCorrection TC; 4746 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4747 unsigned diag_id = 4748 MinArgs == NumParams && !Proto->isVariadic() 4749 ? diag::err_typecheck_call_too_many_args_suggest 4750 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4751 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4752 << static_cast<unsigned>(Args.size()) 4753 << TC.getCorrectionRange()); 4754 } else if (NumParams == 1 && FDecl && 4755 FDecl->getParamDecl(0)->getDeclName()) 4756 Diag(Args[NumParams]->getLocStart(), 4757 MinArgs == NumParams 4758 ? diag::err_typecheck_call_too_many_args_one 4759 : diag::err_typecheck_call_too_many_args_at_most_one) 4760 << FnKind << FDecl->getParamDecl(0) 4761 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4762 << SourceRange(Args[NumParams]->getLocStart(), 4763 Args.back()->getLocEnd()); 4764 else 4765 Diag(Args[NumParams]->getLocStart(), 4766 MinArgs == NumParams 4767 ? diag::err_typecheck_call_too_many_args 4768 : diag::err_typecheck_call_too_many_args_at_most) 4769 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4770 << Fn->getSourceRange() 4771 << SourceRange(Args[NumParams]->getLocStart(), 4772 Args.back()->getLocEnd()); 4773 4774 // Emit the location of the prototype. 4775 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4776 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4777 << FDecl; 4778 4779 // This deletes the extra arguments. 4780 Call->setNumArgs(Context, NumParams); 4781 return true; 4782 } 4783 } 4784 SmallVector<Expr *, 8> AllArgs; 4785 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4786 4787 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4788 Proto, 0, Args, AllArgs, CallType); 4789 if (Invalid) 4790 return true; 4791 unsigned TotalNumArgs = AllArgs.size(); 4792 for (unsigned i = 0; i < TotalNumArgs; ++i) 4793 Call->setArg(i, AllArgs[i]); 4794 4795 return false; 4796 } 4797 4798 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4799 const FunctionProtoType *Proto, 4800 unsigned FirstParam, ArrayRef<Expr *> Args, 4801 SmallVectorImpl<Expr *> &AllArgs, 4802 VariadicCallType CallType, bool AllowExplicit, 4803 bool IsListInitialization) { 4804 unsigned NumParams = Proto->getNumParams(); 4805 bool Invalid = false; 4806 size_t ArgIx = 0; 4807 // Continue to check argument types (even if we have too few/many args). 4808 for (unsigned i = FirstParam; i < NumParams; i++) { 4809 QualType ProtoArgType = Proto->getParamType(i); 4810 4811 Expr *Arg; 4812 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4813 if (ArgIx < Args.size()) { 4814 Arg = Args[ArgIx++]; 4815 4816 if (RequireCompleteType(Arg->getLocStart(), 4817 ProtoArgType, 4818 diag::err_call_incomplete_argument, Arg)) 4819 return true; 4820 4821 // Strip the unbridged-cast placeholder expression off, if applicable. 4822 bool CFAudited = false; 4823 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4824 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4825 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4826 Arg = stripARCUnbridgedCast(Arg); 4827 else if (getLangOpts().ObjCAutoRefCount && 4828 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4829 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4830 CFAudited = true; 4831 4832 InitializedEntity Entity = 4833 Param ? InitializedEntity::InitializeParameter(Context, Param, 4834 ProtoArgType) 4835 : InitializedEntity::InitializeParameter( 4836 Context, ProtoArgType, Proto->isParamConsumed(i)); 4837 4838 // Remember that parameter belongs to a CF audited API. 4839 if (CFAudited) 4840 Entity.setParameterCFAudited(); 4841 4842 ExprResult ArgE = PerformCopyInitialization( 4843 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4844 if (ArgE.isInvalid()) 4845 return true; 4846 4847 Arg = ArgE.getAs<Expr>(); 4848 } else { 4849 assert(Param && "can't use default arguments without a known callee"); 4850 4851 ExprResult ArgExpr = 4852 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4853 if (ArgExpr.isInvalid()) 4854 return true; 4855 4856 Arg = ArgExpr.getAs<Expr>(); 4857 } 4858 4859 // Check for array bounds violations for each argument to the call. This 4860 // check only triggers warnings when the argument isn't a more complex Expr 4861 // with its own checking, such as a BinaryOperator. 4862 CheckArrayAccess(Arg); 4863 4864 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4865 CheckStaticArrayArgument(CallLoc, Param, Arg); 4866 4867 AllArgs.push_back(Arg); 4868 } 4869 4870 // If this is a variadic call, handle args passed through "...". 4871 if (CallType != VariadicDoesNotApply) { 4872 // Assume that extern "C" functions with variadic arguments that 4873 // return __unknown_anytype aren't *really* variadic. 4874 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4875 FDecl->isExternC()) { 4876 for (Expr *A : Args.slice(ArgIx)) { 4877 QualType paramType; // ignored 4878 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4879 Invalid |= arg.isInvalid(); 4880 AllArgs.push_back(arg.get()); 4881 } 4882 4883 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4884 } else { 4885 for (Expr *A : Args.slice(ArgIx)) { 4886 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4887 Invalid |= Arg.isInvalid(); 4888 AllArgs.push_back(Arg.get()); 4889 } 4890 } 4891 4892 // Check for array bounds violations. 4893 for (Expr *A : Args.slice(ArgIx)) 4894 CheckArrayAccess(A); 4895 } 4896 return Invalid; 4897 } 4898 4899 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4900 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4901 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4902 TL = DTL.getOriginalLoc(); 4903 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4904 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4905 << ATL.getLocalSourceRange(); 4906 } 4907 4908 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4909 /// array parameter, check that it is non-null, and that if it is formed by 4910 /// array-to-pointer decay, the underlying array is sufficiently large. 4911 /// 4912 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4913 /// array type derivation, then for each call to the function, the value of the 4914 /// corresponding actual argument shall provide access to the first element of 4915 /// an array with at least as many elements as specified by the size expression. 4916 void 4917 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4918 ParmVarDecl *Param, 4919 const Expr *ArgExpr) { 4920 // Static array parameters are not supported in C++. 4921 if (!Param || getLangOpts().CPlusPlus) 4922 return; 4923 4924 QualType OrigTy = Param->getOriginalType(); 4925 4926 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4927 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4928 return; 4929 4930 if (ArgExpr->isNullPointerConstant(Context, 4931 Expr::NPC_NeverValueDependent)) { 4932 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4933 DiagnoseCalleeStaticArrayParam(*this, Param); 4934 return; 4935 } 4936 4937 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4938 if (!CAT) 4939 return; 4940 4941 const ConstantArrayType *ArgCAT = 4942 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4943 if (!ArgCAT) 4944 return; 4945 4946 if (ArgCAT->getSize().ult(CAT->getSize())) { 4947 Diag(CallLoc, diag::warn_static_array_too_small) 4948 << ArgExpr->getSourceRange() 4949 << (unsigned) ArgCAT->getSize().getZExtValue() 4950 << (unsigned) CAT->getSize().getZExtValue(); 4951 DiagnoseCalleeStaticArrayParam(*this, Param); 4952 } 4953 } 4954 4955 /// Given a function expression of unknown-any type, try to rebuild it 4956 /// to have a function type. 4957 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4958 4959 /// Is the given type a placeholder that we need to lower out 4960 /// immediately during argument processing? 4961 static bool isPlaceholderToRemoveAsArg(QualType type) { 4962 // Placeholders are never sugared. 4963 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4964 if (!placeholder) return false; 4965 4966 switch (placeholder->getKind()) { 4967 // Ignore all the non-placeholder types. 4968 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4969 case BuiltinType::Id: 4970 #include "clang/Basic/OpenCLImageTypes.def" 4971 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4972 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4973 #include "clang/AST/BuiltinTypes.def" 4974 return false; 4975 4976 // We cannot lower out overload sets; they might validly be resolved 4977 // by the call machinery. 4978 case BuiltinType::Overload: 4979 return false; 4980 4981 // Unbridged casts in ARC can be handled in some call positions and 4982 // should be left in place. 4983 case BuiltinType::ARCUnbridgedCast: 4984 return false; 4985 4986 // Pseudo-objects should be converted as soon as possible. 4987 case BuiltinType::PseudoObject: 4988 return true; 4989 4990 // The debugger mode could theoretically but currently does not try 4991 // to resolve unknown-typed arguments based on known parameter types. 4992 case BuiltinType::UnknownAny: 4993 return true; 4994 4995 // These are always invalid as call arguments and should be reported. 4996 case BuiltinType::BoundMember: 4997 case BuiltinType::BuiltinFn: 4998 case BuiltinType::OMPArraySection: 4999 return true; 5000 5001 } 5002 llvm_unreachable("bad builtin type kind"); 5003 } 5004 5005 /// Check an argument list for placeholders that we won't try to 5006 /// handle later. 5007 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5008 // Apply this processing to all the arguments at once instead of 5009 // dying at the first failure. 5010 bool hasInvalid = false; 5011 for (size_t i = 0, e = args.size(); i != e; i++) { 5012 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5013 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5014 if (result.isInvalid()) hasInvalid = true; 5015 else args[i] = result.get(); 5016 } else if (hasInvalid) { 5017 (void)S.CorrectDelayedTyposInExpr(args[i]); 5018 } 5019 } 5020 return hasInvalid; 5021 } 5022 5023 /// If a builtin function has a pointer argument with no explicit address 5024 /// space, then it should be able to accept a pointer to any address 5025 /// space as input. In order to do this, we need to replace the 5026 /// standard builtin declaration with one that uses the same address space 5027 /// as the call. 5028 /// 5029 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5030 /// it does not contain any pointer arguments without 5031 /// an address space qualifer. Otherwise the rewritten 5032 /// FunctionDecl is returned. 5033 /// TODO: Handle pointer return types. 5034 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5035 const FunctionDecl *FDecl, 5036 MultiExprArg ArgExprs) { 5037 5038 QualType DeclType = FDecl->getType(); 5039 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5040 5041 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5042 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5043 return nullptr; 5044 5045 bool NeedsNewDecl = false; 5046 unsigned i = 0; 5047 SmallVector<QualType, 8> OverloadParams; 5048 5049 for (QualType ParamType : FT->param_types()) { 5050 5051 // Convert array arguments to pointer to simplify type lookup. 5052 ExprResult ArgRes = 5053 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5054 if (ArgRes.isInvalid()) 5055 return nullptr; 5056 Expr *Arg = ArgRes.get(); 5057 QualType ArgType = Arg->getType(); 5058 if (!ParamType->isPointerType() || 5059 ParamType.getQualifiers().hasAddressSpace() || 5060 !ArgType->isPointerType() || 5061 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5062 OverloadParams.push_back(ParamType); 5063 continue; 5064 } 5065 5066 NeedsNewDecl = true; 5067 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5068 5069 QualType PointeeType = ParamType->getPointeeType(); 5070 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5071 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5072 } 5073 5074 if (!NeedsNewDecl) 5075 return nullptr; 5076 5077 FunctionProtoType::ExtProtoInfo EPI; 5078 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5079 OverloadParams, EPI); 5080 DeclContext *Parent = Context.getTranslationUnitDecl(); 5081 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5082 FDecl->getLocation(), 5083 FDecl->getLocation(), 5084 FDecl->getIdentifier(), 5085 OverloadTy, 5086 /*TInfo=*/nullptr, 5087 SC_Extern, false, 5088 /*hasPrototype=*/true); 5089 SmallVector<ParmVarDecl*, 16> Params; 5090 FT = cast<FunctionProtoType>(OverloadTy); 5091 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5092 QualType ParamType = FT->getParamType(i); 5093 ParmVarDecl *Parm = 5094 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5095 SourceLocation(), nullptr, ParamType, 5096 /*TInfo=*/nullptr, SC_None, nullptr); 5097 Parm->setScopeInfo(0, i); 5098 Params.push_back(Parm); 5099 } 5100 OverloadDecl->setParams(Params); 5101 return OverloadDecl; 5102 } 5103 5104 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5105 FunctionDecl *Callee, 5106 MultiExprArg ArgExprs) { 5107 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5108 // similar attributes) really don't like it when functions are called with an 5109 // invalid number of args. 5110 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5111 /*PartialOverloading=*/false) && 5112 !Callee->isVariadic()) 5113 return; 5114 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5115 return; 5116 5117 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5118 S.Diag(Fn->getLocStart(), 5119 isa<CXXMethodDecl>(Callee) 5120 ? diag::err_ovl_no_viable_member_function_in_call 5121 : diag::err_ovl_no_viable_function_in_call) 5122 << Callee << Callee->getSourceRange(); 5123 S.Diag(Callee->getLocation(), 5124 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5125 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5126 return; 5127 } 5128 } 5129 5130 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5131 const UnresolvedMemberExpr *const UME, Sema &S) { 5132 5133 const auto GetFunctionLevelDCIfCXXClass = 5134 [](Sema &S) -> const CXXRecordDecl * { 5135 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5136 if (!DC || !DC->getParent()) 5137 return nullptr; 5138 5139 // If the call to some member function was made from within a member 5140 // function body 'M' return return 'M's parent. 5141 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5142 return MD->getParent()->getCanonicalDecl(); 5143 // else the call was made from within a default member initializer of a 5144 // class, so return the class. 5145 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5146 return RD->getCanonicalDecl(); 5147 return nullptr; 5148 }; 5149 // If our DeclContext is neither a member function nor a class (in the 5150 // case of a lambda in a default member initializer), we can't have an 5151 // enclosing 'this'. 5152 5153 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5154 if (!CurParentClass) 5155 return false; 5156 5157 // The naming class for implicit member functions call is the class in which 5158 // name lookup starts. 5159 const CXXRecordDecl *const NamingClass = 5160 UME->getNamingClass()->getCanonicalDecl(); 5161 assert(NamingClass && "Must have naming class even for implicit access"); 5162 5163 // If the unresolved member functions were found in a 'naming class' that is 5164 // related (either the same or derived from) to the class that contains the 5165 // member function that itself contained the implicit member access. 5166 5167 return CurParentClass == NamingClass || 5168 CurParentClass->isDerivedFrom(NamingClass); 5169 } 5170 5171 static void 5172 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5173 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5174 5175 if (!UME) 5176 return; 5177 5178 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5179 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5180 // already been captured, or if this is an implicit member function call (if 5181 // it isn't, an attempt to capture 'this' should already have been made). 5182 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5183 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5184 return; 5185 5186 // Check if the naming class in which the unresolved members were found is 5187 // related (same as or is a base of) to the enclosing class. 5188 5189 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5190 return; 5191 5192 5193 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5194 // If the enclosing function is not dependent, then this lambda is 5195 // capture ready, so if we can capture this, do so. 5196 if (!EnclosingFunctionCtx->isDependentContext()) { 5197 // If the current lambda and all enclosing lambdas can capture 'this' - 5198 // then go ahead and capture 'this' (since our unresolved overload set 5199 // contains at least one non-static member function). 5200 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5201 S.CheckCXXThisCapture(CallLoc); 5202 } else if (S.CurContext->isDependentContext()) { 5203 // ... since this is an implicit member reference, that might potentially 5204 // involve a 'this' capture, mark 'this' for potential capture in 5205 // enclosing lambdas. 5206 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5207 CurLSI->addPotentialThisCapture(CallLoc); 5208 } 5209 } 5210 5211 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5212 /// This provides the location of the left/right parens and a list of comma 5213 /// locations. 5214 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5215 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5216 Expr *ExecConfig, bool IsExecConfig) { 5217 // Since this might be a postfix expression, get rid of ParenListExprs. 5218 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5219 if (Result.isInvalid()) return ExprError(); 5220 Fn = Result.get(); 5221 5222 if (checkArgsForPlaceholders(*this, ArgExprs)) 5223 return ExprError(); 5224 5225 if (getLangOpts().CPlusPlus) { 5226 // If this is a pseudo-destructor expression, build the call immediately. 5227 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5228 if (!ArgExprs.empty()) { 5229 // Pseudo-destructor calls should not have any arguments. 5230 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5231 << FixItHint::CreateRemoval( 5232 SourceRange(ArgExprs.front()->getLocStart(), 5233 ArgExprs.back()->getLocEnd())); 5234 } 5235 5236 return new (Context) 5237 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5238 } 5239 if (Fn->getType() == Context.PseudoObjectTy) { 5240 ExprResult result = CheckPlaceholderExpr(Fn); 5241 if (result.isInvalid()) return ExprError(); 5242 Fn = result.get(); 5243 } 5244 5245 // Determine whether this is a dependent call inside a C++ template, 5246 // in which case we won't do any semantic analysis now. 5247 bool Dependent = false; 5248 if (Fn->isTypeDependent()) 5249 Dependent = true; 5250 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5251 Dependent = true; 5252 5253 if (Dependent) { 5254 if (ExecConfig) { 5255 return new (Context) CUDAKernelCallExpr( 5256 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5257 Context.DependentTy, VK_RValue, RParenLoc); 5258 } else { 5259 5260 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5261 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5262 Fn->getLocStart()); 5263 5264 return new (Context) CallExpr( 5265 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5266 } 5267 } 5268 5269 // Determine whether this is a call to an object (C++ [over.call.object]). 5270 if (Fn->getType()->isRecordType()) 5271 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5272 RParenLoc); 5273 5274 if (Fn->getType() == Context.UnknownAnyTy) { 5275 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5276 if (result.isInvalid()) return ExprError(); 5277 Fn = result.get(); 5278 } 5279 5280 if (Fn->getType() == Context.BoundMemberTy) { 5281 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5282 RParenLoc); 5283 } 5284 } 5285 5286 // Check for overloaded calls. This can happen even in C due to extensions. 5287 if (Fn->getType() == Context.OverloadTy) { 5288 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5289 5290 // We aren't supposed to apply this logic if there's an '&' involved. 5291 if (!find.HasFormOfMemberPointer) { 5292 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5293 return new (Context) CallExpr( 5294 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5295 OverloadExpr *ovl = find.Expression; 5296 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5297 return BuildOverloadedCallExpr( 5298 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5299 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5300 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5301 RParenLoc); 5302 } 5303 } 5304 5305 // If we're directly calling a function, get the appropriate declaration. 5306 if (Fn->getType() == Context.UnknownAnyTy) { 5307 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5308 if (result.isInvalid()) return ExprError(); 5309 Fn = result.get(); 5310 } 5311 5312 Expr *NakedFn = Fn->IgnoreParens(); 5313 5314 bool CallingNDeclIndirectly = false; 5315 NamedDecl *NDecl = nullptr; 5316 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5317 if (UnOp->getOpcode() == UO_AddrOf) { 5318 CallingNDeclIndirectly = true; 5319 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5320 } 5321 } 5322 5323 if (isa<DeclRefExpr>(NakedFn)) { 5324 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5325 5326 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5327 if (FDecl && FDecl->getBuiltinID()) { 5328 // Rewrite the function decl for this builtin by replacing parameters 5329 // with no explicit address space with the address space of the arguments 5330 // in ArgExprs. 5331 if ((FDecl = 5332 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5333 NDecl = FDecl; 5334 Fn = DeclRefExpr::Create( 5335 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5336 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5337 } 5338 } 5339 } else if (isa<MemberExpr>(NakedFn)) 5340 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5341 5342 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5343 if (CallingNDeclIndirectly && 5344 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5345 Fn->getLocStart())) 5346 return ExprError(); 5347 5348 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5349 return ExprError(); 5350 5351 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5352 } 5353 5354 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5355 ExecConfig, IsExecConfig); 5356 } 5357 5358 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5359 /// 5360 /// __builtin_astype( value, dst type ) 5361 /// 5362 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5363 SourceLocation BuiltinLoc, 5364 SourceLocation RParenLoc) { 5365 ExprValueKind VK = VK_RValue; 5366 ExprObjectKind OK = OK_Ordinary; 5367 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5368 QualType SrcTy = E->getType(); 5369 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5370 return ExprError(Diag(BuiltinLoc, 5371 diag::err_invalid_astype_of_different_size) 5372 << DstTy 5373 << SrcTy 5374 << E->getSourceRange()); 5375 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5376 } 5377 5378 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5379 /// provided arguments. 5380 /// 5381 /// __builtin_convertvector( value, dst type ) 5382 /// 5383 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5384 SourceLocation BuiltinLoc, 5385 SourceLocation RParenLoc) { 5386 TypeSourceInfo *TInfo; 5387 GetTypeFromParser(ParsedDestTy, &TInfo); 5388 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5389 } 5390 5391 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5392 /// i.e. an expression not of \p OverloadTy. The expression should 5393 /// unary-convert to an expression of function-pointer or 5394 /// block-pointer type. 5395 /// 5396 /// \param NDecl the declaration being called, if available 5397 ExprResult 5398 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5399 SourceLocation LParenLoc, 5400 ArrayRef<Expr *> Args, 5401 SourceLocation RParenLoc, 5402 Expr *Config, bool IsExecConfig) { 5403 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5404 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5405 5406 // Functions with 'interrupt' attribute cannot be called directly. 5407 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5408 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5409 return ExprError(); 5410 } 5411 5412 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5413 // so there's some risk when calling out to non-interrupt handler functions 5414 // that the callee might not preserve them. This is easy to diagnose here, 5415 // but can be very challenging to debug. 5416 if (auto *Caller = getCurFunctionDecl()) 5417 if (Caller->hasAttr<ARMInterruptAttr>()) { 5418 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5419 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5420 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5421 } 5422 5423 // Promote the function operand. 5424 // We special-case function promotion here because we only allow promoting 5425 // builtin functions to function pointers in the callee of a call. 5426 ExprResult Result; 5427 if (BuiltinID && 5428 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5429 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5430 CK_BuiltinFnToFnPtr).get(); 5431 } else { 5432 Result = CallExprUnaryConversions(Fn); 5433 } 5434 if (Result.isInvalid()) 5435 return ExprError(); 5436 Fn = Result.get(); 5437 5438 // Make the call expr early, before semantic checks. This guarantees cleanup 5439 // of arguments and function on error. 5440 CallExpr *TheCall; 5441 if (Config) 5442 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5443 cast<CallExpr>(Config), Args, 5444 Context.BoolTy, VK_RValue, 5445 RParenLoc); 5446 else 5447 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5448 VK_RValue, RParenLoc); 5449 5450 if (!getLangOpts().CPlusPlus) { 5451 // C cannot always handle TypoExpr nodes in builtin calls and direct 5452 // function calls as their argument checking don't necessarily handle 5453 // dependent types properly, so make sure any TypoExprs have been 5454 // dealt with. 5455 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5456 if (!Result.isUsable()) return ExprError(); 5457 TheCall = dyn_cast<CallExpr>(Result.get()); 5458 if (!TheCall) return Result; 5459 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5460 } 5461 5462 // Bail out early if calling a builtin with custom typechecking. 5463 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5464 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5465 5466 retry: 5467 const FunctionType *FuncT; 5468 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5469 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5470 // have type pointer to function". 5471 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5472 if (!FuncT) 5473 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5474 << Fn->getType() << Fn->getSourceRange()); 5475 } else if (const BlockPointerType *BPT = 5476 Fn->getType()->getAs<BlockPointerType>()) { 5477 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5478 } else { 5479 // Handle calls to expressions of unknown-any type. 5480 if (Fn->getType() == Context.UnknownAnyTy) { 5481 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5482 if (rewrite.isInvalid()) return ExprError(); 5483 Fn = rewrite.get(); 5484 TheCall->setCallee(Fn); 5485 goto retry; 5486 } 5487 5488 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5489 << Fn->getType() << Fn->getSourceRange()); 5490 } 5491 5492 if (getLangOpts().CUDA) { 5493 if (Config) { 5494 // CUDA: Kernel calls must be to global functions 5495 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5496 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5497 << FDecl->getName() << Fn->getSourceRange()); 5498 5499 // CUDA: Kernel function must have 'void' return type 5500 if (!FuncT->getReturnType()->isVoidType()) 5501 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5502 << Fn->getType() << Fn->getSourceRange()); 5503 } else { 5504 // CUDA: Calls to global functions must be configured 5505 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5506 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5507 << FDecl->getName() << Fn->getSourceRange()); 5508 } 5509 } 5510 5511 // Check for a valid return type 5512 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5513 FDecl)) 5514 return ExprError(); 5515 5516 // We know the result type of the call, set it. 5517 TheCall->setType(FuncT->getCallResultType(Context)); 5518 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5519 5520 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5521 if (Proto) { 5522 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5523 IsExecConfig)) 5524 return ExprError(); 5525 } else { 5526 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5527 5528 if (FDecl) { 5529 // Check if we have too few/too many template arguments, based 5530 // on our knowledge of the function definition. 5531 const FunctionDecl *Def = nullptr; 5532 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5533 Proto = Def->getType()->getAs<FunctionProtoType>(); 5534 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5535 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5536 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5537 } 5538 5539 // If the function we're calling isn't a function prototype, but we have 5540 // a function prototype from a prior declaratiom, use that prototype. 5541 if (!FDecl->hasPrototype()) 5542 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5543 } 5544 5545 // Promote the arguments (C99 6.5.2.2p6). 5546 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5547 Expr *Arg = Args[i]; 5548 5549 if (Proto && i < Proto->getNumParams()) { 5550 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5551 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5552 ExprResult ArgE = 5553 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5554 if (ArgE.isInvalid()) 5555 return true; 5556 5557 Arg = ArgE.getAs<Expr>(); 5558 5559 } else { 5560 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5561 5562 if (ArgE.isInvalid()) 5563 return true; 5564 5565 Arg = ArgE.getAs<Expr>(); 5566 } 5567 5568 if (RequireCompleteType(Arg->getLocStart(), 5569 Arg->getType(), 5570 diag::err_call_incomplete_argument, Arg)) 5571 return ExprError(); 5572 5573 TheCall->setArg(i, Arg); 5574 } 5575 } 5576 5577 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5578 if (!Method->isStatic()) 5579 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5580 << Fn->getSourceRange()); 5581 5582 // Check for sentinels 5583 if (NDecl) 5584 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5585 5586 // Do special checking on direct calls to functions. 5587 if (FDecl) { 5588 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5589 return ExprError(); 5590 5591 if (BuiltinID) 5592 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5593 } else if (NDecl) { 5594 if (CheckPointerCall(NDecl, TheCall, Proto)) 5595 return ExprError(); 5596 } else { 5597 if (CheckOtherCall(TheCall, Proto)) 5598 return ExprError(); 5599 } 5600 5601 return MaybeBindToTemporary(TheCall); 5602 } 5603 5604 ExprResult 5605 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5606 SourceLocation RParenLoc, Expr *InitExpr) { 5607 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5608 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5609 5610 TypeSourceInfo *TInfo; 5611 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5612 if (!TInfo) 5613 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5614 5615 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5616 } 5617 5618 ExprResult 5619 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5620 SourceLocation RParenLoc, Expr *LiteralExpr) { 5621 QualType literalType = TInfo->getType(); 5622 5623 if (literalType->isArrayType()) { 5624 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5625 diag::err_illegal_decl_array_incomplete_type, 5626 SourceRange(LParenLoc, 5627 LiteralExpr->getSourceRange().getEnd()))) 5628 return ExprError(); 5629 if (literalType->isVariableArrayType()) 5630 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5631 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5632 } else if (!literalType->isDependentType() && 5633 RequireCompleteType(LParenLoc, literalType, 5634 diag::err_typecheck_decl_incomplete_type, 5635 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5636 return ExprError(); 5637 5638 InitializedEntity Entity 5639 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5640 InitializationKind Kind 5641 = InitializationKind::CreateCStyleCast(LParenLoc, 5642 SourceRange(LParenLoc, RParenLoc), 5643 /*InitList=*/true); 5644 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5645 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5646 &literalType); 5647 if (Result.isInvalid()) 5648 return ExprError(); 5649 LiteralExpr = Result.get(); 5650 5651 bool isFileScope = !CurContext->isFunctionOrMethod(); 5652 if (isFileScope && 5653 !LiteralExpr->isTypeDependent() && 5654 !LiteralExpr->isValueDependent() && 5655 !literalType->isDependentType()) { // 6.5.2.5p3 5656 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5657 return ExprError(); 5658 } 5659 5660 // In C, compound literals are l-values for some reason. 5661 // For GCC compatibility, in C++, file-scope array compound literals with 5662 // constant initializers are also l-values, and compound literals are 5663 // otherwise prvalues. 5664 // 5665 // (GCC also treats C++ list-initialized file-scope array prvalues with 5666 // constant initializers as l-values, but that's non-conforming, so we don't 5667 // follow it there.) 5668 // 5669 // FIXME: It would be better to handle the lvalue cases as materializing and 5670 // lifetime-extending a temporary object, but our materialized temporaries 5671 // representation only supports lifetime extension from a variable, not "out 5672 // of thin air". 5673 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5674 // is bound to the result of applying array-to-pointer decay to the compound 5675 // literal. 5676 // FIXME: GCC supports compound literals of reference type, which should 5677 // obviously have a value kind derived from the kind of reference involved. 5678 ExprValueKind VK = 5679 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5680 ? VK_RValue 5681 : VK_LValue; 5682 5683 return MaybeBindToTemporary( 5684 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5685 VK, LiteralExpr, isFileScope)); 5686 } 5687 5688 ExprResult 5689 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5690 SourceLocation RBraceLoc) { 5691 // Immediately handle non-overload placeholders. Overloads can be 5692 // resolved contextually, but everything else here can't. 5693 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5694 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5695 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5696 5697 // Ignore failures; dropping the entire initializer list because 5698 // of one failure would be terrible for indexing/etc. 5699 if (result.isInvalid()) continue; 5700 5701 InitArgList[I] = result.get(); 5702 } 5703 } 5704 5705 // Semantic analysis for initializers is done by ActOnDeclarator() and 5706 // CheckInitializer() - it requires knowledge of the object being intialized. 5707 5708 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5709 RBraceLoc); 5710 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5711 return E; 5712 } 5713 5714 /// Do an explicit extend of the given block pointer if we're in ARC. 5715 void Sema::maybeExtendBlockObject(ExprResult &E) { 5716 assert(E.get()->getType()->isBlockPointerType()); 5717 assert(E.get()->isRValue()); 5718 5719 // Only do this in an r-value context. 5720 if (!getLangOpts().ObjCAutoRefCount) return; 5721 5722 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5723 CK_ARCExtendBlockObject, E.get(), 5724 /*base path*/ nullptr, VK_RValue); 5725 Cleanup.setExprNeedsCleanups(true); 5726 } 5727 5728 /// Prepare a conversion of the given expression to an ObjC object 5729 /// pointer type. 5730 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5731 QualType type = E.get()->getType(); 5732 if (type->isObjCObjectPointerType()) { 5733 return CK_BitCast; 5734 } else if (type->isBlockPointerType()) { 5735 maybeExtendBlockObject(E); 5736 return CK_BlockPointerToObjCPointerCast; 5737 } else { 5738 assert(type->isPointerType()); 5739 return CK_CPointerToObjCPointerCast; 5740 } 5741 } 5742 5743 /// Prepares for a scalar cast, performing all the necessary stages 5744 /// except the final cast and returning the kind required. 5745 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5746 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5747 // Also, callers should have filtered out the invalid cases with 5748 // pointers. Everything else should be possible. 5749 5750 QualType SrcTy = Src.get()->getType(); 5751 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5752 return CK_NoOp; 5753 5754 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5755 case Type::STK_MemberPointer: 5756 llvm_unreachable("member pointer type in C"); 5757 5758 case Type::STK_CPointer: 5759 case Type::STK_BlockPointer: 5760 case Type::STK_ObjCObjectPointer: 5761 switch (DestTy->getScalarTypeKind()) { 5762 case Type::STK_CPointer: { 5763 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5764 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5765 if (SrcAS != DestAS) 5766 return CK_AddressSpaceConversion; 5767 return CK_BitCast; 5768 } 5769 case Type::STK_BlockPointer: 5770 return (SrcKind == Type::STK_BlockPointer 5771 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5772 case Type::STK_ObjCObjectPointer: 5773 if (SrcKind == Type::STK_ObjCObjectPointer) 5774 return CK_BitCast; 5775 if (SrcKind == Type::STK_CPointer) 5776 return CK_CPointerToObjCPointerCast; 5777 maybeExtendBlockObject(Src); 5778 return CK_BlockPointerToObjCPointerCast; 5779 case Type::STK_Bool: 5780 return CK_PointerToBoolean; 5781 case Type::STK_Integral: 5782 return CK_PointerToIntegral; 5783 case Type::STK_Floating: 5784 case Type::STK_FloatingComplex: 5785 case Type::STK_IntegralComplex: 5786 case Type::STK_MemberPointer: 5787 llvm_unreachable("illegal cast from pointer"); 5788 } 5789 llvm_unreachable("Should have returned before this"); 5790 5791 case Type::STK_Bool: // casting from bool is like casting from an integer 5792 case Type::STK_Integral: 5793 switch (DestTy->getScalarTypeKind()) { 5794 case Type::STK_CPointer: 5795 case Type::STK_ObjCObjectPointer: 5796 case Type::STK_BlockPointer: 5797 if (Src.get()->isNullPointerConstant(Context, 5798 Expr::NPC_ValueDependentIsNull)) 5799 return CK_NullToPointer; 5800 return CK_IntegralToPointer; 5801 case Type::STK_Bool: 5802 return CK_IntegralToBoolean; 5803 case Type::STK_Integral: 5804 return CK_IntegralCast; 5805 case Type::STK_Floating: 5806 return CK_IntegralToFloating; 5807 case Type::STK_IntegralComplex: 5808 Src = ImpCastExprToType(Src.get(), 5809 DestTy->castAs<ComplexType>()->getElementType(), 5810 CK_IntegralCast); 5811 return CK_IntegralRealToComplex; 5812 case Type::STK_FloatingComplex: 5813 Src = ImpCastExprToType(Src.get(), 5814 DestTy->castAs<ComplexType>()->getElementType(), 5815 CK_IntegralToFloating); 5816 return CK_FloatingRealToComplex; 5817 case Type::STK_MemberPointer: 5818 llvm_unreachable("member pointer type in C"); 5819 } 5820 llvm_unreachable("Should have returned before this"); 5821 5822 case Type::STK_Floating: 5823 switch (DestTy->getScalarTypeKind()) { 5824 case Type::STK_Floating: 5825 return CK_FloatingCast; 5826 case Type::STK_Bool: 5827 return CK_FloatingToBoolean; 5828 case Type::STK_Integral: 5829 return CK_FloatingToIntegral; 5830 case Type::STK_FloatingComplex: 5831 Src = ImpCastExprToType(Src.get(), 5832 DestTy->castAs<ComplexType>()->getElementType(), 5833 CK_FloatingCast); 5834 return CK_FloatingRealToComplex; 5835 case Type::STK_IntegralComplex: 5836 Src = ImpCastExprToType(Src.get(), 5837 DestTy->castAs<ComplexType>()->getElementType(), 5838 CK_FloatingToIntegral); 5839 return CK_IntegralRealToComplex; 5840 case Type::STK_CPointer: 5841 case Type::STK_ObjCObjectPointer: 5842 case Type::STK_BlockPointer: 5843 llvm_unreachable("valid float->pointer cast?"); 5844 case Type::STK_MemberPointer: 5845 llvm_unreachable("member pointer type in C"); 5846 } 5847 llvm_unreachable("Should have returned before this"); 5848 5849 case Type::STK_FloatingComplex: 5850 switch (DestTy->getScalarTypeKind()) { 5851 case Type::STK_FloatingComplex: 5852 return CK_FloatingComplexCast; 5853 case Type::STK_IntegralComplex: 5854 return CK_FloatingComplexToIntegralComplex; 5855 case Type::STK_Floating: { 5856 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5857 if (Context.hasSameType(ET, DestTy)) 5858 return CK_FloatingComplexToReal; 5859 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5860 return CK_FloatingCast; 5861 } 5862 case Type::STK_Bool: 5863 return CK_FloatingComplexToBoolean; 5864 case Type::STK_Integral: 5865 Src = ImpCastExprToType(Src.get(), 5866 SrcTy->castAs<ComplexType>()->getElementType(), 5867 CK_FloatingComplexToReal); 5868 return CK_FloatingToIntegral; 5869 case Type::STK_CPointer: 5870 case Type::STK_ObjCObjectPointer: 5871 case Type::STK_BlockPointer: 5872 llvm_unreachable("valid complex float->pointer cast?"); 5873 case Type::STK_MemberPointer: 5874 llvm_unreachable("member pointer type in C"); 5875 } 5876 llvm_unreachable("Should have returned before this"); 5877 5878 case Type::STK_IntegralComplex: 5879 switch (DestTy->getScalarTypeKind()) { 5880 case Type::STK_FloatingComplex: 5881 return CK_IntegralComplexToFloatingComplex; 5882 case Type::STK_IntegralComplex: 5883 return CK_IntegralComplexCast; 5884 case Type::STK_Integral: { 5885 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5886 if (Context.hasSameType(ET, DestTy)) 5887 return CK_IntegralComplexToReal; 5888 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5889 return CK_IntegralCast; 5890 } 5891 case Type::STK_Bool: 5892 return CK_IntegralComplexToBoolean; 5893 case Type::STK_Floating: 5894 Src = ImpCastExprToType(Src.get(), 5895 SrcTy->castAs<ComplexType>()->getElementType(), 5896 CK_IntegralComplexToReal); 5897 return CK_IntegralToFloating; 5898 case Type::STK_CPointer: 5899 case Type::STK_ObjCObjectPointer: 5900 case Type::STK_BlockPointer: 5901 llvm_unreachable("valid complex int->pointer cast?"); 5902 case Type::STK_MemberPointer: 5903 llvm_unreachable("member pointer type in C"); 5904 } 5905 llvm_unreachable("Should have returned before this"); 5906 } 5907 5908 llvm_unreachable("Unhandled scalar cast"); 5909 } 5910 5911 static bool breakDownVectorType(QualType type, uint64_t &len, 5912 QualType &eltType) { 5913 // Vectors are simple. 5914 if (const VectorType *vecType = type->getAs<VectorType>()) { 5915 len = vecType->getNumElements(); 5916 eltType = vecType->getElementType(); 5917 assert(eltType->isScalarType()); 5918 return true; 5919 } 5920 5921 // We allow lax conversion to and from non-vector types, but only if 5922 // they're real types (i.e. non-complex, non-pointer scalar types). 5923 if (!type->isRealType()) return false; 5924 5925 len = 1; 5926 eltType = type; 5927 return true; 5928 } 5929 5930 /// Are the two types lax-compatible vector types? That is, given 5931 /// that one of them is a vector, do they have equal storage sizes, 5932 /// where the storage size is the number of elements times the element 5933 /// size? 5934 /// 5935 /// This will also return false if either of the types is neither a 5936 /// vector nor a real type. 5937 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5938 assert(destTy->isVectorType() || srcTy->isVectorType()); 5939 5940 // Disallow lax conversions between scalars and ExtVectors (these 5941 // conversions are allowed for other vector types because common headers 5942 // depend on them). Most scalar OP ExtVector cases are handled by the 5943 // splat path anyway, which does what we want (convert, not bitcast). 5944 // What this rules out for ExtVectors is crazy things like char4*float. 5945 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5946 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5947 5948 uint64_t srcLen, destLen; 5949 QualType srcEltTy, destEltTy; 5950 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5951 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5952 5953 // ASTContext::getTypeSize will return the size rounded up to a 5954 // power of 2, so instead of using that, we need to use the raw 5955 // element size multiplied by the element count. 5956 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5957 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5958 5959 return (srcLen * srcEltSize == destLen * destEltSize); 5960 } 5961 5962 /// Is this a legal conversion between two types, one of which is 5963 /// known to be a vector type? 5964 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5965 assert(destTy->isVectorType() || srcTy->isVectorType()); 5966 5967 if (!Context.getLangOpts().LaxVectorConversions) 5968 return false; 5969 return areLaxCompatibleVectorTypes(srcTy, destTy); 5970 } 5971 5972 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5973 CastKind &Kind) { 5974 assert(VectorTy->isVectorType() && "Not a vector type!"); 5975 5976 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5977 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5978 return Diag(R.getBegin(), 5979 Ty->isVectorType() ? 5980 diag::err_invalid_conversion_between_vectors : 5981 diag::err_invalid_conversion_between_vector_and_integer) 5982 << VectorTy << Ty << R; 5983 } else 5984 return Diag(R.getBegin(), 5985 diag::err_invalid_conversion_between_vector_and_scalar) 5986 << VectorTy << Ty << R; 5987 5988 Kind = CK_BitCast; 5989 return false; 5990 } 5991 5992 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5993 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5994 5995 if (DestElemTy == SplattedExpr->getType()) 5996 return SplattedExpr; 5997 5998 assert(DestElemTy->isFloatingType() || 5999 DestElemTy->isIntegralOrEnumerationType()); 6000 6001 CastKind CK; 6002 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6003 // OpenCL requires that we convert `true` boolean expressions to -1, but 6004 // only when splatting vectors. 6005 if (DestElemTy->isFloatingType()) { 6006 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6007 // in two steps: boolean to signed integral, then to floating. 6008 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6009 CK_BooleanToSignedIntegral); 6010 SplattedExpr = CastExprRes.get(); 6011 CK = CK_IntegralToFloating; 6012 } else { 6013 CK = CK_BooleanToSignedIntegral; 6014 } 6015 } else { 6016 ExprResult CastExprRes = SplattedExpr; 6017 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6018 if (CastExprRes.isInvalid()) 6019 return ExprError(); 6020 SplattedExpr = CastExprRes.get(); 6021 } 6022 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6023 } 6024 6025 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6026 Expr *CastExpr, CastKind &Kind) { 6027 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6028 6029 QualType SrcTy = CastExpr->getType(); 6030 6031 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6032 // an ExtVectorType. 6033 // In OpenCL, casts between vectors of different types are not allowed. 6034 // (See OpenCL 6.2). 6035 if (SrcTy->isVectorType()) { 6036 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6037 (getLangOpts().OpenCL && 6038 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6039 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6040 << DestTy << SrcTy << R; 6041 return ExprError(); 6042 } 6043 Kind = CK_BitCast; 6044 return CastExpr; 6045 } 6046 6047 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6048 // conversion will take place first from scalar to elt type, and then 6049 // splat from elt type to vector. 6050 if (SrcTy->isPointerType()) 6051 return Diag(R.getBegin(), 6052 diag::err_invalid_conversion_between_vector_and_scalar) 6053 << DestTy << SrcTy << R; 6054 6055 Kind = CK_VectorSplat; 6056 return prepareVectorSplat(DestTy, CastExpr); 6057 } 6058 6059 ExprResult 6060 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6061 Declarator &D, ParsedType &Ty, 6062 SourceLocation RParenLoc, Expr *CastExpr) { 6063 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6064 "ActOnCastExpr(): missing type or expr"); 6065 6066 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6067 if (D.isInvalidType()) 6068 return ExprError(); 6069 6070 if (getLangOpts().CPlusPlus) { 6071 // Check that there are no default arguments (C++ only). 6072 CheckExtraCXXDefaultArguments(D); 6073 } else { 6074 // Make sure any TypoExprs have been dealt with. 6075 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6076 if (!Res.isUsable()) 6077 return ExprError(); 6078 CastExpr = Res.get(); 6079 } 6080 6081 checkUnusedDeclAttributes(D); 6082 6083 QualType castType = castTInfo->getType(); 6084 Ty = CreateParsedType(castType, castTInfo); 6085 6086 bool isVectorLiteral = false; 6087 6088 // Check for an altivec or OpenCL literal, 6089 // i.e. all the elements are integer constants. 6090 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6091 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6092 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6093 && castType->isVectorType() && (PE || PLE)) { 6094 if (PLE && PLE->getNumExprs() == 0) { 6095 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6096 return ExprError(); 6097 } 6098 if (PE || PLE->getNumExprs() == 1) { 6099 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6100 if (!E->getType()->isVectorType()) 6101 isVectorLiteral = true; 6102 } 6103 else 6104 isVectorLiteral = true; 6105 } 6106 6107 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6108 // then handle it as such. 6109 if (isVectorLiteral) 6110 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6111 6112 // If the Expr being casted is a ParenListExpr, handle it specially. 6113 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6114 // sequence of BinOp comma operators. 6115 if (isa<ParenListExpr>(CastExpr)) { 6116 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6117 if (Result.isInvalid()) return ExprError(); 6118 CastExpr = Result.get(); 6119 } 6120 6121 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6122 !getSourceManager().isInSystemMacro(LParenLoc)) 6123 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6124 6125 CheckTollFreeBridgeCast(castType, CastExpr); 6126 6127 CheckObjCBridgeRelatedCast(castType, CastExpr); 6128 6129 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6130 6131 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6132 } 6133 6134 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6135 SourceLocation RParenLoc, Expr *E, 6136 TypeSourceInfo *TInfo) { 6137 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6138 "Expected paren or paren list expression"); 6139 6140 Expr **exprs; 6141 unsigned numExprs; 6142 Expr *subExpr; 6143 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6144 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6145 LiteralLParenLoc = PE->getLParenLoc(); 6146 LiteralRParenLoc = PE->getRParenLoc(); 6147 exprs = PE->getExprs(); 6148 numExprs = PE->getNumExprs(); 6149 } else { // isa<ParenExpr> by assertion at function entrance 6150 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6151 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6152 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6153 exprs = &subExpr; 6154 numExprs = 1; 6155 } 6156 6157 QualType Ty = TInfo->getType(); 6158 assert(Ty->isVectorType() && "Expected vector type"); 6159 6160 SmallVector<Expr *, 8> initExprs; 6161 const VectorType *VTy = Ty->getAs<VectorType>(); 6162 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6163 6164 // '(...)' form of vector initialization in AltiVec: the number of 6165 // initializers must be one or must match the size of the vector. 6166 // If a single value is specified in the initializer then it will be 6167 // replicated to all the components of the vector 6168 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6169 // The number of initializers must be one or must match the size of the 6170 // vector. If a single value is specified in the initializer then it will 6171 // be replicated to all the components of the vector 6172 if (numExprs == 1) { 6173 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6174 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6175 if (Literal.isInvalid()) 6176 return ExprError(); 6177 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6178 PrepareScalarCast(Literal, ElemTy)); 6179 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6180 } 6181 else if (numExprs < numElems) { 6182 Diag(E->getExprLoc(), 6183 diag::err_incorrect_number_of_vector_initializers); 6184 return ExprError(); 6185 } 6186 else 6187 initExprs.append(exprs, exprs + numExprs); 6188 } 6189 else { 6190 // For OpenCL, when the number of initializers is a single value, 6191 // it will be replicated to all components of the vector. 6192 if (getLangOpts().OpenCL && 6193 VTy->getVectorKind() == VectorType::GenericVector && 6194 numExprs == 1) { 6195 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6196 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6197 if (Literal.isInvalid()) 6198 return ExprError(); 6199 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6200 PrepareScalarCast(Literal, ElemTy)); 6201 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6202 } 6203 6204 initExprs.append(exprs, exprs + numExprs); 6205 } 6206 // FIXME: This means that pretty-printing the final AST will produce curly 6207 // braces instead of the original commas. 6208 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6209 initExprs, LiteralRParenLoc); 6210 initE->setType(Ty); 6211 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6212 } 6213 6214 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6215 /// the ParenListExpr into a sequence of comma binary operators. 6216 ExprResult 6217 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6218 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6219 if (!E) 6220 return OrigExpr; 6221 6222 ExprResult Result(E->getExpr(0)); 6223 6224 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6225 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6226 E->getExpr(i)); 6227 6228 if (Result.isInvalid()) return ExprError(); 6229 6230 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6231 } 6232 6233 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6234 SourceLocation R, 6235 MultiExprArg Val) { 6236 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6237 return expr; 6238 } 6239 6240 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6241 /// constant and the other is not a pointer. Returns true if a diagnostic is 6242 /// emitted. 6243 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6244 SourceLocation QuestionLoc) { 6245 Expr *NullExpr = LHSExpr; 6246 Expr *NonPointerExpr = RHSExpr; 6247 Expr::NullPointerConstantKind NullKind = 6248 NullExpr->isNullPointerConstant(Context, 6249 Expr::NPC_ValueDependentIsNotNull); 6250 6251 if (NullKind == Expr::NPCK_NotNull) { 6252 NullExpr = RHSExpr; 6253 NonPointerExpr = LHSExpr; 6254 NullKind = 6255 NullExpr->isNullPointerConstant(Context, 6256 Expr::NPC_ValueDependentIsNotNull); 6257 } 6258 6259 if (NullKind == Expr::NPCK_NotNull) 6260 return false; 6261 6262 if (NullKind == Expr::NPCK_ZeroExpression) 6263 return false; 6264 6265 if (NullKind == Expr::NPCK_ZeroLiteral) { 6266 // In this case, check to make sure that we got here from a "NULL" 6267 // string in the source code. 6268 NullExpr = NullExpr->IgnoreParenImpCasts(); 6269 SourceLocation loc = NullExpr->getExprLoc(); 6270 if (!findMacroSpelling(loc, "NULL")) 6271 return false; 6272 } 6273 6274 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6275 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6276 << NonPointerExpr->getType() << DiagType 6277 << NonPointerExpr->getSourceRange(); 6278 return true; 6279 } 6280 6281 /// \brief Return false if the condition expression is valid, true otherwise. 6282 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6283 QualType CondTy = Cond->getType(); 6284 6285 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6286 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6287 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6288 << CondTy << Cond->getSourceRange(); 6289 return true; 6290 } 6291 6292 // C99 6.5.15p2 6293 if (CondTy->isScalarType()) return false; 6294 6295 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6296 << CondTy << Cond->getSourceRange(); 6297 return true; 6298 } 6299 6300 /// \brief Handle when one or both operands are void type. 6301 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6302 ExprResult &RHS) { 6303 Expr *LHSExpr = LHS.get(); 6304 Expr *RHSExpr = RHS.get(); 6305 6306 if (!LHSExpr->getType()->isVoidType()) 6307 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6308 << RHSExpr->getSourceRange(); 6309 if (!RHSExpr->getType()->isVoidType()) 6310 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6311 << LHSExpr->getSourceRange(); 6312 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6313 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6314 return S.Context.VoidTy; 6315 } 6316 6317 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6318 /// true otherwise. 6319 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6320 QualType PointerTy) { 6321 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6322 !NullExpr.get()->isNullPointerConstant(S.Context, 6323 Expr::NPC_ValueDependentIsNull)) 6324 return true; 6325 6326 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6327 return false; 6328 } 6329 6330 /// \brief Checks compatibility between two pointers and return the resulting 6331 /// type. 6332 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6333 ExprResult &RHS, 6334 SourceLocation Loc) { 6335 QualType LHSTy = LHS.get()->getType(); 6336 QualType RHSTy = RHS.get()->getType(); 6337 6338 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6339 // Two identical pointers types are always compatible. 6340 return LHSTy; 6341 } 6342 6343 QualType lhptee, rhptee; 6344 6345 // Get the pointee types. 6346 bool IsBlockPointer = false; 6347 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6348 lhptee = LHSBTy->getPointeeType(); 6349 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6350 IsBlockPointer = true; 6351 } else { 6352 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6353 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6354 } 6355 6356 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6357 // differently qualified versions of compatible types, the result type is 6358 // a pointer to an appropriately qualified version of the composite 6359 // type. 6360 6361 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6362 // clause doesn't make sense for our extensions. E.g. address space 2 should 6363 // be incompatible with address space 3: they may live on different devices or 6364 // anything. 6365 Qualifiers lhQual = lhptee.getQualifiers(); 6366 Qualifiers rhQual = rhptee.getQualifiers(); 6367 6368 unsigned ResultAddrSpace = 0; 6369 unsigned LAddrSpace = lhQual.getAddressSpace(); 6370 unsigned RAddrSpace = rhQual.getAddressSpace(); 6371 if (S.getLangOpts().OpenCL) { 6372 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6373 // spaces is disallowed. 6374 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6375 ResultAddrSpace = LAddrSpace; 6376 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6377 ResultAddrSpace = RAddrSpace; 6378 else { 6379 S.Diag(Loc, 6380 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6381 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6382 << RHS.get()->getSourceRange(); 6383 return QualType(); 6384 } 6385 } 6386 6387 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6388 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6389 lhQual.removeCVRQualifiers(); 6390 rhQual.removeCVRQualifiers(); 6391 6392 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6393 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6394 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6395 // qual types are compatible iff 6396 // * corresponded types are compatible 6397 // * CVR qualifiers are equal 6398 // * address spaces are equal 6399 // Thus for conditional operator we merge CVR and address space unqualified 6400 // pointees and if there is a composite type we return a pointer to it with 6401 // merged qualifiers. 6402 if (S.getLangOpts().OpenCL) { 6403 LHSCastKind = LAddrSpace == ResultAddrSpace 6404 ? CK_BitCast 6405 : CK_AddressSpaceConversion; 6406 RHSCastKind = RAddrSpace == ResultAddrSpace 6407 ? CK_BitCast 6408 : CK_AddressSpaceConversion; 6409 lhQual.removeAddressSpace(); 6410 rhQual.removeAddressSpace(); 6411 } 6412 6413 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6414 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6415 6416 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6417 6418 if (CompositeTy.isNull()) { 6419 // In this situation, we assume void* type. No especially good 6420 // reason, but this is what gcc does, and we do have to pick 6421 // to get a consistent AST. 6422 QualType incompatTy; 6423 incompatTy = S.Context.getPointerType( 6424 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6425 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6426 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6427 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6428 // for casts between types with incompatible address space qualifiers. 6429 // For the following code the compiler produces casts between global and 6430 // local address spaces of the corresponded innermost pointees: 6431 // local int *global *a; 6432 // global int *global *b; 6433 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6434 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6435 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6436 << RHS.get()->getSourceRange(); 6437 return incompatTy; 6438 } 6439 6440 // The pointer types are compatible. 6441 // In case of OpenCL ResultTy should have the address space qualifier 6442 // which is a superset of address spaces of both the 2nd and the 3rd 6443 // operands of the conditional operator. 6444 QualType ResultTy = [&, ResultAddrSpace]() { 6445 if (S.getLangOpts().OpenCL) { 6446 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6447 CompositeQuals.setAddressSpace(ResultAddrSpace); 6448 return S.Context 6449 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6450 .withCVRQualifiers(MergedCVRQual); 6451 } 6452 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6453 }(); 6454 if (IsBlockPointer) 6455 ResultTy = S.Context.getBlockPointerType(ResultTy); 6456 else 6457 ResultTy = S.Context.getPointerType(ResultTy); 6458 6459 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6460 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6461 return ResultTy; 6462 } 6463 6464 /// \brief Return the resulting type when the operands are both block pointers. 6465 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6466 ExprResult &LHS, 6467 ExprResult &RHS, 6468 SourceLocation Loc) { 6469 QualType LHSTy = LHS.get()->getType(); 6470 QualType RHSTy = RHS.get()->getType(); 6471 6472 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6473 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6474 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6475 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6476 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6477 return destType; 6478 } 6479 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6480 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6481 << RHS.get()->getSourceRange(); 6482 return QualType(); 6483 } 6484 6485 // We have 2 block pointer types. 6486 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6487 } 6488 6489 /// \brief Return the resulting type when the operands are both pointers. 6490 static QualType 6491 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6492 ExprResult &RHS, 6493 SourceLocation Loc) { 6494 // get the pointer types 6495 QualType LHSTy = LHS.get()->getType(); 6496 QualType RHSTy = RHS.get()->getType(); 6497 6498 // get the "pointed to" types 6499 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6500 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6501 6502 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6503 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6504 // Figure out necessary qualifiers (C99 6.5.15p6) 6505 QualType destPointee 6506 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6507 QualType destType = S.Context.getPointerType(destPointee); 6508 // Add qualifiers if necessary. 6509 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6510 // Promote to void*. 6511 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6512 return destType; 6513 } 6514 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6515 QualType destPointee 6516 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6517 QualType destType = S.Context.getPointerType(destPointee); 6518 // Add qualifiers if necessary. 6519 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6520 // Promote to void*. 6521 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6522 return destType; 6523 } 6524 6525 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6526 } 6527 6528 /// \brief Return false if the first expression is not an integer and the second 6529 /// expression is not a pointer, true otherwise. 6530 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6531 Expr* PointerExpr, SourceLocation Loc, 6532 bool IsIntFirstExpr) { 6533 if (!PointerExpr->getType()->isPointerType() || 6534 !Int.get()->getType()->isIntegerType()) 6535 return false; 6536 6537 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6538 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6539 6540 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6541 << Expr1->getType() << Expr2->getType() 6542 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6543 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6544 CK_IntegralToPointer); 6545 return true; 6546 } 6547 6548 /// \brief Simple conversion between integer and floating point types. 6549 /// 6550 /// Used when handling the OpenCL conditional operator where the 6551 /// condition is a vector while the other operands are scalar. 6552 /// 6553 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6554 /// types are either integer or floating type. Between the two 6555 /// operands, the type with the higher rank is defined as the "result 6556 /// type". The other operand needs to be promoted to the same type. No 6557 /// other type promotion is allowed. We cannot use 6558 /// UsualArithmeticConversions() for this purpose, since it always 6559 /// promotes promotable types. 6560 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6561 ExprResult &RHS, 6562 SourceLocation QuestionLoc) { 6563 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6564 if (LHS.isInvalid()) 6565 return QualType(); 6566 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6567 if (RHS.isInvalid()) 6568 return QualType(); 6569 6570 // For conversion purposes, we ignore any qualifiers. 6571 // For example, "const float" and "float" are equivalent. 6572 QualType LHSType = 6573 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6574 QualType RHSType = 6575 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6576 6577 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6578 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6579 << LHSType << LHS.get()->getSourceRange(); 6580 return QualType(); 6581 } 6582 6583 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6584 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6585 << RHSType << RHS.get()->getSourceRange(); 6586 return QualType(); 6587 } 6588 6589 // If both types are identical, no conversion is needed. 6590 if (LHSType == RHSType) 6591 return LHSType; 6592 6593 // Now handle "real" floating types (i.e. float, double, long double). 6594 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6595 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6596 /*IsCompAssign = */ false); 6597 6598 // Finally, we have two differing integer types. 6599 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6600 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6601 } 6602 6603 /// \brief Convert scalar operands to a vector that matches the 6604 /// condition in length. 6605 /// 6606 /// Used when handling the OpenCL conditional operator where the 6607 /// condition is a vector while the other operands are scalar. 6608 /// 6609 /// We first compute the "result type" for the scalar operands 6610 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6611 /// into a vector of that type where the length matches the condition 6612 /// vector type. s6.11.6 requires that the element types of the result 6613 /// and the condition must have the same number of bits. 6614 static QualType 6615 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6616 QualType CondTy, SourceLocation QuestionLoc) { 6617 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6618 if (ResTy.isNull()) return QualType(); 6619 6620 const VectorType *CV = CondTy->getAs<VectorType>(); 6621 assert(CV); 6622 6623 // Determine the vector result type 6624 unsigned NumElements = CV->getNumElements(); 6625 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6626 6627 // Ensure that all types have the same number of bits 6628 if (S.Context.getTypeSize(CV->getElementType()) 6629 != S.Context.getTypeSize(ResTy)) { 6630 // Since VectorTy is created internally, it does not pretty print 6631 // with an OpenCL name. Instead, we just print a description. 6632 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6633 SmallString<64> Str; 6634 llvm::raw_svector_ostream OS(Str); 6635 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6636 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6637 << CondTy << OS.str(); 6638 return QualType(); 6639 } 6640 6641 // Convert operands to the vector result type 6642 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6643 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6644 6645 return VectorTy; 6646 } 6647 6648 /// \brief Return false if this is a valid OpenCL condition vector 6649 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6650 SourceLocation QuestionLoc) { 6651 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6652 // integral type. 6653 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6654 assert(CondTy); 6655 QualType EleTy = CondTy->getElementType(); 6656 if (EleTy->isIntegerType()) return false; 6657 6658 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6659 << Cond->getType() << Cond->getSourceRange(); 6660 return true; 6661 } 6662 6663 /// \brief Return false if the vector condition type and the vector 6664 /// result type are compatible. 6665 /// 6666 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6667 /// number of elements, and their element types have the same number 6668 /// of bits. 6669 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6670 SourceLocation QuestionLoc) { 6671 const VectorType *CV = CondTy->getAs<VectorType>(); 6672 const VectorType *RV = VecResTy->getAs<VectorType>(); 6673 assert(CV && RV); 6674 6675 if (CV->getNumElements() != RV->getNumElements()) { 6676 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6677 << CondTy << VecResTy; 6678 return true; 6679 } 6680 6681 QualType CVE = CV->getElementType(); 6682 QualType RVE = RV->getElementType(); 6683 6684 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6685 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6686 << CondTy << VecResTy; 6687 return true; 6688 } 6689 6690 return false; 6691 } 6692 6693 /// \brief Return the resulting type for the conditional operator in 6694 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6695 /// s6.3.i) when the condition is a vector type. 6696 static QualType 6697 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6698 ExprResult &LHS, ExprResult &RHS, 6699 SourceLocation QuestionLoc) { 6700 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6701 if (Cond.isInvalid()) 6702 return QualType(); 6703 QualType CondTy = Cond.get()->getType(); 6704 6705 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6706 return QualType(); 6707 6708 // If either operand is a vector then find the vector type of the 6709 // result as specified in OpenCL v1.1 s6.3.i. 6710 if (LHS.get()->getType()->isVectorType() || 6711 RHS.get()->getType()->isVectorType()) { 6712 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6713 /*isCompAssign*/false, 6714 /*AllowBothBool*/true, 6715 /*AllowBoolConversions*/false); 6716 if (VecResTy.isNull()) return QualType(); 6717 // The result type must match the condition type as specified in 6718 // OpenCL v1.1 s6.11.6. 6719 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6720 return QualType(); 6721 return VecResTy; 6722 } 6723 6724 // Both operands are scalar. 6725 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6726 } 6727 6728 /// \brief Return true if the Expr is block type 6729 static bool checkBlockType(Sema &S, const Expr *E) { 6730 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6731 QualType Ty = CE->getCallee()->getType(); 6732 if (Ty->isBlockPointerType()) { 6733 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6734 return true; 6735 } 6736 } 6737 return false; 6738 } 6739 6740 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6741 /// In that case, LHS = cond. 6742 /// C99 6.5.15 6743 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6744 ExprResult &RHS, ExprValueKind &VK, 6745 ExprObjectKind &OK, 6746 SourceLocation QuestionLoc) { 6747 6748 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6749 if (!LHSResult.isUsable()) return QualType(); 6750 LHS = LHSResult; 6751 6752 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6753 if (!RHSResult.isUsable()) return QualType(); 6754 RHS = RHSResult; 6755 6756 // C++ is sufficiently different to merit its own checker. 6757 if (getLangOpts().CPlusPlus) 6758 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6759 6760 VK = VK_RValue; 6761 OK = OK_Ordinary; 6762 6763 // The OpenCL operator with a vector condition is sufficiently 6764 // different to merit its own checker. 6765 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6766 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6767 6768 // First, check the condition. 6769 Cond = UsualUnaryConversions(Cond.get()); 6770 if (Cond.isInvalid()) 6771 return QualType(); 6772 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6773 return QualType(); 6774 6775 // Now check the two expressions. 6776 if (LHS.get()->getType()->isVectorType() || 6777 RHS.get()->getType()->isVectorType()) 6778 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6779 /*AllowBothBool*/true, 6780 /*AllowBoolConversions*/false); 6781 6782 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6783 if (LHS.isInvalid() || RHS.isInvalid()) 6784 return QualType(); 6785 6786 QualType LHSTy = LHS.get()->getType(); 6787 QualType RHSTy = RHS.get()->getType(); 6788 6789 // Diagnose attempts to convert between __float128 and long double where 6790 // such conversions currently can't be handled. 6791 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6792 Diag(QuestionLoc, 6793 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6794 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6795 return QualType(); 6796 } 6797 6798 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6799 // selection operator (?:). 6800 if (getLangOpts().OpenCL && 6801 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6802 return QualType(); 6803 } 6804 6805 // If both operands have arithmetic type, do the usual arithmetic conversions 6806 // to find a common type: C99 6.5.15p3,5. 6807 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6808 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6809 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6810 6811 return ResTy; 6812 } 6813 6814 // If both operands are the same structure or union type, the result is that 6815 // type. 6816 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6817 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6818 if (LHSRT->getDecl() == RHSRT->getDecl()) 6819 // "If both the operands have structure or union type, the result has 6820 // that type." This implies that CV qualifiers are dropped. 6821 return LHSTy.getUnqualifiedType(); 6822 // FIXME: Type of conditional expression must be complete in C mode. 6823 } 6824 6825 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6826 // The following || allows only one side to be void (a GCC-ism). 6827 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6828 return checkConditionalVoidType(*this, LHS, RHS); 6829 } 6830 6831 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6832 // the type of the other operand." 6833 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6834 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6835 6836 // All objective-c pointer type analysis is done here. 6837 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6838 QuestionLoc); 6839 if (LHS.isInvalid() || RHS.isInvalid()) 6840 return QualType(); 6841 if (!compositeType.isNull()) 6842 return compositeType; 6843 6844 6845 // Handle block pointer types. 6846 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6847 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6848 QuestionLoc); 6849 6850 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6851 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6852 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6853 QuestionLoc); 6854 6855 // GCC compatibility: soften pointer/integer mismatch. Note that 6856 // null pointers have been filtered out by this point. 6857 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6858 /*isIntFirstExpr=*/true)) 6859 return RHSTy; 6860 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6861 /*isIntFirstExpr=*/false)) 6862 return LHSTy; 6863 6864 // Emit a better diagnostic if one of the expressions is a null pointer 6865 // constant and the other is not a pointer type. In this case, the user most 6866 // likely forgot to take the address of the other expression. 6867 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6868 return QualType(); 6869 6870 // Otherwise, the operands are not compatible. 6871 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6872 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6873 << RHS.get()->getSourceRange(); 6874 return QualType(); 6875 } 6876 6877 /// FindCompositeObjCPointerType - Helper method to find composite type of 6878 /// two objective-c pointer types of the two input expressions. 6879 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6880 SourceLocation QuestionLoc) { 6881 QualType LHSTy = LHS.get()->getType(); 6882 QualType RHSTy = RHS.get()->getType(); 6883 6884 // Handle things like Class and struct objc_class*. Here we case the result 6885 // to the pseudo-builtin, because that will be implicitly cast back to the 6886 // redefinition type if an attempt is made to access its fields. 6887 if (LHSTy->isObjCClassType() && 6888 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6889 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6890 return LHSTy; 6891 } 6892 if (RHSTy->isObjCClassType() && 6893 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6894 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6895 return RHSTy; 6896 } 6897 // And the same for struct objc_object* / id 6898 if (LHSTy->isObjCIdType() && 6899 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6900 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6901 return LHSTy; 6902 } 6903 if (RHSTy->isObjCIdType() && 6904 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6905 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6906 return RHSTy; 6907 } 6908 // And the same for struct objc_selector* / SEL 6909 if (Context.isObjCSelType(LHSTy) && 6910 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6911 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6912 return LHSTy; 6913 } 6914 if (Context.isObjCSelType(RHSTy) && 6915 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6916 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6917 return RHSTy; 6918 } 6919 // Check constraints for Objective-C object pointers types. 6920 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6921 6922 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6923 // Two identical object pointer types are always compatible. 6924 return LHSTy; 6925 } 6926 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6927 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6928 QualType compositeType = LHSTy; 6929 6930 // If both operands are interfaces and either operand can be 6931 // assigned to the other, use that type as the composite 6932 // type. This allows 6933 // xxx ? (A*) a : (B*) b 6934 // where B is a subclass of A. 6935 // 6936 // Additionally, as for assignment, if either type is 'id' 6937 // allow silent coercion. Finally, if the types are 6938 // incompatible then make sure to use 'id' as the composite 6939 // type so the result is acceptable for sending messages to. 6940 6941 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6942 // It could return the composite type. 6943 if (!(compositeType = 6944 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6945 // Nothing more to do. 6946 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6947 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6948 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6949 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6950 } else if ((LHSTy->isObjCQualifiedIdType() || 6951 RHSTy->isObjCQualifiedIdType()) && 6952 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6953 // Need to handle "id<xx>" explicitly. 6954 // GCC allows qualified id and any Objective-C type to devolve to 6955 // id. Currently localizing to here until clear this should be 6956 // part of ObjCQualifiedIdTypesAreCompatible. 6957 compositeType = Context.getObjCIdType(); 6958 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6959 compositeType = Context.getObjCIdType(); 6960 } else { 6961 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6962 << LHSTy << RHSTy 6963 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6964 QualType incompatTy = Context.getObjCIdType(); 6965 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6966 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6967 return incompatTy; 6968 } 6969 // The object pointer types are compatible. 6970 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6971 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6972 return compositeType; 6973 } 6974 // Check Objective-C object pointer types and 'void *' 6975 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6976 if (getLangOpts().ObjCAutoRefCount) { 6977 // ARC forbids the implicit conversion of object pointers to 'void *', 6978 // so these types are not compatible. 6979 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6980 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6981 LHS = RHS = true; 6982 return QualType(); 6983 } 6984 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6985 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6986 QualType destPointee 6987 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6988 QualType destType = Context.getPointerType(destPointee); 6989 // Add qualifiers if necessary. 6990 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6991 // Promote to void*. 6992 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6993 return destType; 6994 } 6995 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6996 if (getLangOpts().ObjCAutoRefCount) { 6997 // ARC forbids the implicit conversion of object pointers to 'void *', 6998 // so these types are not compatible. 6999 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7000 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7001 LHS = RHS = true; 7002 return QualType(); 7003 } 7004 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7005 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7006 QualType destPointee 7007 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7008 QualType destType = Context.getPointerType(destPointee); 7009 // Add qualifiers if necessary. 7010 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7011 // Promote to void*. 7012 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7013 return destType; 7014 } 7015 return QualType(); 7016 } 7017 7018 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7019 /// ParenRange in parentheses. 7020 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7021 const PartialDiagnostic &Note, 7022 SourceRange ParenRange) { 7023 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7024 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7025 EndLoc.isValid()) { 7026 Self.Diag(Loc, Note) 7027 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7028 << FixItHint::CreateInsertion(EndLoc, ")"); 7029 } else { 7030 // We can't display the parentheses, so just show the bare note. 7031 Self.Diag(Loc, Note) << ParenRange; 7032 } 7033 } 7034 7035 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7036 return BinaryOperator::isAdditiveOp(Opc) || 7037 BinaryOperator::isMultiplicativeOp(Opc) || 7038 BinaryOperator::isShiftOp(Opc); 7039 } 7040 7041 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7042 /// expression, either using a built-in or overloaded operator, 7043 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7044 /// expression. 7045 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7046 Expr **RHSExprs) { 7047 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7048 E = E->IgnoreImpCasts(); 7049 E = E->IgnoreConversionOperator(); 7050 E = E->IgnoreImpCasts(); 7051 7052 // Built-in binary operator. 7053 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7054 if (IsArithmeticOp(OP->getOpcode())) { 7055 *Opcode = OP->getOpcode(); 7056 *RHSExprs = OP->getRHS(); 7057 return true; 7058 } 7059 } 7060 7061 // Overloaded operator. 7062 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7063 if (Call->getNumArgs() != 2) 7064 return false; 7065 7066 // Make sure this is really a binary operator that is safe to pass into 7067 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7068 OverloadedOperatorKind OO = Call->getOperator(); 7069 if (OO < OO_Plus || OO > OO_Arrow || 7070 OO == OO_PlusPlus || OO == OO_MinusMinus) 7071 return false; 7072 7073 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7074 if (IsArithmeticOp(OpKind)) { 7075 *Opcode = OpKind; 7076 *RHSExprs = Call->getArg(1); 7077 return true; 7078 } 7079 } 7080 7081 return false; 7082 } 7083 7084 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7085 /// or is a logical expression such as (x==y) which has int type, but is 7086 /// commonly interpreted as boolean. 7087 static bool ExprLooksBoolean(Expr *E) { 7088 E = E->IgnoreParenImpCasts(); 7089 7090 if (E->getType()->isBooleanType()) 7091 return true; 7092 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7093 return OP->isComparisonOp() || OP->isLogicalOp(); 7094 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7095 return OP->getOpcode() == UO_LNot; 7096 if (E->getType()->isPointerType()) 7097 return true; 7098 7099 return false; 7100 } 7101 7102 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7103 /// and binary operator are mixed in a way that suggests the programmer assumed 7104 /// the conditional operator has higher precedence, for example: 7105 /// "int x = a + someBinaryCondition ? 1 : 2". 7106 static void DiagnoseConditionalPrecedence(Sema &Self, 7107 SourceLocation OpLoc, 7108 Expr *Condition, 7109 Expr *LHSExpr, 7110 Expr *RHSExpr) { 7111 BinaryOperatorKind CondOpcode; 7112 Expr *CondRHS; 7113 7114 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7115 return; 7116 if (!ExprLooksBoolean(CondRHS)) 7117 return; 7118 7119 // The condition is an arithmetic binary expression, with a right- 7120 // hand side that looks boolean, so warn. 7121 7122 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7123 << Condition->getSourceRange() 7124 << BinaryOperator::getOpcodeStr(CondOpcode); 7125 7126 SuggestParentheses(Self, OpLoc, 7127 Self.PDiag(diag::note_precedence_silence) 7128 << BinaryOperator::getOpcodeStr(CondOpcode), 7129 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7130 7131 SuggestParentheses(Self, OpLoc, 7132 Self.PDiag(diag::note_precedence_conditional_first), 7133 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7134 } 7135 7136 /// Compute the nullability of a conditional expression. 7137 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7138 QualType LHSTy, QualType RHSTy, 7139 ASTContext &Ctx) { 7140 if (!ResTy->isAnyPointerType()) 7141 return ResTy; 7142 7143 auto GetNullability = [&Ctx](QualType Ty) { 7144 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7145 if (Kind) 7146 return *Kind; 7147 return NullabilityKind::Unspecified; 7148 }; 7149 7150 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7151 NullabilityKind MergedKind; 7152 7153 // Compute nullability of a binary conditional expression. 7154 if (IsBin) { 7155 if (LHSKind == NullabilityKind::NonNull) 7156 MergedKind = NullabilityKind::NonNull; 7157 else 7158 MergedKind = RHSKind; 7159 // Compute nullability of a normal conditional expression. 7160 } else { 7161 if (LHSKind == NullabilityKind::Nullable || 7162 RHSKind == NullabilityKind::Nullable) 7163 MergedKind = NullabilityKind::Nullable; 7164 else if (LHSKind == NullabilityKind::NonNull) 7165 MergedKind = RHSKind; 7166 else if (RHSKind == NullabilityKind::NonNull) 7167 MergedKind = LHSKind; 7168 else 7169 MergedKind = NullabilityKind::Unspecified; 7170 } 7171 7172 // Return if ResTy already has the correct nullability. 7173 if (GetNullability(ResTy) == MergedKind) 7174 return ResTy; 7175 7176 // Strip all nullability from ResTy. 7177 while (ResTy->getNullability(Ctx)) 7178 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7179 7180 // Create a new AttributedType with the new nullability kind. 7181 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7182 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7183 } 7184 7185 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7186 /// in the case of a the GNU conditional expr extension. 7187 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7188 SourceLocation ColonLoc, 7189 Expr *CondExpr, Expr *LHSExpr, 7190 Expr *RHSExpr) { 7191 if (!getLangOpts().CPlusPlus) { 7192 // C cannot handle TypoExpr nodes in the condition because it 7193 // doesn't handle dependent types properly, so make sure any TypoExprs have 7194 // been dealt with before checking the operands. 7195 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7196 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7197 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7198 7199 if (!CondResult.isUsable()) 7200 return ExprError(); 7201 7202 if (LHSExpr) { 7203 if (!LHSResult.isUsable()) 7204 return ExprError(); 7205 } 7206 7207 if (!RHSResult.isUsable()) 7208 return ExprError(); 7209 7210 CondExpr = CondResult.get(); 7211 LHSExpr = LHSResult.get(); 7212 RHSExpr = RHSResult.get(); 7213 } 7214 7215 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7216 // was the condition. 7217 OpaqueValueExpr *opaqueValue = nullptr; 7218 Expr *commonExpr = nullptr; 7219 if (!LHSExpr) { 7220 commonExpr = CondExpr; 7221 // Lower out placeholder types first. This is important so that we don't 7222 // try to capture a placeholder. This happens in few cases in C++; such 7223 // as Objective-C++'s dictionary subscripting syntax. 7224 if (commonExpr->hasPlaceholderType()) { 7225 ExprResult result = CheckPlaceholderExpr(commonExpr); 7226 if (!result.isUsable()) return ExprError(); 7227 commonExpr = result.get(); 7228 } 7229 // We usually want to apply unary conversions *before* saving, except 7230 // in the special case of a C++ l-value conditional. 7231 if (!(getLangOpts().CPlusPlus 7232 && !commonExpr->isTypeDependent() 7233 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7234 && commonExpr->isGLValue() 7235 && commonExpr->isOrdinaryOrBitFieldObject() 7236 && RHSExpr->isOrdinaryOrBitFieldObject() 7237 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7238 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7239 if (commonRes.isInvalid()) 7240 return ExprError(); 7241 commonExpr = commonRes.get(); 7242 } 7243 7244 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7245 commonExpr->getType(), 7246 commonExpr->getValueKind(), 7247 commonExpr->getObjectKind(), 7248 commonExpr); 7249 LHSExpr = CondExpr = opaqueValue; 7250 } 7251 7252 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7253 ExprValueKind VK = VK_RValue; 7254 ExprObjectKind OK = OK_Ordinary; 7255 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7256 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7257 VK, OK, QuestionLoc); 7258 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7259 RHS.isInvalid()) 7260 return ExprError(); 7261 7262 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7263 RHS.get()); 7264 7265 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7266 7267 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7268 Context); 7269 7270 if (!commonExpr) 7271 return new (Context) 7272 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7273 RHS.get(), result, VK, OK); 7274 7275 return new (Context) BinaryConditionalOperator( 7276 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7277 ColonLoc, result, VK, OK); 7278 } 7279 7280 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7281 // being closely modeled after the C99 spec:-). The odd characteristic of this 7282 // routine is it effectively iqnores the qualifiers on the top level pointee. 7283 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7284 // FIXME: add a couple examples in this comment. 7285 static Sema::AssignConvertType 7286 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7287 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7288 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7289 7290 // get the "pointed to" type (ignoring qualifiers at the top level) 7291 const Type *lhptee, *rhptee; 7292 Qualifiers lhq, rhq; 7293 std::tie(lhptee, lhq) = 7294 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7295 std::tie(rhptee, rhq) = 7296 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7297 7298 Sema::AssignConvertType ConvTy = Sema::Compatible; 7299 7300 // C99 6.5.16.1p1: This following citation is common to constraints 7301 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7302 // qualifiers of the type *pointed to* by the right; 7303 7304 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7305 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7306 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7307 // Ignore lifetime for further calculation. 7308 lhq.removeObjCLifetime(); 7309 rhq.removeObjCLifetime(); 7310 } 7311 7312 if (!lhq.compatiblyIncludes(rhq)) { 7313 // Treat address-space mismatches as fatal. TODO: address subspaces 7314 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7315 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7316 7317 // It's okay to add or remove GC or lifetime qualifiers when converting to 7318 // and from void*. 7319 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7320 .compatiblyIncludes( 7321 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7322 && (lhptee->isVoidType() || rhptee->isVoidType())) 7323 ; // keep old 7324 7325 // Treat lifetime mismatches as fatal. 7326 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7327 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7328 7329 // For GCC/MS compatibility, other qualifier mismatches are treated 7330 // as still compatible in C. 7331 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7332 } 7333 7334 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7335 // incomplete type and the other is a pointer to a qualified or unqualified 7336 // version of void... 7337 if (lhptee->isVoidType()) { 7338 if (rhptee->isIncompleteOrObjectType()) 7339 return ConvTy; 7340 7341 // As an extension, we allow cast to/from void* to function pointer. 7342 assert(rhptee->isFunctionType()); 7343 return Sema::FunctionVoidPointer; 7344 } 7345 7346 if (rhptee->isVoidType()) { 7347 if (lhptee->isIncompleteOrObjectType()) 7348 return ConvTy; 7349 7350 // As an extension, we allow cast to/from void* to function pointer. 7351 assert(lhptee->isFunctionType()); 7352 return Sema::FunctionVoidPointer; 7353 } 7354 7355 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7356 // unqualified versions of compatible types, ... 7357 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7358 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7359 // Check if the pointee types are compatible ignoring the sign. 7360 // We explicitly check for char so that we catch "char" vs 7361 // "unsigned char" on systems where "char" is unsigned. 7362 if (lhptee->isCharType()) 7363 ltrans = S.Context.UnsignedCharTy; 7364 else if (lhptee->hasSignedIntegerRepresentation()) 7365 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7366 7367 if (rhptee->isCharType()) 7368 rtrans = S.Context.UnsignedCharTy; 7369 else if (rhptee->hasSignedIntegerRepresentation()) 7370 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7371 7372 if (ltrans == rtrans) { 7373 // Types are compatible ignoring the sign. Qualifier incompatibility 7374 // takes priority over sign incompatibility because the sign 7375 // warning can be disabled. 7376 if (ConvTy != Sema::Compatible) 7377 return ConvTy; 7378 7379 return Sema::IncompatiblePointerSign; 7380 } 7381 7382 // If we are a multi-level pointer, it's possible that our issue is simply 7383 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7384 // the eventual target type is the same and the pointers have the same 7385 // level of indirection, this must be the issue. 7386 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7387 do { 7388 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7389 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7390 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7391 7392 if (lhptee == rhptee) 7393 return Sema::IncompatibleNestedPointerQualifiers; 7394 } 7395 7396 // General pointer incompatibility takes priority over qualifiers. 7397 return Sema::IncompatiblePointer; 7398 } 7399 if (!S.getLangOpts().CPlusPlus && 7400 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7401 return Sema::IncompatiblePointer; 7402 return ConvTy; 7403 } 7404 7405 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7406 /// block pointer types are compatible or whether a block and normal pointer 7407 /// are compatible. It is more restrict than comparing two function pointer 7408 // types. 7409 static Sema::AssignConvertType 7410 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7411 QualType RHSType) { 7412 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7413 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7414 7415 QualType lhptee, rhptee; 7416 7417 // get the "pointed to" type (ignoring qualifiers at the top level) 7418 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7419 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7420 7421 // In C++, the types have to match exactly. 7422 if (S.getLangOpts().CPlusPlus) 7423 return Sema::IncompatibleBlockPointer; 7424 7425 Sema::AssignConvertType ConvTy = Sema::Compatible; 7426 7427 // For blocks we enforce that qualifiers are identical. 7428 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7429 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7430 if (S.getLangOpts().OpenCL) { 7431 LQuals.removeAddressSpace(); 7432 RQuals.removeAddressSpace(); 7433 } 7434 if (LQuals != RQuals) 7435 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7436 7437 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7438 // assignment. 7439 // The current behavior is similar to C++ lambdas. A block might be 7440 // assigned to a variable iff its return type and parameters are compatible 7441 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7442 // an assignment. Presumably it should behave in way that a function pointer 7443 // assignment does in C, so for each parameter and return type: 7444 // * CVR and address space of LHS should be a superset of CVR and address 7445 // space of RHS. 7446 // * unqualified types should be compatible. 7447 if (S.getLangOpts().OpenCL) { 7448 if (!S.Context.typesAreBlockPointerCompatible( 7449 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7450 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7451 return Sema::IncompatibleBlockPointer; 7452 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7453 return Sema::IncompatibleBlockPointer; 7454 7455 return ConvTy; 7456 } 7457 7458 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7459 /// for assignment compatibility. 7460 static Sema::AssignConvertType 7461 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7462 QualType RHSType) { 7463 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7464 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7465 7466 if (LHSType->isObjCBuiltinType()) { 7467 // Class is not compatible with ObjC object pointers. 7468 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7469 !RHSType->isObjCQualifiedClassType()) 7470 return Sema::IncompatiblePointer; 7471 return Sema::Compatible; 7472 } 7473 if (RHSType->isObjCBuiltinType()) { 7474 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7475 !LHSType->isObjCQualifiedClassType()) 7476 return Sema::IncompatiblePointer; 7477 return Sema::Compatible; 7478 } 7479 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7480 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7481 7482 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7483 // make an exception for id<P> 7484 !LHSType->isObjCQualifiedIdType()) 7485 return Sema::CompatiblePointerDiscardsQualifiers; 7486 7487 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7488 return Sema::Compatible; 7489 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7490 return Sema::IncompatibleObjCQualifiedId; 7491 return Sema::IncompatiblePointer; 7492 } 7493 7494 Sema::AssignConvertType 7495 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7496 QualType LHSType, QualType RHSType) { 7497 // Fake up an opaque expression. We don't actually care about what 7498 // cast operations are required, so if CheckAssignmentConstraints 7499 // adds casts to this they'll be wasted, but fortunately that doesn't 7500 // usually happen on valid code. 7501 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7502 ExprResult RHSPtr = &RHSExpr; 7503 CastKind K = CK_Invalid; 7504 7505 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7506 } 7507 7508 /// This helper function returns true if QT is a vector type that has element 7509 /// type ElementType. 7510 static bool isVector(QualType QT, QualType ElementType) { 7511 if (const VectorType *VT = QT->getAs<VectorType>()) 7512 return VT->getElementType() == ElementType; 7513 return false; 7514 } 7515 7516 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7517 /// has code to accommodate several GCC extensions when type checking 7518 /// pointers. Here are some objectionable examples that GCC considers warnings: 7519 /// 7520 /// int a, *pint; 7521 /// short *pshort; 7522 /// struct foo *pfoo; 7523 /// 7524 /// pint = pshort; // warning: assignment from incompatible pointer type 7525 /// a = pint; // warning: assignment makes integer from pointer without a cast 7526 /// pint = a; // warning: assignment makes pointer from integer without a cast 7527 /// pint = pfoo; // warning: assignment from incompatible pointer type 7528 /// 7529 /// As a result, the code for dealing with pointers is more complex than the 7530 /// C99 spec dictates. 7531 /// 7532 /// Sets 'Kind' for any result kind except Incompatible. 7533 Sema::AssignConvertType 7534 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7535 CastKind &Kind, bool ConvertRHS) { 7536 QualType RHSType = RHS.get()->getType(); 7537 QualType OrigLHSType = LHSType; 7538 7539 // Get canonical types. We're not formatting these types, just comparing 7540 // them. 7541 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7542 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7543 7544 // Common case: no conversion required. 7545 if (LHSType == RHSType) { 7546 Kind = CK_NoOp; 7547 return Compatible; 7548 } 7549 7550 // If we have an atomic type, try a non-atomic assignment, then just add an 7551 // atomic qualification step. 7552 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7553 Sema::AssignConvertType result = 7554 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7555 if (result != Compatible) 7556 return result; 7557 if (Kind != CK_NoOp && ConvertRHS) 7558 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7559 Kind = CK_NonAtomicToAtomic; 7560 return Compatible; 7561 } 7562 7563 // If the left-hand side is a reference type, then we are in a 7564 // (rare!) case where we've allowed the use of references in C, 7565 // e.g., as a parameter type in a built-in function. In this case, 7566 // just make sure that the type referenced is compatible with the 7567 // right-hand side type. The caller is responsible for adjusting 7568 // LHSType so that the resulting expression does not have reference 7569 // type. 7570 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7571 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7572 Kind = CK_LValueBitCast; 7573 return Compatible; 7574 } 7575 return Incompatible; 7576 } 7577 7578 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7579 // to the same ExtVector type. 7580 if (LHSType->isExtVectorType()) { 7581 if (RHSType->isExtVectorType()) 7582 return Incompatible; 7583 if (RHSType->isArithmeticType()) { 7584 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7585 if (ConvertRHS) 7586 RHS = prepareVectorSplat(LHSType, RHS.get()); 7587 Kind = CK_VectorSplat; 7588 return Compatible; 7589 } 7590 } 7591 7592 // Conversions to or from vector type. 7593 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7594 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7595 // Allow assignments of an AltiVec vector type to an equivalent GCC 7596 // vector type and vice versa 7597 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7598 Kind = CK_BitCast; 7599 return Compatible; 7600 } 7601 7602 // If we are allowing lax vector conversions, and LHS and RHS are both 7603 // vectors, the total size only needs to be the same. This is a bitcast; 7604 // no bits are changed but the result type is different. 7605 if (isLaxVectorConversion(RHSType, LHSType)) { 7606 Kind = CK_BitCast; 7607 return IncompatibleVectors; 7608 } 7609 } 7610 7611 // When the RHS comes from another lax conversion (e.g. binops between 7612 // scalars and vectors) the result is canonicalized as a vector. When the 7613 // LHS is also a vector, the lax is allowed by the condition above. Handle 7614 // the case where LHS is a scalar. 7615 if (LHSType->isScalarType()) { 7616 const VectorType *VecType = RHSType->getAs<VectorType>(); 7617 if (VecType && VecType->getNumElements() == 1 && 7618 isLaxVectorConversion(RHSType, LHSType)) { 7619 ExprResult *VecExpr = &RHS; 7620 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7621 Kind = CK_BitCast; 7622 return Compatible; 7623 } 7624 } 7625 7626 return Incompatible; 7627 } 7628 7629 // Diagnose attempts to convert between __float128 and long double where 7630 // such conversions currently can't be handled. 7631 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7632 return Incompatible; 7633 7634 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7635 // discards the imaginary part. 7636 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7637 !LHSType->getAs<ComplexType>()) 7638 return Incompatible; 7639 7640 // Arithmetic conversions. 7641 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7642 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7643 if (ConvertRHS) 7644 Kind = PrepareScalarCast(RHS, LHSType); 7645 return Compatible; 7646 } 7647 7648 // Conversions to normal pointers. 7649 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7650 // U* -> T* 7651 if (isa<PointerType>(RHSType)) { 7652 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7653 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7654 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7655 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7656 } 7657 7658 // int -> T* 7659 if (RHSType->isIntegerType()) { 7660 Kind = CK_IntegralToPointer; // FIXME: null? 7661 return IntToPointer; 7662 } 7663 7664 // C pointers are not compatible with ObjC object pointers, 7665 // with two exceptions: 7666 if (isa<ObjCObjectPointerType>(RHSType)) { 7667 // - conversions to void* 7668 if (LHSPointer->getPointeeType()->isVoidType()) { 7669 Kind = CK_BitCast; 7670 return Compatible; 7671 } 7672 7673 // - conversions from 'Class' to the redefinition type 7674 if (RHSType->isObjCClassType() && 7675 Context.hasSameType(LHSType, 7676 Context.getObjCClassRedefinitionType())) { 7677 Kind = CK_BitCast; 7678 return Compatible; 7679 } 7680 7681 Kind = CK_BitCast; 7682 return IncompatiblePointer; 7683 } 7684 7685 // U^ -> void* 7686 if (RHSType->getAs<BlockPointerType>()) { 7687 if (LHSPointer->getPointeeType()->isVoidType()) { 7688 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7689 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7690 ->getPointeeType() 7691 .getAddressSpace(); 7692 Kind = 7693 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7694 return Compatible; 7695 } 7696 } 7697 7698 return Incompatible; 7699 } 7700 7701 // Conversions to block pointers. 7702 if (isa<BlockPointerType>(LHSType)) { 7703 // U^ -> T^ 7704 if (RHSType->isBlockPointerType()) { 7705 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>() 7706 ->getPointeeType() 7707 .getAddressSpace(); 7708 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7709 ->getPointeeType() 7710 .getAddressSpace(); 7711 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7712 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7713 } 7714 7715 // int or null -> T^ 7716 if (RHSType->isIntegerType()) { 7717 Kind = CK_IntegralToPointer; // FIXME: null 7718 return IntToBlockPointer; 7719 } 7720 7721 // id -> T^ 7722 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7723 Kind = CK_AnyPointerToBlockPointerCast; 7724 return Compatible; 7725 } 7726 7727 // void* -> T^ 7728 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7729 if (RHSPT->getPointeeType()->isVoidType()) { 7730 Kind = CK_AnyPointerToBlockPointerCast; 7731 return Compatible; 7732 } 7733 7734 return Incompatible; 7735 } 7736 7737 // Conversions to Objective-C pointers. 7738 if (isa<ObjCObjectPointerType>(LHSType)) { 7739 // A* -> B* 7740 if (RHSType->isObjCObjectPointerType()) { 7741 Kind = CK_BitCast; 7742 Sema::AssignConvertType result = 7743 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7744 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7745 result == Compatible && 7746 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7747 result = IncompatibleObjCWeakRef; 7748 return result; 7749 } 7750 7751 // int or null -> A* 7752 if (RHSType->isIntegerType()) { 7753 Kind = CK_IntegralToPointer; // FIXME: null 7754 return IntToPointer; 7755 } 7756 7757 // In general, C pointers are not compatible with ObjC object pointers, 7758 // with two exceptions: 7759 if (isa<PointerType>(RHSType)) { 7760 Kind = CK_CPointerToObjCPointerCast; 7761 7762 // - conversions from 'void*' 7763 if (RHSType->isVoidPointerType()) { 7764 return Compatible; 7765 } 7766 7767 // - conversions to 'Class' from its redefinition type 7768 if (LHSType->isObjCClassType() && 7769 Context.hasSameType(RHSType, 7770 Context.getObjCClassRedefinitionType())) { 7771 return Compatible; 7772 } 7773 7774 return IncompatiblePointer; 7775 } 7776 7777 // Only under strict condition T^ is compatible with an Objective-C pointer. 7778 if (RHSType->isBlockPointerType() && 7779 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7780 if (ConvertRHS) 7781 maybeExtendBlockObject(RHS); 7782 Kind = CK_BlockPointerToObjCPointerCast; 7783 return Compatible; 7784 } 7785 7786 return Incompatible; 7787 } 7788 7789 // Conversions from pointers that are not covered by the above. 7790 if (isa<PointerType>(RHSType)) { 7791 // T* -> _Bool 7792 if (LHSType == Context.BoolTy) { 7793 Kind = CK_PointerToBoolean; 7794 return Compatible; 7795 } 7796 7797 // T* -> int 7798 if (LHSType->isIntegerType()) { 7799 Kind = CK_PointerToIntegral; 7800 return PointerToInt; 7801 } 7802 7803 return Incompatible; 7804 } 7805 7806 // Conversions from Objective-C pointers that are not covered by the above. 7807 if (isa<ObjCObjectPointerType>(RHSType)) { 7808 // T* -> _Bool 7809 if (LHSType == Context.BoolTy) { 7810 Kind = CK_PointerToBoolean; 7811 return Compatible; 7812 } 7813 7814 // T* -> int 7815 if (LHSType->isIntegerType()) { 7816 Kind = CK_PointerToIntegral; 7817 return PointerToInt; 7818 } 7819 7820 return Incompatible; 7821 } 7822 7823 // struct A -> struct B 7824 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7825 if (Context.typesAreCompatible(LHSType, RHSType)) { 7826 Kind = CK_NoOp; 7827 return Compatible; 7828 } 7829 } 7830 7831 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7832 Kind = CK_IntToOCLSampler; 7833 return Compatible; 7834 } 7835 7836 return Incompatible; 7837 } 7838 7839 /// \brief Constructs a transparent union from an expression that is 7840 /// used to initialize the transparent union. 7841 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7842 ExprResult &EResult, QualType UnionType, 7843 FieldDecl *Field) { 7844 // Build an initializer list that designates the appropriate member 7845 // of the transparent union. 7846 Expr *E = EResult.get(); 7847 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7848 E, SourceLocation()); 7849 Initializer->setType(UnionType); 7850 Initializer->setInitializedFieldInUnion(Field); 7851 7852 // Build a compound literal constructing a value of the transparent 7853 // union type from this initializer list. 7854 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7855 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7856 VK_RValue, Initializer, false); 7857 } 7858 7859 Sema::AssignConvertType 7860 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7861 ExprResult &RHS) { 7862 QualType RHSType = RHS.get()->getType(); 7863 7864 // If the ArgType is a Union type, we want to handle a potential 7865 // transparent_union GCC extension. 7866 const RecordType *UT = ArgType->getAsUnionType(); 7867 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7868 return Incompatible; 7869 7870 // The field to initialize within the transparent union. 7871 RecordDecl *UD = UT->getDecl(); 7872 FieldDecl *InitField = nullptr; 7873 // It's compatible if the expression matches any of the fields. 7874 for (auto *it : UD->fields()) { 7875 if (it->getType()->isPointerType()) { 7876 // If the transparent union contains a pointer type, we allow: 7877 // 1) void pointer 7878 // 2) null pointer constant 7879 if (RHSType->isPointerType()) 7880 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7881 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7882 InitField = it; 7883 break; 7884 } 7885 7886 if (RHS.get()->isNullPointerConstant(Context, 7887 Expr::NPC_ValueDependentIsNull)) { 7888 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7889 CK_NullToPointer); 7890 InitField = it; 7891 break; 7892 } 7893 } 7894 7895 CastKind Kind = CK_Invalid; 7896 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7897 == Compatible) { 7898 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7899 InitField = it; 7900 break; 7901 } 7902 } 7903 7904 if (!InitField) 7905 return Incompatible; 7906 7907 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7908 return Compatible; 7909 } 7910 7911 Sema::AssignConvertType 7912 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7913 bool Diagnose, 7914 bool DiagnoseCFAudited, 7915 bool ConvertRHS) { 7916 // We need to be able to tell the caller whether we diagnosed a problem, if 7917 // they ask us to issue diagnostics. 7918 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7919 7920 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7921 // we can't avoid *all* modifications at the moment, so we need some somewhere 7922 // to put the updated value. 7923 ExprResult LocalRHS = CallerRHS; 7924 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7925 7926 if (getLangOpts().CPlusPlus) { 7927 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7928 // C++ 5.17p3: If the left operand is not of class type, the 7929 // expression is implicitly converted (C++ 4) to the 7930 // cv-unqualified type of the left operand. 7931 QualType RHSType = RHS.get()->getType(); 7932 if (Diagnose) { 7933 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7934 AA_Assigning); 7935 } else { 7936 ImplicitConversionSequence ICS = 7937 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7938 /*SuppressUserConversions=*/false, 7939 /*AllowExplicit=*/false, 7940 /*InOverloadResolution=*/false, 7941 /*CStyle=*/false, 7942 /*AllowObjCWritebackConversion=*/false); 7943 if (ICS.isFailure()) 7944 return Incompatible; 7945 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7946 ICS, AA_Assigning); 7947 } 7948 if (RHS.isInvalid()) 7949 return Incompatible; 7950 Sema::AssignConvertType result = Compatible; 7951 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7952 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7953 result = IncompatibleObjCWeakRef; 7954 return result; 7955 } 7956 7957 // FIXME: Currently, we fall through and treat C++ classes like C 7958 // structures. 7959 // FIXME: We also fall through for atomics; not sure what should 7960 // happen there, though. 7961 } else if (RHS.get()->getType() == Context.OverloadTy) { 7962 // As a set of extensions to C, we support overloading on functions. These 7963 // functions need to be resolved here. 7964 DeclAccessPair DAP; 7965 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7966 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7967 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7968 else 7969 return Incompatible; 7970 } 7971 7972 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7973 // a null pointer constant. 7974 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7975 LHSType->isBlockPointerType()) && 7976 RHS.get()->isNullPointerConstant(Context, 7977 Expr::NPC_ValueDependentIsNull)) { 7978 if (Diagnose || ConvertRHS) { 7979 CastKind Kind; 7980 CXXCastPath Path; 7981 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7982 /*IgnoreBaseAccess=*/false, Diagnose); 7983 if (ConvertRHS) 7984 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7985 } 7986 return Compatible; 7987 } 7988 7989 // This check seems unnatural, however it is necessary to ensure the proper 7990 // conversion of functions/arrays. If the conversion were done for all 7991 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7992 // expressions that suppress this implicit conversion (&, sizeof). 7993 // 7994 // Suppress this for references: C++ 8.5.3p5. 7995 if (!LHSType->isReferenceType()) { 7996 // FIXME: We potentially allocate here even if ConvertRHS is false. 7997 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7998 if (RHS.isInvalid()) 7999 return Incompatible; 8000 } 8001 8002 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8003 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8004 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8005 if (PDecl && !PDecl->hasDefinition()) { 8006 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 8007 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8008 } 8009 } 8010 8011 CastKind Kind = CK_Invalid; 8012 Sema::AssignConvertType result = 8013 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8014 8015 // C99 6.5.16.1p2: The value of the right operand is converted to the 8016 // type of the assignment expression. 8017 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8018 // so that we can use references in built-in functions even in C. 8019 // The getNonReferenceType() call makes sure that the resulting expression 8020 // does not have reference type. 8021 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8022 QualType Ty = LHSType.getNonLValueExprType(Context); 8023 Expr *E = RHS.get(); 8024 8025 // Check for various Objective-C errors. If we are not reporting 8026 // diagnostics and just checking for errors, e.g., during overload 8027 // resolution, return Incompatible to indicate the failure. 8028 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8029 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8030 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8031 if (!Diagnose) 8032 return Incompatible; 8033 } 8034 if (getLangOpts().ObjC1 && 8035 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8036 E->getType(), E, Diagnose) || 8037 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8038 if (!Diagnose) 8039 return Incompatible; 8040 // Replace the expression with a corrected version and continue so we 8041 // can find further errors. 8042 RHS = E; 8043 return Compatible; 8044 } 8045 8046 if (ConvertRHS) 8047 RHS = ImpCastExprToType(E, Ty, Kind); 8048 } 8049 return result; 8050 } 8051 8052 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8053 ExprResult &RHS) { 8054 Diag(Loc, diag::err_typecheck_invalid_operands) 8055 << LHS.get()->getType() << RHS.get()->getType() 8056 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8057 return QualType(); 8058 } 8059 8060 // Diagnose cases where a scalar was implicitly converted to a vector and 8061 // diagnose the underlying types. Otherwise, diagnose the error 8062 // as invalid vector logical operands for non-C++ cases. 8063 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8064 ExprResult &RHS) { 8065 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8066 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8067 8068 bool LHSNatVec = LHSType->isVectorType(); 8069 bool RHSNatVec = RHSType->isVectorType(); 8070 8071 if (!(LHSNatVec && RHSNatVec)) { 8072 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8073 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8074 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8075 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8076 << Vector->getSourceRange(); 8077 return QualType(); 8078 } 8079 8080 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8081 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8082 << RHS.get()->getSourceRange(); 8083 8084 return QualType(); 8085 } 8086 8087 /// Try to convert a value of non-vector type to a vector type by converting 8088 /// the type to the element type of the vector and then performing a splat. 8089 /// If the language is OpenCL, we only use conversions that promote scalar 8090 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8091 /// for float->int. 8092 /// 8093 /// OpenCL V2.0 6.2.6.p2: 8094 /// An error shall occur if any scalar operand type has greater rank 8095 /// than the type of the vector element. 8096 /// 8097 /// \param scalar - if non-null, actually perform the conversions 8098 /// \return true if the operation fails (but without diagnosing the failure) 8099 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8100 QualType scalarTy, 8101 QualType vectorEltTy, 8102 QualType vectorTy, 8103 unsigned &DiagID) { 8104 // The conversion to apply to the scalar before splatting it, 8105 // if necessary. 8106 CastKind scalarCast = CK_Invalid; 8107 8108 if (vectorEltTy->isIntegralType(S.Context)) { 8109 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8110 (scalarTy->isIntegerType() && 8111 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8112 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8113 return true; 8114 } 8115 if (!scalarTy->isIntegralType(S.Context)) 8116 return true; 8117 scalarCast = CK_IntegralCast; 8118 } else if (vectorEltTy->isRealFloatingType()) { 8119 if (scalarTy->isRealFloatingType()) { 8120 if (S.getLangOpts().OpenCL && 8121 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8122 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8123 return true; 8124 } 8125 scalarCast = CK_FloatingCast; 8126 } 8127 else if (scalarTy->isIntegralType(S.Context)) 8128 scalarCast = CK_IntegralToFloating; 8129 else 8130 return true; 8131 } else { 8132 return true; 8133 } 8134 8135 // Adjust scalar if desired. 8136 if (scalar) { 8137 if (scalarCast != CK_Invalid) 8138 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8139 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8140 } 8141 return false; 8142 } 8143 8144 /// Convert vector E to a vector with the same number of elements but different 8145 /// element type. 8146 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8147 const auto *VecTy = E->getType()->getAs<VectorType>(); 8148 assert(VecTy && "Expression E must be a vector"); 8149 QualType NewVecTy = S.Context.getVectorType(ElementType, 8150 VecTy->getNumElements(), 8151 VecTy->getVectorKind()); 8152 8153 // Look through the implicit cast. Return the subexpression if its type is 8154 // NewVecTy. 8155 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8156 if (ICE->getSubExpr()->getType() == NewVecTy) 8157 return ICE->getSubExpr(); 8158 8159 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8160 return S.ImpCastExprToType(E, NewVecTy, Cast); 8161 } 8162 8163 /// Test if a (constant) integer Int can be casted to another integer type 8164 /// IntTy without losing precision. 8165 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8166 QualType OtherIntTy) { 8167 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8168 8169 // Reject cases where the value of the Int is unknown as that would 8170 // possibly cause truncation, but accept cases where the scalar can be 8171 // demoted without loss of precision. 8172 llvm::APSInt Result; 8173 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8174 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8175 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8176 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8177 8178 if (CstInt) { 8179 // If the scalar is constant and is of a higher order and has more active 8180 // bits that the vector element type, reject it. 8181 unsigned NumBits = IntSigned 8182 ? (Result.isNegative() ? Result.getMinSignedBits() 8183 : Result.getActiveBits()) 8184 : Result.getActiveBits(); 8185 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8186 return true; 8187 8188 // If the signedness of the scalar type and the vector element type 8189 // differs and the number of bits is greater than that of the vector 8190 // element reject it. 8191 return (IntSigned != OtherIntSigned && 8192 NumBits > S.Context.getIntWidth(OtherIntTy)); 8193 } 8194 8195 // Reject cases where the value of the scalar is not constant and it's 8196 // order is greater than that of the vector element type. 8197 return (Order < 0); 8198 } 8199 8200 /// Test if a (constant) integer Int can be casted to floating point type 8201 /// FloatTy without losing precision. 8202 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8203 QualType FloatTy) { 8204 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8205 8206 // Determine if the integer constant can be expressed as a floating point 8207 // number of the appropiate type. 8208 llvm::APSInt Result; 8209 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8210 uint64_t Bits = 0; 8211 if (CstInt) { 8212 // Reject constants that would be truncated if they were converted to 8213 // the floating point type. Test by simple to/from conversion. 8214 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8215 // could be avoided if there was a convertFromAPInt method 8216 // which could signal back if implicit truncation occurred. 8217 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8218 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8219 llvm::APFloat::rmTowardZero); 8220 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8221 !IntTy->hasSignedIntegerRepresentation()); 8222 bool Ignored = false; 8223 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8224 &Ignored); 8225 if (Result != ConvertBack) 8226 return true; 8227 } else { 8228 // Reject types that cannot be fully encoded into the mantissa of 8229 // the float. 8230 Bits = S.Context.getTypeSize(IntTy); 8231 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8232 S.Context.getFloatTypeSemantics(FloatTy)); 8233 if (Bits > FloatPrec) 8234 return true; 8235 } 8236 8237 return false; 8238 } 8239 8240 /// Attempt to convert and splat Scalar into a vector whose types matches 8241 /// Vector following GCC conversion rules. The rule is that implicit 8242 /// conversion can occur when Scalar can be casted to match Vector's element 8243 /// type without causing truncation of Scalar. 8244 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8245 ExprResult *Vector) { 8246 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8247 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8248 const VectorType *VT = VectorTy->getAs<VectorType>(); 8249 8250 assert(!isa<ExtVectorType>(VT) && 8251 "ExtVectorTypes should not be handled here!"); 8252 8253 QualType VectorEltTy = VT->getElementType(); 8254 8255 // Reject cases where the vector element type or the scalar element type are 8256 // not integral or floating point types. 8257 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8258 return true; 8259 8260 // The conversion to apply to the scalar before splatting it, 8261 // if necessary. 8262 CastKind ScalarCast = CK_NoOp; 8263 8264 // Accept cases where the vector elements are integers and the scalar is 8265 // an integer. 8266 // FIXME: Notionally if the scalar was a floating point value with a precise 8267 // integral representation, we could cast it to an appropriate integer 8268 // type and then perform the rest of the checks here. GCC will perform 8269 // this conversion in some cases as determined by the input language. 8270 // We should accept it on a language independent basis. 8271 if (VectorEltTy->isIntegralType(S.Context) && 8272 ScalarTy->isIntegralType(S.Context) && 8273 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8274 8275 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8276 return true; 8277 8278 ScalarCast = CK_IntegralCast; 8279 } else if (VectorEltTy->isRealFloatingType()) { 8280 if (ScalarTy->isRealFloatingType()) { 8281 8282 // Reject cases where the scalar type is not a constant and has a higher 8283 // Order than the vector element type. 8284 llvm::APFloat Result(0.0); 8285 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8286 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8287 if (!CstScalar && Order < 0) 8288 return true; 8289 8290 // If the scalar cannot be safely casted to the vector element type, 8291 // reject it. 8292 if (CstScalar) { 8293 bool Truncated = false; 8294 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8295 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8296 if (Truncated) 8297 return true; 8298 } 8299 8300 ScalarCast = CK_FloatingCast; 8301 } else if (ScalarTy->isIntegralType(S.Context)) { 8302 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8303 return true; 8304 8305 ScalarCast = CK_IntegralToFloating; 8306 } else 8307 return true; 8308 } 8309 8310 // Adjust scalar if desired. 8311 if (Scalar) { 8312 if (ScalarCast != CK_NoOp) 8313 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8314 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8315 } 8316 return false; 8317 } 8318 8319 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8320 SourceLocation Loc, bool IsCompAssign, 8321 bool AllowBothBool, 8322 bool AllowBoolConversions) { 8323 if (!IsCompAssign) { 8324 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8325 if (LHS.isInvalid()) 8326 return QualType(); 8327 } 8328 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8329 if (RHS.isInvalid()) 8330 return QualType(); 8331 8332 // For conversion purposes, we ignore any qualifiers. 8333 // For example, "const float" and "float" are equivalent. 8334 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8335 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8336 8337 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8338 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8339 assert(LHSVecType || RHSVecType); 8340 8341 // AltiVec-style "vector bool op vector bool" combinations are allowed 8342 // for some operators but not others. 8343 if (!AllowBothBool && 8344 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8345 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8346 return InvalidOperands(Loc, LHS, RHS); 8347 8348 // If the vector types are identical, return. 8349 if (Context.hasSameType(LHSType, RHSType)) 8350 return LHSType; 8351 8352 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8353 if (LHSVecType && RHSVecType && 8354 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8355 if (isa<ExtVectorType>(LHSVecType)) { 8356 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8357 return LHSType; 8358 } 8359 8360 if (!IsCompAssign) 8361 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8362 return RHSType; 8363 } 8364 8365 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8366 // can be mixed, with the result being the non-bool type. The non-bool 8367 // operand must have integer element type. 8368 if (AllowBoolConversions && LHSVecType && RHSVecType && 8369 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8370 (Context.getTypeSize(LHSVecType->getElementType()) == 8371 Context.getTypeSize(RHSVecType->getElementType()))) { 8372 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8373 LHSVecType->getElementType()->isIntegerType() && 8374 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8375 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8376 return LHSType; 8377 } 8378 if (!IsCompAssign && 8379 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8380 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8381 RHSVecType->getElementType()->isIntegerType()) { 8382 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8383 return RHSType; 8384 } 8385 } 8386 8387 // If there's a vector type and a scalar, try to convert the scalar to 8388 // the vector element type and splat. 8389 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8390 if (!RHSVecType) { 8391 if (isa<ExtVectorType>(LHSVecType)) { 8392 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8393 LHSVecType->getElementType(), LHSType, 8394 DiagID)) 8395 return LHSType; 8396 } else { 8397 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8398 return LHSType; 8399 } 8400 } 8401 if (!LHSVecType) { 8402 if (isa<ExtVectorType>(RHSVecType)) { 8403 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8404 LHSType, RHSVecType->getElementType(), 8405 RHSType, DiagID)) 8406 return RHSType; 8407 } else { 8408 if (LHS.get()->getValueKind() == VK_LValue || 8409 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8410 return RHSType; 8411 } 8412 } 8413 8414 // FIXME: The code below also handles conversion between vectors and 8415 // non-scalars, we should break this down into fine grained specific checks 8416 // and emit proper diagnostics. 8417 QualType VecType = LHSVecType ? LHSType : RHSType; 8418 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8419 QualType OtherType = LHSVecType ? RHSType : LHSType; 8420 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8421 if (isLaxVectorConversion(OtherType, VecType)) { 8422 // If we're allowing lax vector conversions, only the total (data) size 8423 // needs to be the same. For non compound assignment, if one of the types is 8424 // scalar, the result is always the vector type. 8425 if (!IsCompAssign) { 8426 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8427 return VecType; 8428 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8429 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8430 // type. Note that this is already done by non-compound assignments in 8431 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8432 // <1 x T> -> T. The result is also a vector type. 8433 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8434 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8435 ExprResult *RHSExpr = &RHS; 8436 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8437 return VecType; 8438 } 8439 } 8440 8441 // Okay, the expression is invalid. 8442 8443 // If there's a non-vector, non-real operand, diagnose that. 8444 if ((!RHSVecType && !RHSType->isRealType()) || 8445 (!LHSVecType && !LHSType->isRealType())) { 8446 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8447 << LHSType << RHSType 8448 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8449 return QualType(); 8450 } 8451 8452 // OpenCL V1.1 6.2.6.p1: 8453 // If the operands are of more than one vector type, then an error shall 8454 // occur. Implicit conversions between vector types are not permitted, per 8455 // section 6.2.1. 8456 if (getLangOpts().OpenCL && 8457 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8458 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8459 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8460 << RHSType; 8461 return QualType(); 8462 } 8463 8464 8465 // If there is a vector type that is not a ExtVector and a scalar, we reach 8466 // this point if scalar could not be converted to the vector's element type 8467 // without truncation. 8468 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8469 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8470 QualType Scalar = LHSVecType ? RHSType : LHSType; 8471 QualType Vector = LHSVecType ? LHSType : RHSType; 8472 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8473 Diag(Loc, 8474 diag::err_typecheck_vector_not_convertable_implict_truncation) 8475 << ScalarOrVector << Scalar << Vector; 8476 8477 return QualType(); 8478 } 8479 8480 // Otherwise, use the generic diagnostic. 8481 Diag(Loc, DiagID) 8482 << LHSType << RHSType 8483 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8484 return QualType(); 8485 } 8486 8487 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8488 // expression. These are mainly cases where the null pointer is used as an 8489 // integer instead of a pointer. 8490 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8491 SourceLocation Loc, bool IsCompare) { 8492 // The canonical way to check for a GNU null is with isNullPointerConstant, 8493 // but we use a bit of a hack here for speed; this is a relatively 8494 // hot path, and isNullPointerConstant is slow. 8495 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8496 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8497 8498 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8499 8500 // Avoid analyzing cases where the result will either be invalid (and 8501 // diagnosed as such) or entirely valid and not something to warn about. 8502 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8503 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8504 return; 8505 8506 // Comparison operations would not make sense with a null pointer no matter 8507 // what the other expression is. 8508 if (!IsCompare) { 8509 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8510 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8511 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8512 return; 8513 } 8514 8515 // The rest of the operations only make sense with a null pointer 8516 // if the other expression is a pointer. 8517 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8518 NonNullType->canDecayToPointerType()) 8519 return; 8520 8521 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8522 << LHSNull /* LHS is NULL */ << NonNullType 8523 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8524 } 8525 8526 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8527 ExprResult &RHS, 8528 SourceLocation Loc, bool IsDiv) { 8529 // Check for division/remainder by zero. 8530 llvm::APSInt RHSValue; 8531 if (!RHS.get()->isValueDependent() && 8532 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8533 S.DiagRuntimeBehavior(Loc, RHS.get(), 8534 S.PDiag(diag::warn_remainder_division_by_zero) 8535 << IsDiv << RHS.get()->getSourceRange()); 8536 } 8537 8538 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8539 SourceLocation Loc, 8540 bool IsCompAssign, bool IsDiv) { 8541 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8542 8543 if (LHS.get()->getType()->isVectorType() || 8544 RHS.get()->getType()->isVectorType()) 8545 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8546 /*AllowBothBool*/getLangOpts().AltiVec, 8547 /*AllowBoolConversions*/false); 8548 8549 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8550 if (LHS.isInvalid() || RHS.isInvalid()) 8551 return QualType(); 8552 8553 8554 if (compType.isNull() || !compType->isArithmeticType()) 8555 return InvalidOperands(Loc, LHS, RHS); 8556 if (IsDiv) 8557 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8558 return compType; 8559 } 8560 8561 QualType Sema::CheckRemainderOperands( 8562 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8563 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8564 8565 if (LHS.get()->getType()->isVectorType() || 8566 RHS.get()->getType()->isVectorType()) { 8567 if (LHS.get()->getType()->hasIntegerRepresentation() && 8568 RHS.get()->getType()->hasIntegerRepresentation()) 8569 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8570 /*AllowBothBool*/getLangOpts().AltiVec, 8571 /*AllowBoolConversions*/false); 8572 return InvalidOperands(Loc, LHS, RHS); 8573 } 8574 8575 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8576 if (LHS.isInvalid() || RHS.isInvalid()) 8577 return QualType(); 8578 8579 if (compType.isNull() || !compType->isIntegerType()) 8580 return InvalidOperands(Loc, LHS, RHS); 8581 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8582 return compType; 8583 } 8584 8585 /// \brief Diagnose invalid arithmetic on two void pointers. 8586 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8587 Expr *LHSExpr, Expr *RHSExpr) { 8588 S.Diag(Loc, S.getLangOpts().CPlusPlus 8589 ? diag::err_typecheck_pointer_arith_void_type 8590 : diag::ext_gnu_void_ptr) 8591 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8592 << RHSExpr->getSourceRange(); 8593 } 8594 8595 /// \brief Diagnose invalid arithmetic on a void pointer. 8596 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8597 Expr *Pointer) { 8598 S.Diag(Loc, S.getLangOpts().CPlusPlus 8599 ? diag::err_typecheck_pointer_arith_void_type 8600 : diag::ext_gnu_void_ptr) 8601 << 0 /* one pointer */ << Pointer->getSourceRange(); 8602 } 8603 8604 /// \brief Diagnose invalid arithmetic on a null pointer. 8605 /// 8606 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8607 /// idiom, which we recognize as a GNU extension. 8608 /// 8609 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8610 Expr *Pointer, bool IsGNUIdiom) { 8611 if (IsGNUIdiom) 8612 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8613 << Pointer->getSourceRange(); 8614 else 8615 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8616 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8617 } 8618 8619 /// \brief Diagnose invalid arithmetic on two function pointers. 8620 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8621 Expr *LHS, Expr *RHS) { 8622 assert(LHS->getType()->isAnyPointerType()); 8623 assert(RHS->getType()->isAnyPointerType()); 8624 S.Diag(Loc, S.getLangOpts().CPlusPlus 8625 ? diag::err_typecheck_pointer_arith_function_type 8626 : diag::ext_gnu_ptr_func_arith) 8627 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8628 // We only show the second type if it differs from the first. 8629 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8630 RHS->getType()) 8631 << RHS->getType()->getPointeeType() 8632 << LHS->getSourceRange() << RHS->getSourceRange(); 8633 } 8634 8635 /// \brief Diagnose invalid arithmetic on a function pointer. 8636 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8637 Expr *Pointer) { 8638 assert(Pointer->getType()->isAnyPointerType()); 8639 S.Diag(Loc, S.getLangOpts().CPlusPlus 8640 ? diag::err_typecheck_pointer_arith_function_type 8641 : diag::ext_gnu_ptr_func_arith) 8642 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8643 << 0 /* one pointer, so only one type */ 8644 << Pointer->getSourceRange(); 8645 } 8646 8647 /// \brief Emit error if Operand is incomplete pointer type 8648 /// 8649 /// \returns True if pointer has incomplete type 8650 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8651 Expr *Operand) { 8652 QualType ResType = Operand->getType(); 8653 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8654 ResType = ResAtomicType->getValueType(); 8655 8656 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8657 QualType PointeeTy = ResType->getPointeeType(); 8658 return S.RequireCompleteType(Loc, PointeeTy, 8659 diag::err_typecheck_arithmetic_incomplete_type, 8660 PointeeTy, Operand->getSourceRange()); 8661 } 8662 8663 /// \brief Check the validity of an arithmetic pointer operand. 8664 /// 8665 /// If the operand has pointer type, this code will check for pointer types 8666 /// which are invalid in arithmetic operations. These will be diagnosed 8667 /// appropriately, including whether or not the use is supported as an 8668 /// extension. 8669 /// 8670 /// \returns True when the operand is valid to use (even if as an extension). 8671 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8672 Expr *Operand) { 8673 QualType ResType = Operand->getType(); 8674 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8675 ResType = ResAtomicType->getValueType(); 8676 8677 if (!ResType->isAnyPointerType()) return true; 8678 8679 QualType PointeeTy = ResType->getPointeeType(); 8680 if (PointeeTy->isVoidType()) { 8681 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8682 return !S.getLangOpts().CPlusPlus; 8683 } 8684 if (PointeeTy->isFunctionType()) { 8685 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8686 return !S.getLangOpts().CPlusPlus; 8687 } 8688 8689 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8690 8691 return true; 8692 } 8693 8694 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8695 /// operands. 8696 /// 8697 /// This routine will diagnose any invalid arithmetic on pointer operands much 8698 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8699 /// for emitting a single diagnostic even for operations where both LHS and RHS 8700 /// are (potentially problematic) pointers. 8701 /// 8702 /// \returns True when the operand is valid to use (even if as an extension). 8703 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8704 Expr *LHSExpr, Expr *RHSExpr) { 8705 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8706 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8707 if (!isLHSPointer && !isRHSPointer) return true; 8708 8709 QualType LHSPointeeTy, RHSPointeeTy; 8710 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8711 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8712 8713 // if both are pointers check if operation is valid wrt address spaces 8714 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8715 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8716 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8717 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8718 S.Diag(Loc, 8719 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8720 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8721 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8722 return false; 8723 } 8724 } 8725 8726 // Check for arithmetic on pointers to incomplete types. 8727 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8728 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8729 if (isLHSVoidPtr || isRHSVoidPtr) { 8730 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8731 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8732 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8733 8734 return !S.getLangOpts().CPlusPlus; 8735 } 8736 8737 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8738 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8739 if (isLHSFuncPtr || isRHSFuncPtr) { 8740 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8741 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8742 RHSExpr); 8743 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8744 8745 return !S.getLangOpts().CPlusPlus; 8746 } 8747 8748 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8749 return false; 8750 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8751 return false; 8752 8753 return true; 8754 } 8755 8756 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8757 /// literal. 8758 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8759 Expr *LHSExpr, Expr *RHSExpr) { 8760 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8761 Expr* IndexExpr = RHSExpr; 8762 if (!StrExpr) { 8763 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8764 IndexExpr = LHSExpr; 8765 } 8766 8767 bool IsStringPlusInt = StrExpr && 8768 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8769 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8770 return; 8771 8772 llvm::APSInt index; 8773 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8774 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8775 if (index.isNonNegative() && 8776 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8777 index.isUnsigned())) 8778 return; 8779 } 8780 8781 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8782 Self.Diag(OpLoc, diag::warn_string_plus_int) 8783 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8784 8785 // Only print a fixit for "str" + int, not for int + "str". 8786 if (IndexExpr == RHSExpr) { 8787 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8788 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8789 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8790 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8791 << FixItHint::CreateInsertion(EndLoc, "]"); 8792 } else 8793 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8794 } 8795 8796 /// \brief Emit a warning when adding a char literal to a string. 8797 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8798 Expr *LHSExpr, Expr *RHSExpr) { 8799 const Expr *StringRefExpr = LHSExpr; 8800 const CharacterLiteral *CharExpr = 8801 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8802 8803 if (!CharExpr) { 8804 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8805 StringRefExpr = RHSExpr; 8806 } 8807 8808 if (!CharExpr || !StringRefExpr) 8809 return; 8810 8811 const QualType StringType = StringRefExpr->getType(); 8812 8813 // Return if not a PointerType. 8814 if (!StringType->isAnyPointerType()) 8815 return; 8816 8817 // Return if not a CharacterType. 8818 if (!StringType->getPointeeType()->isAnyCharacterType()) 8819 return; 8820 8821 ASTContext &Ctx = Self.getASTContext(); 8822 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8823 8824 const QualType CharType = CharExpr->getType(); 8825 if (!CharType->isAnyCharacterType() && 8826 CharType->isIntegerType() && 8827 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8828 Self.Diag(OpLoc, diag::warn_string_plus_char) 8829 << DiagRange << Ctx.CharTy; 8830 } else { 8831 Self.Diag(OpLoc, diag::warn_string_plus_char) 8832 << DiagRange << CharExpr->getType(); 8833 } 8834 8835 // Only print a fixit for str + char, not for char + str. 8836 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8837 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8838 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8839 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8840 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8841 << FixItHint::CreateInsertion(EndLoc, "]"); 8842 } else { 8843 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8844 } 8845 } 8846 8847 /// \brief Emit error when two pointers are incompatible. 8848 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8849 Expr *LHSExpr, Expr *RHSExpr) { 8850 assert(LHSExpr->getType()->isAnyPointerType()); 8851 assert(RHSExpr->getType()->isAnyPointerType()); 8852 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8853 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8854 << RHSExpr->getSourceRange(); 8855 } 8856 8857 // C99 6.5.6 8858 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8859 SourceLocation Loc, BinaryOperatorKind Opc, 8860 QualType* CompLHSTy) { 8861 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8862 8863 if (LHS.get()->getType()->isVectorType() || 8864 RHS.get()->getType()->isVectorType()) { 8865 QualType compType = CheckVectorOperands( 8866 LHS, RHS, Loc, CompLHSTy, 8867 /*AllowBothBool*/getLangOpts().AltiVec, 8868 /*AllowBoolConversions*/getLangOpts().ZVector); 8869 if (CompLHSTy) *CompLHSTy = compType; 8870 return compType; 8871 } 8872 8873 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8874 if (LHS.isInvalid() || RHS.isInvalid()) 8875 return QualType(); 8876 8877 // Diagnose "string literal" '+' int and string '+' "char literal". 8878 if (Opc == BO_Add) { 8879 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8880 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8881 } 8882 8883 // handle the common case first (both operands are arithmetic). 8884 if (!compType.isNull() && compType->isArithmeticType()) { 8885 if (CompLHSTy) *CompLHSTy = compType; 8886 return compType; 8887 } 8888 8889 // Type-checking. Ultimately the pointer's going to be in PExp; 8890 // note that we bias towards the LHS being the pointer. 8891 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8892 8893 bool isObjCPointer; 8894 if (PExp->getType()->isPointerType()) { 8895 isObjCPointer = false; 8896 } else if (PExp->getType()->isObjCObjectPointerType()) { 8897 isObjCPointer = true; 8898 } else { 8899 std::swap(PExp, IExp); 8900 if (PExp->getType()->isPointerType()) { 8901 isObjCPointer = false; 8902 } else if (PExp->getType()->isObjCObjectPointerType()) { 8903 isObjCPointer = true; 8904 } else { 8905 return InvalidOperands(Loc, LHS, RHS); 8906 } 8907 } 8908 assert(PExp->getType()->isAnyPointerType()); 8909 8910 if (!IExp->getType()->isIntegerType()) 8911 return InvalidOperands(Loc, LHS, RHS); 8912 8913 // Adding to a null pointer results in undefined behavior. 8914 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8915 Context, Expr::NPC_ValueDependentIsNotNull)) { 8916 // In C++ adding zero to a null pointer is defined. 8917 llvm::APSInt KnownVal; 8918 if (!getLangOpts().CPlusPlus || 8919 (!IExp->isValueDependent() && 8920 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8921 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8922 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8923 Context, BO_Add, PExp, IExp); 8924 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8925 } 8926 } 8927 8928 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8929 return QualType(); 8930 8931 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8932 return QualType(); 8933 8934 // Check array bounds for pointer arithemtic 8935 CheckArrayAccess(PExp, IExp); 8936 8937 if (CompLHSTy) { 8938 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8939 if (LHSTy.isNull()) { 8940 LHSTy = LHS.get()->getType(); 8941 if (LHSTy->isPromotableIntegerType()) 8942 LHSTy = Context.getPromotedIntegerType(LHSTy); 8943 } 8944 *CompLHSTy = LHSTy; 8945 } 8946 8947 return PExp->getType(); 8948 } 8949 8950 // C99 6.5.6 8951 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8952 SourceLocation Loc, 8953 QualType* CompLHSTy) { 8954 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8955 8956 if (LHS.get()->getType()->isVectorType() || 8957 RHS.get()->getType()->isVectorType()) { 8958 QualType compType = CheckVectorOperands( 8959 LHS, RHS, Loc, CompLHSTy, 8960 /*AllowBothBool*/getLangOpts().AltiVec, 8961 /*AllowBoolConversions*/getLangOpts().ZVector); 8962 if (CompLHSTy) *CompLHSTy = compType; 8963 return compType; 8964 } 8965 8966 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8967 if (LHS.isInvalid() || RHS.isInvalid()) 8968 return QualType(); 8969 8970 // Enforce type constraints: C99 6.5.6p3. 8971 8972 // Handle the common case first (both operands are arithmetic). 8973 if (!compType.isNull() && compType->isArithmeticType()) { 8974 if (CompLHSTy) *CompLHSTy = compType; 8975 return compType; 8976 } 8977 8978 // Either ptr - int or ptr - ptr. 8979 if (LHS.get()->getType()->isAnyPointerType()) { 8980 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8981 8982 // Diagnose bad cases where we step over interface counts. 8983 if (LHS.get()->getType()->isObjCObjectPointerType() && 8984 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8985 return QualType(); 8986 8987 // The result type of a pointer-int computation is the pointer type. 8988 if (RHS.get()->getType()->isIntegerType()) { 8989 // Subtracting from a null pointer should produce a warning. 8990 // The last argument to the diagnose call says this doesn't match the 8991 // GNU int-to-pointer idiom. 8992 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 8993 Expr::NPC_ValueDependentIsNotNull)) { 8994 // In C++ adding zero to a null pointer is defined. 8995 llvm::APSInt KnownVal; 8996 if (!getLangOpts().CPlusPlus || 8997 (!RHS.get()->isValueDependent() && 8998 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8999 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9000 } 9001 } 9002 9003 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9004 return QualType(); 9005 9006 // Check array bounds for pointer arithemtic 9007 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9008 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9009 9010 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9011 return LHS.get()->getType(); 9012 } 9013 9014 // Handle pointer-pointer subtractions. 9015 if (const PointerType *RHSPTy 9016 = RHS.get()->getType()->getAs<PointerType>()) { 9017 QualType rpointee = RHSPTy->getPointeeType(); 9018 9019 if (getLangOpts().CPlusPlus) { 9020 // Pointee types must be the same: C++ [expr.add] 9021 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9022 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9023 } 9024 } else { 9025 // Pointee types must be compatible C99 6.5.6p3 9026 if (!Context.typesAreCompatible( 9027 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9028 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9029 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9030 return QualType(); 9031 } 9032 } 9033 9034 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9035 LHS.get(), RHS.get())) 9036 return QualType(); 9037 9038 // FIXME: Add warnings for nullptr - ptr. 9039 9040 // The pointee type may have zero size. As an extension, a structure or 9041 // union may have zero size or an array may have zero length. In this 9042 // case subtraction does not make sense. 9043 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9044 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9045 if (ElementSize.isZero()) { 9046 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9047 << rpointee.getUnqualifiedType() 9048 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9049 } 9050 } 9051 9052 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9053 return Context.getPointerDiffType(); 9054 } 9055 } 9056 9057 return InvalidOperands(Loc, LHS, RHS); 9058 } 9059 9060 static bool isScopedEnumerationType(QualType T) { 9061 if (const EnumType *ET = T->getAs<EnumType>()) 9062 return ET->getDecl()->isScoped(); 9063 return false; 9064 } 9065 9066 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9067 SourceLocation Loc, BinaryOperatorKind Opc, 9068 QualType LHSType) { 9069 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9070 // so skip remaining warnings as we don't want to modify values within Sema. 9071 if (S.getLangOpts().OpenCL) 9072 return; 9073 9074 llvm::APSInt Right; 9075 // Check right/shifter operand 9076 if (RHS.get()->isValueDependent() || 9077 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9078 return; 9079 9080 if (Right.isNegative()) { 9081 S.DiagRuntimeBehavior(Loc, RHS.get(), 9082 S.PDiag(diag::warn_shift_negative) 9083 << RHS.get()->getSourceRange()); 9084 return; 9085 } 9086 llvm::APInt LeftBits(Right.getBitWidth(), 9087 S.Context.getTypeSize(LHS.get()->getType())); 9088 if (Right.uge(LeftBits)) { 9089 S.DiagRuntimeBehavior(Loc, RHS.get(), 9090 S.PDiag(diag::warn_shift_gt_typewidth) 9091 << RHS.get()->getSourceRange()); 9092 return; 9093 } 9094 if (Opc != BO_Shl) 9095 return; 9096 9097 // When left shifting an ICE which is signed, we can check for overflow which 9098 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9099 // integers have defined behavior modulo one more than the maximum value 9100 // representable in the result type, so never warn for those. 9101 llvm::APSInt Left; 9102 if (LHS.get()->isValueDependent() || 9103 LHSType->hasUnsignedIntegerRepresentation() || 9104 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9105 return; 9106 9107 // If LHS does not have a signed type and non-negative value 9108 // then, the behavior is undefined. Warn about it. 9109 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9110 S.DiagRuntimeBehavior(Loc, LHS.get(), 9111 S.PDiag(diag::warn_shift_lhs_negative) 9112 << LHS.get()->getSourceRange()); 9113 return; 9114 } 9115 9116 llvm::APInt ResultBits = 9117 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9118 if (LeftBits.uge(ResultBits)) 9119 return; 9120 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9121 Result = Result.shl(Right); 9122 9123 // Print the bit representation of the signed integer as an unsigned 9124 // hexadecimal number. 9125 SmallString<40> HexResult; 9126 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9127 9128 // If we are only missing a sign bit, this is less likely to result in actual 9129 // bugs -- if the result is cast back to an unsigned type, it will have the 9130 // expected value. Thus we place this behind a different warning that can be 9131 // turned off separately if needed. 9132 if (LeftBits == ResultBits - 1) { 9133 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9134 << HexResult << LHSType 9135 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9136 return; 9137 } 9138 9139 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9140 << HexResult.str() << Result.getMinSignedBits() << LHSType 9141 << Left.getBitWidth() << LHS.get()->getSourceRange() 9142 << RHS.get()->getSourceRange(); 9143 } 9144 9145 /// \brief Return the resulting type when a vector is shifted 9146 /// by a scalar or vector shift amount. 9147 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9148 SourceLocation Loc, bool IsCompAssign) { 9149 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9150 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9151 !LHS.get()->getType()->isVectorType()) { 9152 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9153 << RHS.get()->getType() << LHS.get()->getType() 9154 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9155 return QualType(); 9156 } 9157 9158 if (!IsCompAssign) { 9159 LHS = S.UsualUnaryConversions(LHS.get()); 9160 if (LHS.isInvalid()) return QualType(); 9161 } 9162 9163 RHS = S.UsualUnaryConversions(RHS.get()); 9164 if (RHS.isInvalid()) return QualType(); 9165 9166 QualType LHSType = LHS.get()->getType(); 9167 // Note that LHS might be a scalar because the routine calls not only in 9168 // OpenCL case. 9169 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9170 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9171 9172 // Note that RHS might not be a vector. 9173 QualType RHSType = RHS.get()->getType(); 9174 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9175 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9176 9177 // The operands need to be integers. 9178 if (!LHSEleType->isIntegerType()) { 9179 S.Diag(Loc, diag::err_typecheck_expect_int) 9180 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9181 return QualType(); 9182 } 9183 9184 if (!RHSEleType->isIntegerType()) { 9185 S.Diag(Loc, diag::err_typecheck_expect_int) 9186 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9187 return QualType(); 9188 } 9189 9190 if (!LHSVecTy) { 9191 assert(RHSVecTy); 9192 if (IsCompAssign) 9193 return RHSType; 9194 if (LHSEleType != RHSEleType) { 9195 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9196 LHSEleType = RHSEleType; 9197 } 9198 QualType VecTy = 9199 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9200 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9201 LHSType = VecTy; 9202 } else if (RHSVecTy) { 9203 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9204 // are applied component-wise. So if RHS is a vector, then ensure 9205 // that the number of elements is the same as LHS... 9206 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9207 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9208 << LHS.get()->getType() << RHS.get()->getType() 9209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9210 return QualType(); 9211 } 9212 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9213 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9214 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9215 if (LHSBT != RHSBT && 9216 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9217 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9218 << LHS.get()->getType() << RHS.get()->getType() 9219 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9220 } 9221 } 9222 } else { 9223 // ...else expand RHS to match the number of elements in LHS. 9224 QualType VecTy = 9225 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9226 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9227 } 9228 9229 return LHSType; 9230 } 9231 9232 // C99 6.5.7 9233 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9234 SourceLocation Loc, BinaryOperatorKind Opc, 9235 bool IsCompAssign) { 9236 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9237 9238 // Vector shifts promote their scalar inputs to vector type. 9239 if (LHS.get()->getType()->isVectorType() || 9240 RHS.get()->getType()->isVectorType()) { 9241 if (LangOpts.ZVector) { 9242 // The shift operators for the z vector extensions work basically 9243 // like general shifts, except that neither the LHS nor the RHS is 9244 // allowed to be a "vector bool". 9245 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9246 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9247 return InvalidOperands(Loc, LHS, RHS); 9248 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9249 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9250 return InvalidOperands(Loc, LHS, RHS); 9251 } 9252 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9253 } 9254 9255 // Shifts don't perform usual arithmetic conversions, they just do integer 9256 // promotions on each operand. C99 6.5.7p3 9257 9258 // For the LHS, do usual unary conversions, but then reset them away 9259 // if this is a compound assignment. 9260 ExprResult OldLHS = LHS; 9261 LHS = UsualUnaryConversions(LHS.get()); 9262 if (LHS.isInvalid()) 9263 return QualType(); 9264 QualType LHSType = LHS.get()->getType(); 9265 if (IsCompAssign) LHS = OldLHS; 9266 9267 // The RHS is simpler. 9268 RHS = UsualUnaryConversions(RHS.get()); 9269 if (RHS.isInvalid()) 9270 return QualType(); 9271 QualType RHSType = RHS.get()->getType(); 9272 9273 // C99 6.5.7p2: Each of the operands shall have integer type. 9274 if (!LHSType->hasIntegerRepresentation() || 9275 !RHSType->hasIntegerRepresentation()) 9276 return InvalidOperands(Loc, LHS, RHS); 9277 9278 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9279 // hasIntegerRepresentation() above instead of this. 9280 if (isScopedEnumerationType(LHSType) || 9281 isScopedEnumerationType(RHSType)) { 9282 return InvalidOperands(Loc, LHS, RHS); 9283 } 9284 // Sanity-check shift operands 9285 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9286 9287 // "The type of the result is that of the promoted left operand." 9288 return LHSType; 9289 } 9290 9291 static bool IsWithinTemplateSpecialization(Decl *D) { 9292 if (DeclContext *DC = D->getDeclContext()) { 9293 if (isa<ClassTemplateSpecializationDecl>(DC)) 9294 return true; 9295 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 9296 return FD->isFunctionTemplateSpecialization(); 9297 } 9298 return false; 9299 } 9300 9301 /// If two different enums are compared, raise a warning. 9302 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9303 Expr *RHS) { 9304 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9305 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9306 9307 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9308 if (!LHSEnumType) 9309 return; 9310 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9311 if (!RHSEnumType) 9312 return; 9313 9314 // Ignore anonymous enums. 9315 if (!LHSEnumType->getDecl()->getIdentifier() && 9316 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9317 return; 9318 if (!RHSEnumType->getDecl()->getIdentifier() && 9319 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9320 return; 9321 9322 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9323 return; 9324 9325 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9326 << LHSStrippedType << RHSStrippedType 9327 << LHS->getSourceRange() << RHS->getSourceRange(); 9328 } 9329 9330 /// \brief Diagnose bad pointer comparisons. 9331 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9332 ExprResult &LHS, ExprResult &RHS, 9333 bool IsError) { 9334 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9335 : diag::ext_typecheck_comparison_of_distinct_pointers) 9336 << LHS.get()->getType() << RHS.get()->getType() 9337 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9338 } 9339 9340 /// \brief Returns false if the pointers are converted to a composite type, 9341 /// true otherwise. 9342 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9343 ExprResult &LHS, ExprResult &RHS) { 9344 // C++ [expr.rel]p2: 9345 // [...] Pointer conversions (4.10) and qualification 9346 // conversions (4.4) are performed on pointer operands (or on 9347 // a pointer operand and a null pointer constant) to bring 9348 // them to their composite pointer type. [...] 9349 // 9350 // C++ [expr.eq]p1 uses the same notion for (in)equality 9351 // comparisons of pointers. 9352 9353 QualType LHSType = LHS.get()->getType(); 9354 QualType RHSType = RHS.get()->getType(); 9355 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9356 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9357 9358 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9359 if (T.isNull()) { 9360 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9361 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9362 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9363 else 9364 S.InvalidOperands(Loc, LHS, RHS); 9365 return true; 9366 } 9367 9368 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9369 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9370 return false; 9371 } 9372 9373 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9374 ExprResult &LHS, 9375 ExprResult &RHS, 9376 bool IsError) { 9377 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9378 : diag::ext_typecheck_comparison_of_fptr_to_void) 9379 << LHS.get()->getType() << RHS.get()->getType() 9380 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9381 } 9382 9383 static bool isObjCObjectLiteral(ExprResult &E) { 9384 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9385 case Stmt::ObjCArrayLiteralClass: 9386 case Stmt::ObjCDictionaryLiteralClass: 9387 case Stmt::ObjCStringLiteralClass: 9388 case Stmt::ObjCBoxedExprClass: 9389 return true; 9390 default: 9391 // Note that ObjCBoolLiteral is NOT an object literal! 9392 return false; 9393 } 9394 } 9395 9396 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9397 const ObjCObjectPointerType *Type = 9398 LHS->getType()->getAs<ObjCObjectPointerType>(); 9399 9400 // If this is not actually an Objective-C object, bail out. 9401 if (!Type) 9402 return false; 9403 9404 // Get the LHS object's interface type. 9405 QualType InterfaceType = Type->getPointeeType(); 9406 9407 // If the RHS isn't an Objective-C object, bail out. 9408 if (!RHS->getType()->isObjCObjectPointerType()) 9409 return false; 9410 9411 // Try to find the -isEqual: method. 9412 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9413 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9414 InterfaceType, 9415 /*instance=*/true); 9416 if (!Method) { 9417 if (Type->isObjCIdType()) { 9418 // For 'id', just check the global pool. 9419 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9420 /*receiverId=*/true); 9421 } else { 9422 // Check protocols. 9423 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9424 /*instance=*/true); 9425 } 9426 } 9427 9428 if (!Method) 9429 return false; 9430 9431 QualType T = Method->parameters()[0]->getType(); 9432 if (!T->isObjCObjectPointerType()) 9433 return false; 9434 9435 QualType R = Method->getReturnType(); 9436 if (!R->isScalarType()) 9437 return false; 9438 9439 return true; 9440 } 9441 9442 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9443 FromE = FromE->IgnoreParenImpCasts(); 9444 switch (FromE->getStmtClass()) { 9445 default: 9446 break; 9447 case Stmt::ObjCStringLiteralClass: 9448 // "string literal" 9449 return LK_String; 9450 case Stmt::ObjCArrayLiteralClass: 9451 // "array literal" 9452 return LK_Array; 9453 case Stmt::ObjCDictionaryLiteralClass: 9454 // "dictionary literal" 9455 return LK_Dictionary; 9456 case Stmt::BlockExprClass: 9457 return LK_Block; 9458 case Stmt::ObjCBoxedExprClass: { 9459 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9460 switch (Inner->getStmtClass()) { 9461 case Stmt::IntegerLiteralClass: 9462 case Stmt::FloatingLiteralClass: 9463 case Stmt::CharacterLiteralClass: 9464 case Stmt::ObjCBoolLiteralExprClass: 9465 case Stmt::CXXBoolLiteralExprClass: 9466 // "numeric literal" 9467 return LK_Numeric; 9468 case Stmt::ImplicitCastExprClass: { 9469 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9470 // Boolean literals can be represented by implicit casts. 9471 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9472 return LK_Numeric; 9473 break; 9474 } 9475 default: 9476 break; 9477 } 9478 return LK_Boxed; 9479 } 9480 } 9481 return LK_None; 9482 } 9483 9484 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9485 ExprResult &LHS, ExprResult &RHS, 9486 BinaryOperator::Opcode Opc){ 9487 Expr *Literal; 9488 Expr *Other; 9489 if (isObjCObjectLiteral(LHS)) { 9490 Literal = LHS.get(); 9491 Other = RHS.get(); 9492 } else { 9493 Literal = RHS.get(); 9494 Other = LHS.get(); 9495 } 9496 9497 // Don't warn on comparisons against nil. 9498 Other = Other->IgnoreParenCasts(); 9499 if (Other->isNullPointerConstant(S.getASTContext(), 9500 Expr::NPC_ValueDependentIsNotNull)) 9501 return; 9502 9503 // This should be kept in sync with warn_objc_literal_comparison. 9504 // LK_String should always be after the other literals, since it has its own 9505 // warning flag. 9506 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9507 assert(LiteralKind != Sema::LK_Block); 9508 if (LiteralKind == Sema::LK_None) { 9509 llvm_unreachable("Unknown Objective-C object literal kind"); 9510 } 9511 9512 if (LiteralKind == Sema::LK_String) 9513 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9514 << Literal->getSourceRange(); 9515 else 9516 S.Diag(Loc, diag::warn_objc_literal_comparison) 9517 << LiteralKind << Literal->getSourceRange(); 9518 9519 if (BinaryOperator::isEqualityOp(Opc) && 9520 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9521 SourceLocation Start = LHS.get()->getLocStart(); 9522 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9523 CharSourceRange OpRange = 9524 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9525 9526 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9527 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9528 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9529 << FixItHint::CreateInsertion(End, "]"); 9530 } 9531 } 9532 9533 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9534 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9535 ExprResult &RHS, SourceLocation Loc, 9536 BinaryOperatorKind Opc) { 9537 // Check that left hand side is !something. 9538 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9539 if (!UO || UO->getOpcode() != UO_LNot) return; 9540 9541 // Only check if the right hand side is non-bool arithmetic type. 9542 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9543 9544 // Make sure that the something in !something is not bool. 9545 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9546 if (SubExpr->isKnownToHaveBooleanValue()) return; 9547 9548 // Emit warning. 9549 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9550 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9551 << Loc << IsBitwiseOp; 9552 9553 // First note suggest !(x < y) 9554 SourceLocation FirstOpen = SubExpr->getLocStart(); 9555 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9556 FirstClose = S.getLocForEndOfToken(FirstClose); 9557 if (FirstClose.isInvalid()) 9558 FirstOpen = SourceLocation(); 9559 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9560 << IsBitwiseOp 9561 << FixItHint::CreateInsertion(FirstOpen, "(") 9562 << FixItHint::CreateInsertion(FirstClose, ")"); 9563 9564 // Second note suggests (!x) < y 9565 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9566 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9567 SecondClose = S.getLocForEndOfToken(SecondClose); 9568 if (SecondClose.isInvalid()) 9569 SecondOpen = SourceLocation(); 9570 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9571 << FixItHint::CreateInsertion(SecondOpen, "(") 9572 << FixItHint::CreateInsertion(SecondClose, ")"); 9573 } 9574 9575 // Get the decl for a simple expression: a reference to a variable, 9576 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9577 static ValueDecl *getCompareDecl(Expr *E) { 9578 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9579 return DR->getDecl(); 9580 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9581 if (Ivar->isFreeIvar()) 9582 return Ivar->getDecl(); 9583 } 9584 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9585 if (Mem->isImplicitAccess()) 9586 return Mem->getMemberDecl(); 9587 } 9588 return nullptr; 9589 } 9590 9591 // C99 6.5.8, C++ [expr.rel] 9592 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9593 SourceLocation Loc, BinaryOperatorKind Opc, 9594 bool IsRelational) { 9595 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9596 9597 // Handle vector comparisons separately. 9598 if (LHS.get()->getType()->isVectorType() || 9599 RHS.get()->getType()->isVectorType()) 9600 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9601 9602 QualType LHSType = LHS.get()->getType(); 9603 QualType RHSType = RHS.get()->getType(); 9604 9605 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9606 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9607 9608 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9609 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9610 9611 if (!LHSType->hasFloatingRepresentation() && 9612 !(LHSType->isBlockPointerType() && IsRelational) && 9613 !LHS.get()->getLocStart().isMacroID() && 9614 !RHS.get()->getLocStart().isMacroID() && 9615 !inTemplateInstantiation()) { 9616 // For non-floating point types, check for self-comparisons of the form 9617 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9618 // often indicate logic errors in the program. 9619 // 9620 // NOTE: Don't warn about comparison expressions resulting from macro 9621 // expansion. Also don't warn about comparisons which are only self 9622 // comparisons within a template specialization. The warnings should catch 9623 // obvious cases in the definition of the template anyways. The idea is to 9624 // warn when the typed comparison operator will always evaluate to the same 9625 // result. 9626 ValueDecl *DL = getCompareDecl(LHSStripped); 9627 ValueDecl *DR = getCompareDecl(RHSStripped); 9628 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9629 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9630 << 0 // self- 9631 << (Opc == BO_EQ 9632 || Opc == BO_LE 9633 || Opc == BO_GE)); 9634 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9635 !DL->getType()->isReferenceType() && 9636 !DR->getType()->isReferenceType()) { 9637 // what is it always going to eval to? 9638 char always_evals_to; 9639 switch(Opc) { 9640 case BO_EQ: // e.g. array1 == array2 9641 always_evals_to = 0; // false 9642 break; 9643 case BO_NE: // e.g. array1 != array2 9644 always_evals_to = 1; // true 9645 break; 9646 default: 9647 // best we can say is 'a constant' 9648 always_evals_to = 2; // e.g. array1 <= array2 9649 break; 9650 } 9651 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9652 << 1 // array 9653 << always_evals_to); 9654 } 9655 9656 if (isa<CastExpr>(LHSStripped)) 9657 LHSStripped = LHSStripped->IgnoreParenCasts(); 9658 if (isa<CastExpr>(RHSStripped)) 9659 RHSStripped = RHSStripped->IgnoreParenCasts(); 9660 9661 // Warn about comparisons against a string constant (unless the other 9662 // operand is null), the user probably wants strcmp. 9663 Expr *literalString = nullptr; 9664 Expr *literalStringStripped = nullptr; 9665 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9666 !RHSStripped->isNullPointerConstant(Context, 9667 Expr::NPC_ValueDependentIsNull)) { 9668 literalString = LHS.get(); 9669 literalStringStripped = LHSStripped; 9670 } else if ((isa<StringLiteral>(RHSStripped) || 9671 isa<ObjCEncodeExpr>(RHSStripped)) && 9672 !LHSStripped->isNullPointerConstant(Context, 9673 Expr::NPC_ValueDependentIsNull)) { 9674 literalString = RHS.get(); 9675 literalStringStripped = RHSStripped; 9676 } 9677 9678 if (literalString) { 9679 DiagRuntimeBehavior(Loc, nullptr, 9680 PDiag(diag::warn_stringcompare) 9681 << isa<ObjCEncodeExpr>(literalStringStripped) 9682 << literalString->getSourceRange()); 9683 } 9684 } 9685 9686 // C99 6.5.8p3 / C99 6.5.9p4 9687 UsualArithmeticConversions(LHS, RHS); 9688 if (LHS.isInvalid() || RHS.isInvalid()) 9689 return QualType(); 9690 9691 LHSType = LHS.get()->getType(); 9692 RHSType = RHS.get()->getType(); 9693 9694 // The result of comparisons is 'bool' in C++, 'int' in C. 9695 QualType ResultTy = Context.getLogicalOperationType(); 9696 9697 if (IsRelational) { 9698 if (LHSType->isRealType() && RHSType->isRealType()) 9699 return ResultTy; 9700 } else { 9701 // Check for comparisons of floating point operands using != and ==. 9702 if (LHSType->hasFloatingRepresentation()) 9703 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9704 9705 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9706 return ResultTy; 9707 } 9708 9709 const Expr::NullPointerConstantKind LHSNullKind = 9710 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9711 const Expr::NullPointerConstantKind RHSNullKind = 9712 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9713 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9714 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9715 9716 if (!IsRelational && LHSIsNull != RHSIsNull) { 9717 bool IsEquality = Opc == BO_EQ; 9718 if (RHSIsNull) 9719 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9720 RHS.get()->getSourceRange()); 9721 else 9722 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9723 LHS.get()->getSourceRange()); 9724 } 9725 9726 if ((LHSType->isIntegerType() && !LHSIsNull) || 9727 (RHSType->isIntegerType() && !RHSIsNull)) { 9728 // Skip normal pointer conversion checks in this case; we have better 9729 // diagnostics for this below. 9730 } else if (getLangOpts().CPlusPlus) { 9731 // Equality comparison of a function pointer to a void pointer is invalid, 9732 // but we allow it as an extension. 9733 // FIXME: If we really want to allow this, should it be part of composite 9734 // pointer type computation so it works in conditionals too? 9735 if (!IsRelational && 9736 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9737 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9738 // This is a gcc extension compatibility comparison. 9739 // In a SFINAE context, we treat this as a hard error to maintain 9740 // conformance with the C++ standard. 9741 diagnoseFunctionPointerToVoidComparison( 9742 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9743 9744 if (isSFINAEContext()) 9745 return QualType(); 9746 9747 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9748 return ResultTy; 9749 } 9750 9751 // C++ [expr.eq]p2: 9752 // If at least one operand is a pointer [...] bring them to their 9753 // composite pointer type. 9754 // C++ [expr.rel]p2: 9755 // If both operands are pointers, [...] bring them to their composite 9756 // pointer type. 9757 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9758 (IsRelational ? 2 : 1) && 9759 (!LangOpts.ObjCAutoRefCount || 9760 !(LHSType->isObjCObjectPointerType() || 9761 RHSType->isObjCObjectPointerType()))) { 9762 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9763 return QualType(); 9764 else 9765 return ResultTy; 9766 } 9767 } else if (LHSType->isPointerType() && 9768 RHSType->isPointerType()) { // C99 6.5.8p2 9769 // All of the following pointer-related warnings are GCC extensions, except 9770 // when handling null pointer constants. 9771 QualType LCanPointeeTy = 9772 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9773 QualType RCanPointeeTy = 9774 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9775 9776 // C99 6.5.9p2 and C99 6.5.8p2 9777 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9778 RCanPointeeTy.getUnqualifiedType())) { 9779 // Valid unless a relational comparison of function pointers 9780 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9781 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9782 << LHSType << RHSType << LHS.get()->getSourceRange() 9783 << RHS.get()->getSourceRange(); 9784 } 9785 } else if (!IsRelational && 9786 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9787 // Valid unless comparison between non-null pointer and function pointer 9788 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9789 && !LHSIsNull && !RHSIsNull) 9790 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9791 /*isError*/false); 9792 } else { 9793 // Invalid 9794 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9795 } 9796 if (LCanPointeeTy != RCanPointeeTy) { 9797 // Treat NULL constant as a special case in OpenCL. 9798 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9799 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9800 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9801 Diag(Loc, 9802 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9803 << LHSType << RHSType << 0 /* comparison */ 9804 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9805 } 9806 } 9807 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9808 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9809 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9810 : CK_BitCast; 9811 if (LHSIsNull && !RHSIsNull) 9812 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9813 else 9814 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9815 } 9816 return ResultTy; 9817 } 9818 9819 if (getLangOpts().CPlusPlus) { 9820 // C++ [expr.eq]p4: 9821 // Two operands of type std::nullptr_t or one operand of type 9822 // std::nullptr_t and the other a null pointer constant compare equal. 9823 if (!IsRelational && LHSIsNull && RHSIsNull) { 9824 if (LHSType->isNullPtrType()) { 9825 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9826 return ResultTy; 9827 } 9828 if (RHSType->isNullPtrType()) { 9829 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9830 return ResultTy; 9831 } 9832 } 9833 9834 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9835 // These aren't covered by the composite pointer type rules. 9836 if (!IsRelational && RHSType->isNullPtrType() && 9837 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9838 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9839 return ResultTy; 9840 } 9841 if (!IsRelational && LHSType->isNullPtrType() && 9842 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9843 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9844 return ResultTy; 9845 } 9846 9847 if (IsRelational && 9848 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9849 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9850 // HACK: Relational comparison of nullptr_t against a pointer type is 9851 // invalid per DR583, but we allow it within std::less<> and friends, 9852 // since otherwise common uses of it break. 9853 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9854 // friends to have std::nullptr_t overload candidates. 9855 DeclContext *DC = CurContext; 9856 if (isa<FunctionDecl>(DC)) 9857 DC = DC->getParent(); 9858 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9859 if (CTSD->isInStdNamespace() && 9860 llvm::StringSwitch<bool>(CTSD->getName()) 9861 .Cases("less", "less_equal", "greater", "greater_equal", true) 9862 .Default(false)) { 9863 if (RHSType->isNullPtrType()) 9864 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9865 else 9866 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9867 return ResultTy; 9868 } 9869 } 9870 } 9871 9872 // C++ [expr.eq]p2: 9873 // If at least one operand is a pointer to member, [...] bring them to 9874 // their composite pointer type. 9875 if (!IsRelational && 9876 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9877 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9878 return QualType(); 9879 else 9880 return ResultTy; 9881 } 9882 9883 // Handle scoped enumeration types specifically, since they don't promote 9884 // to integers. 9885 if (LHS.get()->getType()->isEnumeralType() && 9886 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9887 RHS.get()->getType())) 9888 return ResultTy; 9889 } 9890 9891 // Handle block pointer types. 9892 if (!IsRelational && LHSType->isBlockPointerType() && 9893 RHSType->isBlockPointerType()) { 9894 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9895 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9896 9897 if (!LHSIsNull && !RHSIsNull && 9898 !Context.typesAreCompatible(lpointee, rpointee)) { 9899 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9900 << LHSType << RHSType << LHS.get()->getSourceRange() 9901 << RHS.get()->getSourceRange(); 9902 } 9903 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9904 return ResultTy; 9905 } 9906 9907 // Allow block pointers to be compared with null pointer constants. 9908 if (!IsRelational 9909 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9910 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9911 if (!LHSIsNull && !RHSIsNull) { 9912 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9913 ->getPointeeType()->isVoidType()) 9914 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9915 ->getPointeeType()->isVoidType()))) 9916 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9917 << LHSType << RHSType << LHS.get()->getSourceRange() 9918 << RHS.get()->getSourceRange(); 9919 } 9920 if (LHSIsNull && !RHSIsNull) 9921 LHS = ImpCastExprToType(LHS.get(), RHSType, 9922 RHSType->isPointerType() ? CK_BitCast 9923 : CK_AnyPointerToBlockPointerCast); 9924 else 9925 RHS = ImpCastExprToType(RHS.get(), LHSType, 9926 LHSType->isPointerType() ? CK_BitCast 9927 : CK_AnyPointerToBlockPointerCast); 9928 return ResultTy; 9929 } 9930 9931 if (LHSType->isObjCObjectPointerType() || 9932 RHSType->isObjCObjectPointerType()) { 9933 const PointerType *LPT = LHSType->getAs<PointerType>(); 9934 const PointerType *RPT = RHSType->getAs<PointerType>(); 9935 if (LPT || RPT) { 9936 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9937 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9938 9939 if (!LPtrToVoid && !RPtrToVoid && 9940 !Context.typesAreCompatible(LHSType, RHSType)) { 9941 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9942 /*isError*/false); 9943 } 9944 if (LHSIsNull && !RHSIsNull) { 9945 Expr *E = LHS.get(); 9946 if (getLangOpts().ObjCAutoRefCount) 9947 CheckObjCConversion(SourceRange(), RHSType, E, 9948 CCK_ImplicitConversion); 9949 LHS = ImpCastExprToType(E, RHSType, 9950 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9951 } 9952 else { 9953 Expr *E = RHS.get(); 9954 if (getLangOpts().ObjCAutoRefCount) 9955 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9956 /*Diagnose=*/true, 9957 /*DiagnoseCFAudited=*/false, Opc); 9958 RHS = ImpCastExprToType(E, LHSType, 9959 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9960 } 9961 return ResultTy; 9962 } 9963 if (LHSType->isObjCObjectPointerType() && 9964 RHSType->isObjCObjectPointerType()) { 9965 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9966 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9967 /*isError*/false); 9968 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9969 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9970 9971 if (LHSIsNull && !RHSIsNull) 9972 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9973 else 9974 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9975 return ResultTy; 9976 } 9977 } 9978 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9979 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9980 unsigned DiagID = 0; 9981 bool isError = false; 9982 if (LangOpts.DebuggerSupport) { 9983 // Under a debugger, allow the comparison of pointers to integers, 9984 // since users tend to want to compare addresses. 9985 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9986 (RHSIsNull && RHSType->isIntegerType())) { 9987 if (IsRelational) { 9988 isError = getLangOpts().CPlusPlus; 9989 DiagID = 9990 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9991 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9992 } 9993 } else if (getLangOpts().CPlusPlus) { 9994 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9995 isError = true; 9996 } else if (IsRelational) 9997 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9998 else 9999 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10000 10001 if (DiagID) { 10002 Diag(Loc, DiagID) 10003 << LHSType << RHSType << LHS.get()->getSourceRange() 10004 << RHS.get()->getSourceRange(); 10005 if (isError) 10006 return QualType(); 10007 } 10008 10009 if (LHSType->isIntegerType()) 10010 LHS = ImpCastExprToType(LHS.get(), RHSType, 10011 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10012 else 10013 RHS = ImpCastExprToType(RHS.get(), LHSType, 10014 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10015 return ResultTy; 10016 } 10017 10018 // Handle block pointers. 10019 if (!IsRelational && RHSIsNull 10020 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10021 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10022 return ResultTy; 10023 } 10024 if (!IsRelational && LHSIsNull 10025 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10026 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10027 return ResultTy; 10028 } 10029 10030 if (getLangOpts().OpenCLVersion >= 200) { 10031 if (LHSIsNull && RHSType->isQueueT()) { 10032 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10033 return ResultTy; 10034 } 10035 10036 if (LHSType->isQueueT() && RHSIsNull) { 10037 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10038 return ResultTy; 10039 } 10040 } 10041 10042 return InvalidOperands(Loc, LHS, RHS); 10043 } 10044 10045 // Return a signed ext_vector_type that is of identical size and number of 10046 // elements. For floating point vectors, return an integer type of identical 10047 // size and number of elements. In the non ext_vector_type case, search from 10048 // the largest type to the smallest type to avoid cases where long long == long, 10049 // where long gets picked over long long. 10050 QualType Sema::GetSignedVectorType(QualType V) { 10051 const VectorType *VTy = V->getAs<VectorType>(); 10052 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10053 10054 if (isa<ExtVectorType>(VTy)) { 10055 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10056 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10057 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10058 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10059 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10060 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10061 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10062 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10063 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10064 "Unhandled vector element size in vector compare"); 10065 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10066 } 10067 10068 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10069 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10070 VectorType::GenericVector); 10071 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10072 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10073 VectorType::GenericVector); 10074 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10075 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10076 VectorType::GenericVector); 10077 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10078 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10079 VectorType::GenericVector); 10080 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10081 "Unhandled vector element size in vector compare"); 10082 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10083 VectorType::GenericVector); 10084 } 10085 10086 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10087 /// operates on extended vector types. Instead of producing an IntTy result, 10088 /// like a scalar comparison, a vector comparison produces a vector of integer 10089 /// types. 10090 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10091 SourceLocation Loc, 10092 bool IsRelational) { 10093 // Check to make sure we're operating on vectors of the same type and width, 10094 // Allowing one side to be a scalar of element type. 10095 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10096 /*AllowBothBool*/true, 10097 /*AllowBoolConversions*/getLangOpts().ZVector); 10098 if (vType.isNull()) 10099 return vType; 10100 10101 QualType LHSType = LHS.get()->getType(); 10102 10103 // If AltiVec, the comparison results in a numeric type, i.e. 10104 // bool for C++, int for C 10105 if (getLangOpts().AltiVec && 10106 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10107 return Context.getLogicalOperationType(); 10108 10109 // For non-floating point types, check for self-comparisons of the form 10110 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10111 // often indicate logic errors in the program. 10112 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 10113 if (DeclRefExpr* DRL 10114 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 10115 if (DeclRefExpr* DRR 10116 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 10117 if (DRL->getDecl() == DRR->getDecl()) 10118 DiagRuntimeBehavior(Loc, nullptr, 10119 PDiag(diag::warn_comparison_always) 10120 << 0 // self- 10121 << 2 // "a constant" 10122 ); 10123 } 10124 10125 // Check for comparisons of floating point operands using != and ==. 10126 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 10127 assert (RHS.get()->getType()->hasFloatingRepresentation()); 10128 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10129 } 10130 10131 // Return a signed type for the vector. 10132 return GetSignedVectorType(vType); 10133 } 10134 10135 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10136 SourceLocation Loc) { 10137 // Ensure that either both operands are of the same vector type, or 10138 // one operand is of a vector type and the other is of its element type. 10139 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10140 /*AllowBothBool*/true, 10141 /*AllowBoolConversions*/false); 10142 if (vType.isNull()) 10143 return InvalidOperands(Loc, LHS, RHS); 10144 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10145 vType->hasFloatingRepresentation()) 10146 return InvalidOperands(Loc, LHS, RHS); 10147 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10148 // usage of the logical operators && and || with vectors in C. This 10149 // check could be notionally dropped. 10150 if (!getLangOpts().CPlusPlus && 10151 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10152 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10153 10154 return GetSignedVectorType(LHS.get()->getType()); 10155 } 10156 10157 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10158 SourceLocation Loc, 10159 BinaryOperatorKind Opc) { 10160 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10161 10162 bool IsCompAssign = 10163 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10164 10165 if (LHS.get()->getType()->isVectorType() || 10166 RHS.get()->getType()->isVectorType()) { 10167 if (LHS.get()->getType()->hasIntegerRepresentation() && 10168 RHS.get()->getType()->hasIntegerRepresentation()) 10169 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10170 /*AllowBothBool*/true, 10171 /*AllowBoolConversions*/getLangOpts().ZVector); 10172 return InvalidOperands(Loc, LHS, RHS); 10173 } 10174 10175 if (Opc == BO_And) 10176 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10177 10178 ExprResult LHSResult = LHS, RHSResult = RHS; 10179 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10180 IsCompAssign); 10181 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10182 return QualType(); 10183 LHS = LHSResult.get(); 10184 RHS = RHSResult.get(); 10185 10186 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10187 return compType; 10188 return InvalidOperands(Loc, LHS, RHS); 10189 } 10190 10191 // C99 6.5.[13,14] 10192 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10193 SourceLocation Loc, 10194 BinaryOperatorKind Opc) { 10195 // Check vector operands differently. 10196 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10197 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10198 10199 // Diagnose cases where the user write a logical and/or but probably meant a 10200 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10201 // is a constant. 10202 if (LHS.get()->getType()->isIntegerType() && 10203 !LHS.get()->getType()->isBooleanType() && 10204 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10205 // Don't warn in macros or template instantiations. 10206 !Loc.isMacroID() && !inTemplateInstantiation()) { 10207 // If the RHS can be constant folded, and if it constant folds to something 10208 // that isn't 0 or 1 (which indicate a potential logical operation that 10209 // happened to fold to true/false) then warn. 10210 // Parens on the RHS are ignored. 10211 llvm::APSInt Result; 10212 if (RHS.get()->EvaluateAsInt(Result, Context)) 10213 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10214 !RHS.get()->getExprLoc().isMacroID()) || 10215 (Result != 0 && Result != 1)) { 10216 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10217 << RHS.get()->getSourceRange() 10218 << (Opc == BO_LAnd ? "&&" : "||"); 10219 // Suggest replacing the logical operator with the bitwise version 10220 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10221 << (Opc == BO_LAnd ? "&" : "|") 10222 << FixItHint::CreateReplacement(SourceRange( 10223 Loc, getLocForEndOfToken(Loc)), 10224 Opc == BO_LAnd ? "&" : "|"); 10225 if (Opc == BO_LAnd) 10226 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10227 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10228 << FixItHint::CreateRemoval( 10229 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10230 RHS.get()->getLocEnd())); 10231 } 10232 } 10233 10234 if (!Context.getLangOpts().CPlusPlus) { 10235 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10236 // not operate on the built-in scalar and vector float types. 10237 if (Context.getLangOpts().OpenCL && 10238 Context.getLangOpts().OpenCLVersion < 120) { 10239 if (LHS.get()->getType()->isFloatingType() || 10240 RHS.get()->getType()->isFloatingType()) 10241 return InvalidOperands(Loc, LHS, RHS); 10242 } 10243 10244 LHS = UsualUnaryConversions(LHS.get()); 10245 if (LHS.isInvalid()) 10246 return QualType(); 10247 10248 RHS = UsualUnaryConversions(RHS.get()); 10249 if (RHS.isInvalid()) 10250 return QualType(); 10251 10252 if (!LHS.get()->getType()->isScalarType() || 10253 !RHS.get()->getType()->isScalarType()) 10254 return InvalidOperands(Loc, LHS, RHS); 10255 10256 return Context.IntTy; 10257 } 10258 10259 // The following is safe because we only use this method for 10260 // non-overloadable operands. 10261 10262 // C++ [expr.log.and]p1 10263 // C++ [expr.log.or]p1 10264 // The operands are both contextually converted to type bool. 10265 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10266 if (LHSRes.isInvalid()) 10267 return InvalidOperands(Loc, LHS, RHS); 10268 LHS = LHSRes; 10269 10270 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10271 if (RHSRes.isInvalid()) 10272 return InvalidOperands(Loc, LHS, RHS); 10273 RHS = RHSRes; 10274 10275 // C++ [expr.log.and]p2 10276 // C++ [expr.log.or]p2 10277 // The result is a bool. 10278 return Context.BoolTy; 10279 } 10280 10281 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10282 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10283 if (!ME) return false; 10284 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10285 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10286 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10287 if (!Base) return false; 10288 return Base->getMethodDecl() != nullptr; 10289 } 10290 10291 /// Is the given expression (which must be 'const') a reference to a 10292 /// variable which was originally non-const, but which has become 10293 /// 'const' due to being captured within a block? 10294 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10295 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10296 assert(E->isLValue() && E->getType().isConstQualified()); 10297 E = E->IgnoreParens(); 10298 10299 // Must be a reference to a declaration from an enclosing scope. 10300 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10301 if (!DRE) return NCCK_None; 10302 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10303 10304 // The declaration must be a variable which is not declared 'const'. 10305 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10306 if (!var) return NCCK_None; 10307 if (var->getType().isConstQualified()) return NCCK_None; 10308 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10309 10310 // Decide whether the first capture was for a block or a lambda. 10311 DeclContext *DC = S.CurContext, *Prev = nullptr; 10312 // Decide whether the first capture was for a block or a lambda. 10313 while (DC) { 10314 // For init-capture, it is possible that the variable belongs to the 10315 // template pattern of the current context. 10316 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10317 if (var->isInitCapture() && 10318 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10319 break; 10320 if (DC == var->getDeclContext()) 10321 break; 10322 Prev = DC; 10323 DC = DC->getParent(); 10324 } 10325 // Unless we have an init-capture, we've gone one step too far. 10326 if (!var->isInitCapture()) 10327 DC = Prev; 10328 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10329 } 10330 10331 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10332 Ty = Ty.getNonReferenceType(); 10333 if (IsDereference && Ty->isPointerType()) 10334 Ty = Ty->getPointeeType(); 10335 return !Ty.isConstQualified(); 10336 } 10337 10338 // Update err_typecheck_assign_const and note_typecheck_assign_const 10339 // when this enum is changed. 10340 enum { 10341 ConstFunction, 10342 ConstVariable, 10343 ConstMember, 10344 ConstMethod, 10345 NestedConstMember, 10346 ConstUnknown, // Keep as last element 10347 }; 10348 10349 /// Emit the "read-only variable not assignable" error and print notes to give 10350 /// more information about why the variable is not assignable, such as pointing 10351 /// to the declaration of a const variable, showing that a method is const, or 10352 /// that the function is returning a const reference. 10353 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10354 SourceLocation Loc) { 10355 SourceRange ExprRange = E->getSourceRange(); 10356 10357 // Only emit one error on the first const found. All other consts will emit 10358 // a note to the error. 10359 bool DiagnosticEmitted = false; 10360 10361 // Track if the current expression is the result of a dereference, and if the 10362 // next checked expression is the result of a dereference. 10363 bool IsDereference = false; 10364 bool NextIsDereference = false; 10365 10366 // Loop to process MemberExpr chains. 10367 while (true) { 10368 IsDereference = NextIsDereference; 10369 10370 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10371 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10372 NextIsDereference = ME->isArrow(); 10373 const ValueDecl *VD = ME->getMemberDecl(); 10374 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10375 // Mutable fields can be modified even if the class is const. 10376 if (Field->isMutable()) { 10377 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10378 break; 10379 } 10380 10381 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10382 if (!DiagnosticEmitted) { 10383 S.Diag(Loc, diag::err_typecheck_assign_const) 10384 << ExprRange << ConstMember << false /*static*/ << Field 10385 << Field->getType(); 10386 DiagnosticEmitted = true; 10387 } 10388 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10389 << ConstMember << false /*static*/ << Field << Field->getType() 10390 << Field->getSourceRange(); 10391 } 10392 E = ME->getBase(); 10393 continue; 10394 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10395 if (VDecl->getType().isConstQualified()) { 10396 if (!DiagnosticEmitted) { 10397 S.Diag(Loc, diag::err_typecheck_assign_const) 10398 << ExprRange << ConstMember << true /*static*/ << VDecl 10399 << VDecl->getType(); 10400 DiagnosticEmitted = true; 10401 } 10402 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10403 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10404 << VDecl->getSourceRange(); 10405 } 10406 // Static fields do not inherit constness from parents. 10407 break; 10408 } 10409 break; 10410 } // End MemberExpr 10411 break; 10412 } 10413 10414 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10415 // Function calls 10416 const FunctionDecl *FD = CE->getDirectCallee(); 10417 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10418 if (!DiagnosticEmitted) { 10419 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10420 << ConstFunction << FD; 10421 DiagnosticEmitted = true; 10422 } 10423 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10424 diag::note_typecheck_assign_const) 10425 << ConstFunction << FD << FD->getReturnType() 10426 << FD->getReturnTypeSourceRange(); 10427 } 10428 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10429 // Point to variable declaration. 10430 if (const ValueDecl *VD = DRE->getDecl()) { 10431 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10432 if (!DiagnosticEmitted) { 10433 S.Diag(Loc, diag::err_typecheck_assign_const) 10434 << ExprRange << ConstVariable << VD << VD->getType(); 10435 DiagnosticEmitted = true; 10436 } 10437 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10438 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10439 } 10440 } 10441 } else if (isa<CXXThisExpr>(E)) { 10442 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10443 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10444 if (MD->isConst()) { 10445 if (!DiagnosticEmitted) { 10446 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10447 << ConstMethod << MD; 10448 DiagnosticEmitted = true; 10449 } 10450 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10451 << ConstMethod << MD << MD->getSourceRange(); 10452 } 10453 } 10454 } 10455 } 10456 10457 if (DiagnosticEmitted) 10458 return; 10459 10460 // Can't determine a more specific message, so display the generic error. 10461 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10462 } 10463 10464 enum OriginalExprKind { 10465 OEK_Variable, 10466 OEK_Member, 10467 OEK_LValue 10468 }; 10469 10470 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10471 const RecordType *Ty, 10472 SourceLocation Loc, SourceRange Range, 10473 OriginalExprKind OEK, 10474 bool &DiagnosticEmitted, 10475 bool IsNested = false) { 10476 // We walk the record hierarchy breadth-first to ensure that we print 10477 // diagnostics in field nesting order. 10478 // First, check every field for constness. 10479 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10480 if (Field->getType().isConstQualified()) { 10481 if (!DiagnosticEmitted) { 10482 S.Diag(Loc, diag::err_typecheck_assign_const) 10483 << Range << NestedConstMember << OEK << VD 10484 << IsNested << Field; 10485 DiagnosticEmitted = true; 10486 } 10487 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10488 << NestedConstMember << IsNested << Field 10489 << Field->getType() << Field->getSourceRange(); 10490 } 10491 } 10492 // Then, recurse. 10493 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10494 QualType FTy = Field->getType(); 10495 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10496 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10497 OEK, DiagnosticEmitted, true); 10498 } 10499 } 10500 10501 /// Emit an error for the case where a record we are trying to assign to has a 10502 /// const-qualified field somewhere in its hierarchy. 10503 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10504 SourceLocation Loc) { 10505 QualType Ty = E->getType(); 10506 assert(Ty->isRecordType() && "lvalue was not record?"); 10507 SourceRange Range = E->getSourceRange(); 10508 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10509 bool DiagEmitted = false; 10510 10511 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10512 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10513 Range, OEK_Member, DiagEmitted); 10514 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10515 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10516 Range, OEK_Variable, DiagEmitted); 10517 else 10518 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10519 Range, OEK_LValue, DiagEmitted); 10520 if (!DiagEmitted) 10521 DiagnoseConstAssignment(S, E, Loc); 10522 } 10523 10524 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10525 /// emit an error and return true. If so, return false. 10526 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10527 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10528 10529 S.CheckShadowingDeclModification(E, Loc); 10530 10531 SourceLocation OrigLoc = Loc; 10532 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10533 &Loc); 10534 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10535 IsLV = Expr::MLV_InvalidMessageExpression; 10536 if (IsLV == Expr::MLV_Valid) 10537 return false; 10538 10539 unsigned DiagID = 0; 10540 bool NeedType = false; 10541 switch (IsLV) { // C99 6.5.16p2 10542 case Expr::MLV_ConstQualified: 10543 // Use a specialized diagnostic when we're assigning to an object 10544 // from an enclosing function or block. 10545 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10546 if (NCCK == NCCK_Block) 10547 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10548 else 10549 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10550 break; 10551 } 10552 10553 // In ARC, use some specialized diagnostics for occasions where we 10554 // infer 'const'. These are always pseudo-strong variables. 10555 if (S.getLangOpts().ObjCAutoRefCount) { 10556 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10557 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10558 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10559 10560 // Use the normal diagnostic if it's pseudo-__strong but the 10561 // user actually wrote 'const'. 10562 if (var->isARCPseudoStrong() && 10563 (!var->getTypeSourceInfo() || 10564 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10565 // There are two pseudo-strong cases: 10566 // - self 10567 ObjCMethodDecl *method = S.getCurMethodDecl(); 10568 if (method && var == method->getSelfDecl()) 10569 DiagID = method->isClassMethod() 10570 ? diag::err_typecheck_arc_assign_self_class_method 10571 : diag::err_typecheck_arc_assign_self; 10572 10573 // - fast enumeration variables 10574 else 10575 DiagID = diag::err_typecheck_arr_assign_enumeration; 10576 10577 SourceRange Assign; 10578 if (Loc != OrigLoc) 10579 Assign = SourceRange(OrigLoc, OrigLoc); 10580 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10581 // We need to preserve the AST regardless, so migration tool 10582 // can do its job. 10583 return false; 10584 } 10585 } 10586 } 10587 10588 // If none of the special cases above are triggered, then this is a 10589 // simple const assignment. 10590 if (DiagID == 0) { 10591 DiagnoseConstAssignment(S, E, Loc); 10592 return true; 10593 } 10594 10595 break; 10596 case Expr::MLV_ConstAddrSpace: 10597 DiagnoseConstAssignment(S, E, Loc); 10598 return true; 10599 case Expr::MLV_ConstQualifiedField: 10600 DiagnoseRecursiveConstFields(S, E, Loc); 10601 return true; 10602 case Expr::MLV_ArrayType: 10603 case Expr::MLV_ArrayTemporary: 10604 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10605 NeedType = true; 10606 break; 10607 case Expr::MLV_NotObjectType: 10608 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10609 NeedType = true; 10610 break; 10611 case Expr::MLV_LValueCast: 10612 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10613 break; 10614 case Expr::MLV_Valid: 10615 llvm_unreachable("did not take early return for MLV_Valid"); 10616 case Expr::MLV_InvalidExpression: 10617 case Expr::MLV_MemberFunction: 10618 case Expr::MLV_ClassTemporary: 10619 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10620 break; 10621 case Expr::MLV_IncompleteType: 10622 case Expr::MLV_IncompleteVoidType: 10623 return S.RequireCompleteType(Loc, E->getType(), 10624 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10625 case Expr::MLV_DuplicateVectorComponents: 10626 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10627 break; 10628 case Expr::MLV_NoSetterProperty: 10629 llvm_unreachable("readonly properties should be processed differently"); 10630 case Expr::MLV_InvalidMessageExpression: 10631 DiagID = diag::err_readonly_message_assignment; 10632 break; 10633 case Expr::MLV_SubObjCPropertySetting: 10634 DiagID = diag::err_no_subobject_property_setting; 10635 break; 10636 } 10637 10638 SourceRange Assign; 10639 if (Loc != OrigLoc) 10640 Assign = SourceRange(OrigLoc, OrigLoc); 10641 if (NeedType) 10642 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10643 else 10644 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10645 return true; 10646 } 10647 10648 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10649 SourceLocation Loc, 10650 Sema &Sema) { 10651 // C / C++ fields 10652 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10653 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10654 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10655 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10656 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10657 } 10658 10659 // Objective-C instance variables 10660 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10661 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10662 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10663 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10664 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10665 if (RL && RR && RL->getDecl() == RR->getDecl()) 10666 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10667 } 10668 } 10669 10670 // C99 6.5.16.1 10671 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10672 SourceLocation Loc, 10673 QualType CompoundType) { 10674 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10675 10676 // Verify that LHS is a modifiable lvalue, and emit error if not. 10677 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10678 return QualType(); 10679 10680 QualType LHSType = LHSExpr->getType(); 10681 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10682 CompoundType; 10683 // OpenCL v1.2 s6.1.1.1 p2: 10684 // The half data type can only be used to declare a pointer to a buffer that 10685 // contains half values 10686 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10687 LHSType->isHalfType()) { 10688 Diag(Loc, diag::err_opencl_half_load_store) << 1 10689 << LHSType.getUnqualifiedType(); 10690 return QualType(); 10691 } 10692 10693 AssignConvertType ConvTy; 10694 if (CompoundType.isNull()) { 10695 Expr *RHSCheck = RHS.get(); 10696 10697 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10698 10699 QualType LHSTy(LHSType); 10700 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10701 if (RHS.isInvalid()) 10702 return QualType(); 10703 // Special case of NSObject attributes on c-style pointer types. 10704 if (ConvTy == IncompatiblePointer && 10705 ((Context.isObjCNSObjectType(LHSType) && 10706 RHSType->isObjCObjectPointerType()) || 10707 (Context.isObjCNSObjectType(RHSType) && 10708 LHSType->isObjCObjectPointerType()))) 10709 ConvTy = Compatible; 10710 10711 if (ConvTy == Compatible && 10712 LHSType->isObjCObjectType()) 10713 Diag(Loc, diag::err_objc_object_assignment) 10714 << LHSType; 10715 10716 // If the RHS is a unary plus or minus, check to see if they = and + are 10717 // right next to each other. If so, the user may have typo'd "x =+ 4" 10718 // instead of "x += 4". 10719 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10720 RHSCheck = ICE->getSubExpr(); 10721 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10722 if ((UO->getOpcode() == UO_Plus || 10723 UO->getOpcode() == UO_Minus) && 10724 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10725 // Only if the two operators are exactly adjacent. 10726 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10727 // And there is a space or other character before the subexpr of the 10728 // unary +/-. We don't want to warn on "x=-1". 10729 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10730 UO->getSubExpr()->getLocStart().isFileID()) { 10731 Diag(Loc, diag::warn_not_compound_assign) 10732 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10733 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10734 } 10735 } 10736 10737 if (ConvTy == Compatible) { 10738 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10739 // Warn about retain cycles where a block captures the LHS, but 10740 // not if the LHS is a simple variable into which the block is 10741 // being stored...unless that variable can be captured by reference! 10742 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10743 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10744 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10745 checkRetainCycles(LHSExpr, RHS.get()); 10746 } 10747 10748 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10749 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10750 // It is safe to assign a weak reference into a strong variable. 10751 // Although this code can still have problems: 10752 // id x = self.weakProp; 10753 // id y = self.weakProp; 10754 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10755 // paths through the function. This should be revisited if 10756 // -Wrepeated-use-of-weak is made flow-sensitive. 10757 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10758 // variable, which will be valid for the current autorelease scope. 10759 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10760 RHS.get()->getLocStart())) 10761 getCurFunction()->markSafeWeakUse(RHS.get()); 10762 10763 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10764 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10765 } 10766 } 10767 } else { 10768 // Compound assignment "x += y" 10769 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10770 } 10771 10772 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10773 RHS.get(), AA_Assigning)) 10774 return QualType(); 10775 10776 CheckForNullPointerDereference(*this, LHSExpr); 10777 10778 // C99 6.5.16p3: The type of an assignment expression is the type of the 10779 // left operand unless the left operand has qualified type, in which case 10780 // it is the unqualified version of the type of the left operand. 10781 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10782 // is converted to the type of the assignment expression (above). 10783 // C++ 5.17p1: the type of the assignment expression is that of its left 10784 // operand. 10785 return (getLangOpts().CPlusPlus 10786 ? LHSType : LHSType.getUnqualifiedType()); 10787 } 10788 10789 // Only ignore explicit casts to void. 10790 static bool IgnoreCommaOperand(const Expr *E) { 10791 E = E->IgnoreParens(); 10792 10793 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10794 if (CE->getCastKind() == CK_ToVoid) { 10795 return true; 10796 } 10797 } 10798 10799 return false; 10800 } 10801 10802 // Look for instances where it is likely the comma operator is confused with 10803 // another operator. There is a whitelist of acceptable expressions for the 10804 // left hand side of the comma operator, otherwise emit a warning. 10805 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10806 // No warnings in macros 10807 if (Loc.isMacroID()) 10808 return; 10809 10810 // Don't warn in template instantiations. 10811 if (inTemplateInstantiation()) 10812 return; 10813 10814 // Scope isn't fine-grained enough to whitelist the specific cases, so 10815 // instead, skip more than needed, then call back into here with the 10816 // CommaVisitor in SemaStmt.cpp. 10817 // The whitelisted locations are the initialization and increment portions 10818 // of a for loop. The additional checks are on the condition of 10819 // if statements, do/while loops, and for loops. 10820 const unsigned ForIncrementFlags = 10821 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10822 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10823 const unsigned ScopeFlags = getCurScope()->getFlags(); 10824 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10825 (ScopeFlags & ForInitFlags) == ForInitFlags) 10826 return; 10827 10828 // If there are multiple comma operators used together, get the RHS of the 10829 // of the comma operator as the LHS. 10830 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10831 if (BO->getOpcode() != BO_Comma) 10832 break; 10833 LHS = BO->getRHS(); 10834 } 10835 10836 // Only allow some expressions on LHS to not warn. 10837 if (IgnoreCommaOperand(LHS)) 10838 return; 10839 10840 Diag(Loc, diag::warn_comma_operator); 10841 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10842 << LHS->getSourceRange() 10843 << FixItHint::CreateInsertion(LHS->getLocStart(), 10844 LangOpts.CPlusPlus ? "static_cast<void>(" 10845 : "(void)(") 10846 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10847 ")"); 10848 } 10849 10850 // C99 6.5.17 10851 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10852 SourceLocation Loc) { 10853 LHS = S.CheckPlaceholderExpr(LHS.get()); 10854 RHS = S.CheckPlaceholderExpr(RHS.get()); 10855 if (LHS.isInvalid() || RHS.isInvalid()) 10856 return QualType(); 10857 10858 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10859 // operands, but not unary promotions. 10860 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10861 10862 // So we treat the LHS as a ignored value, and in C++ we allow the 10863 // containing site to determine what should be done with the RHS. 10864 LHS = S.IgnoredValueConversions(LHS.get()); 10865 if (LHS.isInvalid()) 10866 return QualType(); 10867 10868 S.DiagnoseUnusedExprResult(LHS.get()); 10869 10870 if (!S.getLangOpts().CPlusPlus) { 10871 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10872 if (RHS.isInvalid()) 10873 return QualType(); 10874 if (!RHS.get()->getType()->isVoidType()) 10875 S.RequireCompleteType(Loc, RHS.get()->getType(), 10876 diag::err_incomplete_type); 10877 } 10878 10879 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10880 S.DiagnoseCommaOperator(LHS.get(), Loc); 10881 10882 return RHS.get()->getType(); 10883 } 10884 10885 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10886 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10887 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10888 ExprValueKind &VK, 10889 ExprObjectKind &OK, 10890 SourceLocation OpLoc, 10891 bool IsInc, bool IsPrefix) { 10892 if (Op->isTypeDependent()) 10893 return S.Context.DependentTy; 10894 10895 QualType ResType = Op->getType(); 10896 // Atomic types can be used for increment / decrement where the non-atomic 10897 // versions can, so ignore the _Atomic() specifier for the purpose of 10898 // checking. 10899 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10900 ResType = ResAtomicType->getValueType(); 10901 10902 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10903 10904 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10905 // Decrement of bool is not allowed. 10906 if (!IsInc) { 10907 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10908 return QualType(); 10909 } 10910 // Increment of bool sets it to true, but is deprecated. 10911 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10912 : diag::warn_increment_bool) 10913 << Op->getSourceRange(); 10914 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10915 // Error on enum increments and decrements in C++ mode 10916 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10917 return QualType(); 10918 } else if (ResType->isRealType()) { 10919 // OK! 10920 } else if (ResType->isPointerType()) { 10921 // C99 6.5.2.4p2, 6.5.6p2 10922 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10923 return QualType(); 10924 } else if (ResType->isObjCObjectPointerType()) { 10925 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10926 // Otherwise, we just need a complete type. 10927 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10928 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10929 return QualType(); 10930 } else if (ResType->isAnyComplexType()) { 10931 // C99 does not support ++/-- on complex types, we allow as an extension. 10932 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10933 << ResType << Op->getSourceRange(); 10934 } else if (ResType->isPlaceholderType()) { 10935 ExprResult PR = S.CheckPlaceholderExpr(Op); 10936 if (PR.isInvalid()) return QualType(); 10937 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10938 IsInc, IsPrefix); 10939 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10940 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10941 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10942 (ResType->getAs<VectorType>()->getVectorKind() != 10943 VectorType::AltiVecBool)) { 10944 // The z vector extensions allow ++ and -- for non-bool vectors. 10945 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10946 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10947 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10948 } else { 10949 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10950 << ResType << int(IsInc) << Op->getSourceRange(); 10951 return QualType(); 10952 } 10953 // At this point, we know we have a real, complex or pointer type. 10954 // Now make sure the operand is a modifiable lvalue. 10955 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10956 return QualType(); 10957 // In C++, a prefix increment is the same type as the operand. Otherwise 10958 // (in C or with postfix), the increment is the unqualified type of the 10959 // operand. 10960 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10961 VK = VK_LValue; 10962 OK = Op->getObjectKind(); 10963 return ResType; 10964 } else { 10965 VK = VK_RValue; 10966 return ResType.getUnqualifiedType(); 10967 } 10968 } 10969 10970 10971 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10972 /// This routine allows us to typecheck complex/recursive expressions 10973 /// where the declaration is needed for type checking. We only need to 10974 /// handle cases when the expression references a function designator 10975 /// or is an lvalue. Here are some examples: 10976 /// - &(x) => x 10977 /// - &*****f => f for f a function designator. 10978 /// - &s.xx => s 10979 /// - &s.zz[1].yy -> s, if zz is an array 10980 /// - *(x + 1) -> x, if x is an array 10981 /// - &"123"[2] -> 0 10982 /// - & __real__ x -> x 10983 static ValueDecl *getPrimaryDecl(Expr *E) { 10984 switch (E->getStmtClass()) { 10985 case Stmt::DeclRefExprClass: 10986 return cast<DeclRefExpr>(E)->getDecl(); 10987 case Stmt::MemberExprClass: 10988 // If this is an arrow operator, the address is an offset from 10989 // the base's value, so the object the base refers to is 10990 // irrelevant. 10991 if (cast<MemberExpr>(E)->isArrow()) 10992 return nullptr; 10993 // Otherwise, the expression refers to a part of the base 10994 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10995 case Stmt::ArraySubscriptExprClass: { 10996 // FIXME: This code shouldn't be necessary! We should catch the implicit 10997 // promotion of register arrays earlier. 10998 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10999 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11000 if (ICE->getSubExpr()->getType()->isArrayType()) 11001 return getPrimaryDecl(ICE->getSubExpr()); 11002 } 11003 return nullptr; 11004 } 11005 case Stmt::UnaryOperatorClass: { 11006 UnaryOperator *UO = cast<UnaryOperator>(E); 11007 11008 switch(UO->getOpcode()) { 11009 case UO_Real: 11010 case UO_Imag: 11011 case UO_Extension: 11012 return getPrimaryDecl(UO->getSubExpr()); 11013 default: 11014 return nullptr; 11015 } 11016 } 11017 case Stmt::ParenExprClass: 11018 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11019 case Stmt::ImplicitCastExprClass: 11020 // If the result of an implicit cast is an l-value, we care about 11021 // the sub-expression; otherwise, the result here doesn't matter. 11022 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11023 default: 11024 return nullptr; 11025 } 11026 } 11027 11028 namespace { 11029 enum { 11030 AO_Bit_Field = 0, 11031 AO_Vector_Element = 1, 11032 AO_Property_Expansion = 2, 11033 AO_Register_Variable = 3, 11034 AO_No_Error = 4 11035 }; 11036 } 11037 /// \brief Diagnose invalid operand for address of operations. 11038 /// 11039 /// \param Type The type of operand which cannot have its address taken. 11040 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11041 Expr *E, unsigned Type) { 11042 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11043 } 11044 11045 /// CheckAddressOfOperand - The operand of & must be either a function 11046 /// designator or an lvalue designating an object. If it is an lvalue, the 11047 /// object cannot be declared with storage class register or be a bit field. 11048 /// Note: The usual conversions are *not* applied to the operand of the & 11049 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11050 /// In C++, the operand might be an overloaded function name, in which case 11051 /// we allow the '&' but retain the overloaded-function type. 11052 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11053 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11054 if (PTy->getKind() == BuiltinType::Overload) { 11055 Expr *E = OrigOp.get()->IgnoreParens(); 11056 if (!isa<OverloadExpr>(E)) { 11057 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11058 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11059 << OrigOp.get()->getSourceRange(); 11060 return QualType(); 11061 } 11062 11063 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11064 if (isa<UnresolvedMemberExpr>(Ovl)) 11065 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11066 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11067 << OrigOp.get()->getSourceRange(); 11068 return QualType(); 11069 } 11070 11071 return Context.OverloadTy; 11072 } 11073 11074 if (PTy->getKind() == BuiltinType::UnknownAny) 11075 return Context.UnknownAnyTy; 11076 11077 if (PTy->getKind() == BuiltinType::BoundMember) { 11078 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11079 << OrigOp.get()->getSourceRange(); 11080 return QualType(); 11081 } 11082 11083 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11084 if (OrigOp.isInvalid()) return QualType(); 11085 } 11086 11087 if (OrigOp.get()->isTypeDependent()) 11088 return Context.DependentTy; 11089 11090 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11091 11092 // Make sure to ignore parentheses in subsequent checks 11093 Expr *op = OrigOp.get()->IgnoreParens(); 11094 11095 // In OpenCL captures for blocks called as lambda functions 11096 // are located in the private address space. Blocks used in 11097 // enqueue_kernel can be located in a different address space 11098 // depending on a vendor implementation. Thus preventing 11099 // taking an address of the capture to avoid invalid AS casts. 11100 if (LangOpts.OpenCL) { 11101 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11102 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11103 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11104 return QualType(); 11105 } 11106 } 11107 11108 if (getLangOpts().C99) { 11109 // Implement C99-only parts of addressof rules. 11110 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11111 if (uOp->getOpcode() == UO_Deref) 11112 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11113 // (assuming the deref expression is valid). 11114 return uOp->getSubExpr()->getType(); 11115 } 11116 // Technically, there should be a check for array subscript 11117 // expressions here, but the result of one is always an lvalue anyway. 11118 } 11119 ValueDecl *dcl = getPrimaryDecl(op); 11120 11121 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11122 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11123 op->getLocStart())) 11124 return QualType(); 11125 11126 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11127 unsigned AddressOfError = AO_No_Error; 11128 11129 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11130 bool sfinae = (bool)isSFINAEContext(); 11131 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11132 : diag::ext_typecheck_addrof_temporary) 11133 << op->getType() << op->getSourceRange(); 11134 if (sfinae) 11135 return QualType(); 11136 // Materialize the temporary as an lvalue so that we can take its address. 11137 OrigOp = op = 11138 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11139 } else if (isa<ObjCSelectorExpr>(op)) { 11140 return Context.getPointerType(op->getType()); 11141 } else if (lval == Expr::LV_MemberFunction) { 11142 // If it's an instance method, make a member pointer. 11143 // The expression must have exactly the form &A::foo. 11144 11145 // If the underlying expression isn't a decl ref, give up. 11146 if (!isa<DeclRefExpr>(op)) { 11147 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11148 << OrigOp.get()->getSourceRange(); 11149 return QualType(); 11150 } 11151 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11152 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11153 11154 // The id-expression was parenthesized. 11155 if (OrigOp.get() != DRE) { 11156 Diag(OpLoc, diag::err_parens_pointer_member_function) 11157 << OrigOp.get()->getSourceRange(); 11158 11159 // The method was named without a qualifier. 11160 } else if (!DRE->getQualifier()) { 11161 if (MD->getParent()->getName().empty()) 11162 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11163 << op->getSourceRange(); 11164 else { 11165 SmallString<32> Str; 11166 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11167 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11168 << op->getSourceRange() 11169 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11170 } 11171 } 11172 11173 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11174 if (isa<CXXDestructorDecl>(MD)) 11175 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11176 11177 QualType MPTy = Context.getMemberPointerType( 11178 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11179 // Under the MS ABI, lock down the inheritance model now. 11180 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11181 (void)isCompleteType(OpLoc, MPTy); 11182 return MPTy; 11183 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11184 // C99 6.5.3.2p1 11185 // The operand must be either an l-value or a function designator 11186 if (!op->getType()->isFunctionType()) { 11187 // Use a special diagnostic for loads from property references. 11188 if (isa<PseudoObjectExpr>(op)) { 11189 AddressOfError = AO_Property_Expansion; 11190 } else { 11191 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11192 << op->getType() << op->getSourceRange(); 11193 return QualType(); 11194 } 11195 } 11196 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11197 // The operand cannot be a bit-field 11198 AddressOfError = AO_Bit_Field; 11199 } else if (op->getObjectKind() == OK_VectorComponent) { 11200 // The operand cannot be an element of a vector 11201 AddressOfError = AO_Vector_Element; 11202 } else if (dcl) { // C99 6.5.3.2p1 11203 // We have an lvalue with a decl. Make sure the decl is not declared 11204 // with the register storage-class specifier. 11205 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11206 // in C++ it is not error to take address of a register 11207 // variable (c++03 7.1.1P3) 11208 if (vd->getStorageClass() == SC_Register && 11209 !getLangOpts().CPlusPlus) { 11210 AddressOfError = AO_Register_Variable; 11211 } 11212 } else if (isa<MSPropertyDecl>(dcl)) { 11213 AddressOfError = AO_Property_Expansion; 11214 } else if (isa<FunctionTemplateDecl>(dcl)) { 11215 return Context.OverloadTy; 11216 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11217 // Okay: we can take the address of a field. 11218 // Could be a pointer to member, though, if there is an explicit 11219 // scope qualifier for the class. 11220 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11221 DeclContext *Ctx = dcl->getDeclContext(); 11222 if (Ctx && Ctx->isRecord()) { 11223 if (dcl->getType()->isReferenceType()) { 11224 Diag(OpLoc, 11225 diag::err_cannot_form_pointer_to_member_of_reference_type) 11226 << dcl->getDeclName() << dcl->getType(); 11227 return QualType(); 11228 } 11229 11230 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11231 Ctx = Ctx->getParent(); 11232 11233 QualType MPTy = Context.getMemberPointerType( 11234 op->getType(), 11235 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11236 // Under the MS ABI, lock down the inheritance model now. 11237 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11238 (void)isCompleteType(OpLoc, MPTy); 11239 return MPTy; 11240 } 11241 } 11242 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11243 !isa<BindingDecl>(dcl)) 11244 llvm_unreachable("Unknown/unexpected decl type"); 11245 } 11246 11247 if (AddressOfError != AO_No_Error) { 11248 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11249 return QualType(); 11250 } 11251 11252 if (lval == Expr::LV_IncompleteVoidType) { 11253 // Taking the address of a void variable is technically illegal, but we 11254 // allow it in cases which are otherwise valid. 11255 // Example: "extern void x; void* y = &x;". 11256 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11257 } 11258 11259 // If the operand has type "type", the result has type "pointer to type". 11260 if (op->getType()->isObjCObjectType()) 11261 return Context.getObjCObjectPointerType(op->getType()); 11262 11263 CheckAddressOfPackedMember(op); 11264 11265 return Context.getPointerType(op->getType()); 11266 } 11267 11268 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11269 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11270 if (!DRE) 11271 return; 11272 const Decl *D = DRE->getDecl(); 11273 if (!D) 11274 return; 11275 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11276 if (!Param) 11277 return; 11278 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11279 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11280 return; 11281 if (FunctionScopeInfo *FD = S.getCurFunction()) 11282 if (!FD->ModifiedNonNullParams.count(Param)) 11283 FD->ModifiedNonNullParams.insert(Param); 11284 } 11285 11286 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11287 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11288 SourceLocation OpLoc) { 11289 if (Op->isTypeDependent()) 11290 return S.Context.DependentTy; 11291 11292 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11293 if (ConvResult.isInvalid()) 11294 return QualType(); 11295 Op = ConvResult.get(); 11296 QualType OpTy = Op->getType(); 11297 QualType Result; 11298 11299 if (isa<CXXReinterpretCastExpr>(Op)) { 11300 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11301 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11302 Op->getSourceRange()); 11303 } 11304 11305 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11306 { 11307 Result = PT->getPointeeType(); 11308 } 11309 else if (const ObjCObjectPointerType *OPT = 11310 OpTy->getAs<ObjCObjectPointerType>()) 11311 Result = OPT->getPointeeType(); 11312 else { 11313 ExprResult PR = S.CheckPlaceholderExpr(Op); 11314 if (PR.isInvalid()) return QualType(); 11315 if (PR.get() != Op) 11316 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11317 } 11318 11319 if (Result.isNull()) { 11320 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11321 << OpTy << Op->getSourceRange(); 11322 return QualType(); 11323 } 11324 11325 // Note that per both C89 and C99, indirection is always legal, even if Result 11326 // is an incomplete type or void. It would be possible to warn about 11327 // dereferencing a void pointer, but it's completely well-defined, and such a 11328 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11329 // for pointers to 'void' but is fine for any other pointer type: 11330 // 11331 // C++ [expr.unary.op]p1: 11332 // [...] the expression to which [the unary * operator] is applied shall 11333 // be a pointer to an object type, or a pointer to a function type 11334 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11335 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11336 << OpTy << Op->getSourceRange(); 11337 11338 // Dereferences are usually l-values... 11339 VK = VK_LValue; 11340 11341 // ...except that certain expressions are never l-values in C. 11342 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11343 VK = VK_RValue; 11344 11345 return Result; 11346 } 11347 11348 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11349 BinaryOperatorKind Opc; 11350 switch (Kind) { 11351 default: llvm_unreachable("Unknown binop!"); 11352 case tok::periodstar: Opc = BO_PtrMemD; break; 11353 case tok::arrowstar: Opc = BO_PtrMemI; break; 11354 case tok::star: Opc = BO_Mul; break; 11355 case tok::slash: Opc = BO_Div; break; 11356 case tok::percent: Opc = BO_Rem; break; 11357 case tok::plus: Opc = BO_Add; break; 11358 case tok::minus: Opc = BO_Sub; break; 11359 case tok::lessless: Opc = BO_Shl; break; 11360 case tok::greatergreater: Opc = BO_Shr; break; 11361 case tok::lessequal: Opc = BO_LE; break; 11362 case tok::less: Opc = BO_LT; break; 11363 case tok::greaterequal: Opc = BO_GE; break; 11364 case tok::greater: Opc = BO_GT; break; 11365 case tok::exclaimequal: Opc = BO_NE; break; 11366 case tok::equalequal: Opc = BO_EQ; break; 11367 case tok::amp: Opc = BO_And; break; 11368 case tok::caret: Opc = BO_Xor; break; 11369 case tok::pipe: Opc = BO_Or; break; 11370 case tok::ampamp: Opc = BO_LAnd; break; 11371 case tok::pipepipe: Opc = BO_LOr; break; 11372 case tok::equal: Opc = BO_Assign; break; 11373 case tok::starequal: Opc = BO_MulAssign; break; 11374 case tok::slashequal: Opc = BO_DivAssign; break; 11375 case tok::percentequal: Opc = BO_RemAssign; break; 11376 case tok::plusequal: Opc = BO_AddAssign; break; 11377 case tok::minusequal: Opc = BO_SubAssign; break; 11378 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11379 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11380 case tok::ampequal: Opc = BO_AndAssign; break; 11381 case tok::caretequal: Opc = BO_XorAssign; break; 11382 case tok::pipeequal: Opc = BO_OrAssign; break; 11383 case tok::comma: Opc = BO_Comma; break; 11384 } 11385 return Opc; 11386 } 11387 11388 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11389 tok::TokenKind Kind) { 11390 UnaryOperatorKind Opc; 11391 switch (Kind) { 11392 default: llvm_unreachable("Unknown unary op!"); 11393 case tok::plusplus: Opc = UO_PreInc; break; 11394 case tok::minusminus: Opc = UO_PreDec; break; 11395 case tok::amp: Opc = UO_AddrOf; break; 11396 case tok::star: Opc = UO_Deref; break; 11397 case tok::plus: Opc = UO_Plus; break; 11398 case tok::minus: Opc = UO_Minus; break; 11399 case tok::tilde: Opc = UO_Not; break; 11400 case tok::exclaim: Opc = UO_LNot; break; 11401 case tok::kw___real: Opc = UO_Real; break; 11402 case tok::kw___imag: Opc = UO_Imag; break; 11403 case tok::kw___extension__: Opc = UO_Extension; break; 11404 } 11405 return Opc; 11406 } 11407 11408 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11409 /// This warning is only emitted for builtin assignment operations. It is also 11410 /// suppressed in the event of macro expansions. 11411 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11412 SourceLocation OpLoc) { 11413 if (S.inTemplateInstantiation()) 11414 return; 11415 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11416 return; 11417 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11418 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11419 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11420 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11421 if (!LHSDeclRef || !RHSDeclRef || 11422 LHSDeclRef->getLocation().isMacroID() || 11423 RHSDeclRef->getLocation().isMacroID()) 11424 return; 11425 const ValueDecl *LHSDecl = 11426 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11427 const ValueDecl *RHSDecl = 11428 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11429 if (LHSDecl != RHSDecl) 11430 return; 11431 if (LHSDecl->getType().isVolatileQualified()) 11432 return; 11433 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11434 if (RefTy->getPointeeType().isVolatileQualified()) 11435 return; 11436 11437 S.Diag(OpLoc, diag::warn_self_assignment) 11438 << LHSDeclRef->getType() 11439 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11440 } 11441 11442 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11443 /// is usually indicative of introspection within the Objective-C pointer. 11444 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11445 SourceLocation OpLoc) { 11446 if (!S.getLangOpts().ObjC1) 11447 return; 11448 11449 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11450 const Expr *LHS = L.get(); 11451 const Expr *RHS = R.get(); 11452 11453 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11454 ObjCPointerExpr = LHS; 11455 OtherExpr = RHS; 11456 } 11457 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11458 ObjCPointerExpr = RHS; 11459 OtherExpr = LHS; 11460 } 11461 11462 // This warning is deliberately made very specific to reduce false 11463 // positives with logic that uses '&' for hashing. This logic mainly 11464 // looks for code trying to introspect into tagged pointers, which 11465 // code should generally never do. 11466 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11467 unsigned Diag = diag::warn_objc_pointer_masking; 11468 // Determine if we are introspecting the result of performSelectorXXX. 11469 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11470 // Special case messages to -performSelector and friends, which 11471 // can return non-pointer values boxed in a pointer value. 11472 // Some clients may wish to silence warnings in this subcase. 11473 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11474 Selector S = ME->getSelector(); 11475 StringRef SelArg0 = S.getNameForSlot(0); 11476 if (SelArg0.startswith("performSelector")) 11477 Diag = diag::warn_objc_pointer_masking_performSelector; 11478 } 11479 11480 S.Diag(OpLoc, Diag) 11481 << ObjCPointerExpr->getSourceRange(); 11482 } 11483 } 11484 11485 static NamedDecl *getDeclFromExpr(Expr *E) { 11486 if (!E) 11487 return nullptr; 11488 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11489 return DRE->getDecl(); 11490 if (auto *ME = dyn_cast<MemberExpr>(E)) 11491 return ME->getMemberDecl(); 11492 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11493 return IRE->getDecl(); 11494 return nullptr; 11495 } 11496 11497 // This helper function promotes a binary operator's operands (which are of a 11498 // half vector type) to a vector of floats and then truncates the result to 11499 // a vector of either half or short. 11500 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11501 BinaryOperatorKind Opc, QualType ResultTy, 11502 ExprValueKind VK, ExprObjectKind OK, 11503 bool IsCompAssign, SourceLocation OpLoc, 11504 FPOptions FPFeatures) { 11505 auto &Context = S.getASTContext(); 11506 assert((isVector(ResultTy, Context.HalfTy) || 11507 isVector(ResultTy, Context.ShortTy)) && 11508 "Result must be a vector of half or short"); 11509 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11510 isVector(RHS.get()->getType(), Context.HalfTy) && 11511 "both operands expected to be a half vector"); 11512 11513 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11514 QualType BinOpResTy = RHS.get()->getType(); 11515 11516 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11517 // change BinOpResTy to a vector of ints. 11518 if (isVector(ResultTy, Context.ShortTy)) 11519 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11520 11521 if (IsCompAssign) 11522 return new (Context) CompoundAssignOperator( 11523 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11524 OpLoc, FPFeatures); 11525 11526 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11527 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11528 VK, OK, OpLoc, FPFeatures); 11529 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11530 } 11531 11532 static std::pair<ExprResult, ExprResult> 11533 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11534 Expr *RHSExpr) { 11535 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11536 if (!S.getLangOpts().CPlusPlus) { 11537 // C cannot handle TypoExpr nodes on either side of a binop because it 11538 // doesn't handle dependent types properly, so make sure any TypoExprs have 11539 // been dealt with before checking the operands. 11540 LHS = S.CorrectDelayedTyposInExpr(LHS); 11541 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11542 if (Opc != BO_Assign) 11543 return ExprResult(E); 11544 // Avoid correcting the RHS to the same Expr as the LHS. 11545 Decl *D = getDeclFromExpr(E); 11546 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11547 }); 11548 } 11549 return std::make_pair(LHS, RHS); 11550 } 11551 11552 /// Returns true if conversion between vectors of halfs and vectors of floats 11553 /// is needed. 11554 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11555 QualType SrcType) { 11556 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11557 Ctx.getLangOpts().HalfArgsAndReturns && isVector(SrcType, Ctx.HalfTy); 11558 } 11559 11560 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11561 /// operator @p Opc at location @c TokLoc. This routine only supports 11562 /// built-in operations; ActOnBinOp handles overloaded operators. 11563 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11564 BinaryOperatorKind Opc, 11565 Expr *LHSExpr, Expr *RHSExpr) { 11566 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11567 // The syntax only allows initializer lists on the RHS of assignment, 11568 // so we don't need to worry about accepting invalid code for 11569 // non-assignment operators. 11570 // C++11 5.17p9: 11571 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11572 // of x = {} is x = T(). 11573 InitializationKind Kind = 11574 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11575 InitializedEntity Entity = 11576 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11577 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11578 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11579 if (Init.isInvalid()) 11580 return Init; 11581 RHSExpr = Init.get(); 11582 } 11583 11584 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11585 QualType ResultTy; // Result type of the binary operator. 11586 // The following two variables are used for compound assignment operators 11587 QualType CompLHSTy; // Type of LHS after promotions for computation 11588 QualType CompResultTy; // Type of computation result 11589 ExprValueKind VK = VK_RValue; 11590 ExprObjectKind OK = OK_Ordinary; 11591 bool ConvertHalfVec = false; 11592 11593 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11594 if (!LHS.isUsable() || !RHS.isUsable()) 11595 return ExprError(); 11596 11597 if (getLangOpts().OpenCL) { 11598 QualType LHSTy = LHSExpr->getType(); 11599 QualType RHSTy = RHSExpr->getType(); 11600 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11601 // the ATOMIC_VAR_INIT macro. 11602 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11603 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11604 if (BO_Assign == Opc) 11605 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11606 else 11607 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11608 return ExprError(); 11609 } 11610 11611 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11612 // only with a builtin functions and therefore should be disallowed here. 11613 if (LHSTy->isImageType() || RHSTy->isImageType() || 11614 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11615 LHSTy->isPipeType() || RHSTy->isPipeType() || 11616 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11617 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11618 return ExprError(); 11619 } 11620 } 11621 11622 switch (Opc) { 11623 case BO_Assign: 11624 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11625 if (getLangOpts().CPlusPlus && 11626 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11627 VK = LHS.get()->getValueKind(); 11628 OK = LHS.get()->getObjectKind(); 11629 } 11630 if (!ResultTy.isNull()) { 11631 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11632 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11633 } 11634 RecordModifiableNonNullParam(*this, LHS.get()); 11635 break; 11636 case BO_PtrMemD: 11637 case BO_PtrMemI: 11638 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11639 Opc == BO_PtrMemI); 11640 break; 11641 case BO_Mul: 11642 case BO_Div: 11643 ConvertHalfVec = true; 11644 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11645 Opc == BO_Div); 11646 break; 11647 case BO_Rem: 11648 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11649 break; 11650 case BO_Add: 11651 ConvertHalfVec = true; 11652 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11653 break; 11654 case BO_Sub: 11655 ConvertHalfVec = true; 11656 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11657 break; 11658 case BO_Shl: 11659 case BO_Shr: 11660 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11661 break; 11662 case BO_LE: 11663 case BO_LT: 11664 case BO_GE: 11665 case BO_GT: 11666 ConvertHalfVec = true; 11667 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11668 break; 11669 case BO_EQ: 11670 case BO_NE: 11671 ConvertHalfVec = true; 11672 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11673 break; 11674 case BO_And: 11675 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11676 LLVM_FALLTHROUGH; 11677 case BO_Xor: 11678 case BO_Or: 11679 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11680 break; 11681 case BO_LAnd: 11682 case BO_LOr: 11683 ConvertHalfVec = true; 11684 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11685 break; 11686 case BO_MulAssign: 11687 case BO_DivAssign: 11688 ConvertHalfVec = true; 11689 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11690 Opc == BO_DivAssign); 11691 CompLHSTy = CompResultTy; 11692 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11693 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11694 break; 11695 case BO_RemAssign: 11696 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11697 CompLHSTy = CompResultTy; 11698 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11699 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11700 break; 11701 case BO_AddAssign: 11702 ConvertHalfVec = true; 11703 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11704 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11705 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11706 break; 11707 case BO_SubAssign: 11708 ConvertHalfVec = true; 11709 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11710 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11711 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11712 break; 11713 case BO_ShlAssign: 11714 case BO_ShrAssign: 11715 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11716 CompLHSTy = CompResultTy; 11717 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11718 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11719 break; 11720 case BO_AndAssign: 11721 case BO_OrAssign: // fallthrough 11722 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11723 LLVM_FALLTHROUGH; 11724 case BO_XorAssign: 11725 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11726 CompLHSTy = CompResultTy; 11727 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11728 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11729 break; 11730 case BO_Comma: 11731 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11732 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11733 VK = RHS.get()->getValueKind(); 11734 OK = RHS.get()->getObjectKind(); 11735 } 11736 break; 11737 } 11738 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11739 return ExprError(); 11740 11741 // Some of the binary operations require promoting operands of half vector to 11742 // float vectors and truncating the result back to half vector. For now, we do 11743 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 11744 // arm64). 11745 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 11746 isVector(LHS.get()->getType(), Context.HalfTy) && 11747 "both sides are half vectors or neither sides are"); 11748 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 11749 LHS.get()->getType()); 11750 11751 // Check for array bounds violations for both sides of the BinaryOperator 11752 CheckArrayAccess(LHS.get()); 11753 CheckArrayAccess(RHS.get()); 11754 11755 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11756 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11757 &Context.Idents.get("object_setClass"), 11758 SourceLocation(), LookupOrdinaryName); 11759 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11760 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11761 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11762 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11763 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11764 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11765 } 11766 else 11767 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11768 } 11769 else if (const ObjCIvarRefExpr *OIRE = 11770 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11771 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11772 11773 // Opc is not a compound assignment if CompResultTy is null. 11774 if (CompResultTy.isNull()) { 11775 if (ConvertHalfVec) 11776 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 11777 OpLoc, FPFeatures); 11778 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11779 OK, OpLoc, FPFeatures); 11780 } 11781 11782 // Handle compound assignments. 11783 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11784 OK_ObjCProperty) { 11785 VK = VK_LValue; 11786 OK = LHS.get()->getObjectKind(); 11787 } 11788 11789 if (ConvertHalfVec) 11790 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 11791 OpLoc, FPFeatures); 11792 11793 return new (Context) CompoundAssignOperator( 11794 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11795 OpLoc, FPFeatures); 11796 } 11797 11798 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11799 /// operators are mixed in a way that suggests that the programmer forgot that 11800 /// comparison operators have higher precedence. The most typical example of 11801 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11802 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11803 SourceLocation OpLoc, Expr *LHSExpr, 11804 Expr *RHSExpr) { 11805 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11806 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11807 11808 // Check that one of the sides is a comparison operator and the other isn't. 11809 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11810 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11811 if (isLeftComp == isRightComp) 11812 return; 11813 11814 // Bitwise operations are sometimes used as eager logical ops. 11815 // Don't diagnose this. 11816 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11817 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11818 if (isLeftBitwise || isRightBitwise) 11819 return; 11820 11821 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11822 OpLoc) 11823 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11824 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11825 SourceRange ParensRange = isLeftComp ? 11826 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11827 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11828 11829 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11830 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11831 SuggestParentheses(Self, OpLoc, 11832 Self.PDiag(diag::note_precedence_silence) << OpStr, 11833 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11834 SuggestParentheses(Self, OpLoc, 11835 Self.PDiag(diag::note_precedence_bitwise_first) 11836 << BinaryOperator::getOpcodeStr(Opc), 11837 ParensRange); 11838 } 11839 11840 /// \brief It accepts a '&&' expr that is inside a '||' one. 11841 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11842 /// in parentheses. 11843 static void 11844 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11845 BinaryOperator *Bop) { 11846 assert(Bop->getOpcode() == BO_LAnd); 11847 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11848 << Bop->getSourceRange() << OpLoc; 11849 SuggestParentheses(Self, Bop->getOperatorLoc(), 11850 Self.PDiag(diag::note_precedence_silence) 11851 << Bop->getOpcodeStr(), 11852 Bop->getSourceRange()); 11853 } 11854 11855 /// \brief Returns true if the given expression can be evaluated as a constant 11856 /// 'true'. 11857 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11858 bool Res; 11859 return !E->isValueDependent() && 11860 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11861 } 11862 11863 /// \brief Returns true if the given expression can be evaluated as a constant 11864 /// 'false'. 11865 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11866 bool Res; 11867 return !E->isValueDependent() && 11868 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11869 } 11870 11871 /// \brief Look for '&&' in the left hand of a '||' expr. 11872 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11873 Expr *LHSExpr, Expr *RHSExpr) { 11874 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11875 if (Bop->getOpcode() == BO_LAnd) { 11876 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11877 if (EvaluatesAsFalse(S, RHSExpr)) 11878 return; 11879 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11880 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11881 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11882 } else if (Bop->getOpcode() == BO_LOr) { 11883 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11884 // If it's "a || b && 1 || c" we didn't warn earlier for 11885 // "a || b && 1", but warn now. 11886 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11887 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11888 } 11889 } 11890 } 11891 } 11892 11893 /// \brief Look for '&&' in the right hand of a '||' expr. 11894 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11895 Expr *LHSExpr, Expr *RHSExpr) { 11896 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11897 if (Bop->getOpcode() == BO_LAnd) { 11898 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11899 if (EvaluatesAsFalse(S, LHSExpr)) 11900 return; 11901 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11902 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11903 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11904 } 11905 } 11906 } 11907 11908 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11909 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11910 /// the '&' expression in parentheses. 11911 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11912 SourceLocation OpLoc, Expr *SubExpr) { 11913 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11914 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11915 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11916 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11917 << Bop->getSourceRange() << OpLoc; 11918 SuggestParentheses(S, Bop->getOperatorLoc(), 11919 S.PDiag(diag::note_precedence_silence) 11920 << Bop->getOpcodeStr(), 11921 Bop->getSourceRange()); 11922 } 11923 } 11924 } 11925 11926 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11927 Expr *SubExpr, StringRef Shift) { 11928 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11929 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11930 StringRef Op = Bop->getOpcodeStr(); 11931 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11932 << Bop->getSourceRange() << OpLoc << Shift << Op; 11933 SuggestParentheses(S, Bop->getOperatorLoc(), 11934 S.PDiag(diag::note_precedence_silence) << Op, 11935 Bop->getSourceRange()); 11936 } 11937 } 11938 } 11939 11940 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11941 Expr *LHSExpr, Expr *RHSExpr) { 11942 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11943 if (!OCE) 11944 return; 11945 11946 FunctionDecl *FD = OCE->getDirectCallee(); 11947 if (!FD || !FD->isOverloadedOperator()) 11948 return; 11949 11950 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11951 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11952 return; 11953 11954 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11955 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11956 << (Kind == OO_LessLess); 11957 SuggestParentheses(S, OCE->getOperatorLoc(), 11958 S.PDiag(diag::note_precedence_silence) 11959 << (Kind == OO_LessLess ? "<<" : ">>"), 11960 OCE->getSourceRange()); 11961 SuggestParentheses(S, OpLoc, 11962 S.PDiag(diag::note_evaluate_comparison_first), 11963 SourceRange(OCE->getArg(1)->getLocStart(), 11964 RHSExpr->getLocEnd())); 11965 } 11966 11967 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11968 /// precedence. 11969 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11970 SourceLocation OpLoc, Expr *LHSExpr, 11971 Expr *RHSExpr){ 11972 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11973 if (BinaryOperator::isBitwiseOp(Opc)) 11974 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11975 11976 // Diagnose "arg1 & arg2 | arg3" 11977 if ((Opc == BO_Or || Opc == BO_Xor) && 11978 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11979 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11980 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11981 } 11982 11983 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11984 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11985 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11986 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11987 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11988 } 11989 11990 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11991 || Opc == BO_Shr) { 11992 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11993 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11994 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11995 } 11996 11997 // Warn on overloaded shift operators and comparisons, such as: 11998 // cout << 5 == 4; 11999 if (BinaryOperator::isComparisonOp(Opc)) 12000 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12001 } 12002 12003 // Binary Operators. 'Tok' is the token for the operator. 12004 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12005 tok::TokenKind Kind, 12006 Expr *LHSExpr, Expr *RHSExpr) { 12007 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12008 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12009 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12010 12011 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12012 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12013 12014 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12015 } 12016 12017 /// Build an overloaded binary operator expression in the given scope. 12018 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12019 BinaryOperatorKind Opc, 12020 Expr *LHS, Expr *RHS) { 12021 // Find all of the overloaded operators visible from this 12022 // point. We perform both an operator-name lookup from the local 12023 // scope and an argument-dependent lookup based on the types of 12024 // the arguments. 12025 UnresolvedSet<16> Functions; 12026 OverloadedOperatorKind OverOp 12027 = BinaryOperator::getOverloadedOperator(Opc); 12028 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12029 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12030 RHS->getType(), Functions); 12031 12032 // Build the (potentially-overloaded, potentially-dependent) 12033 // binary operation. 12034 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12035 } 12036 12037 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12038 BinaryOperatorKind Opc, 12039 Expr *LHSExpr, Expr *RHSExpr) { 12040 ExprResult LHS, RHS; 12041 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12042 if (!LHS.isUsable() || !RHS.isUsable()) 12043 return ExprError(); 12044 LHSExpr = LHS.get(); 12045 RHSExpr = RHS.get(); 12046 12047 // We want to end up calling one of checkPseudoObjectAssignment 12048 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12049 // both expressions are overloadable or either is type-dependent), 12050 // or CreateBuiltinBinOp (in any other case). We also want to get 12051 // any placeholder types out of the way. 12052 12053 // Handle pseudo-objects in the LHS. 12054 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12055 // Assignments with a pseudo-object l-value need special analysis. 12056 if (pty->getKind() == BuiltinType::PseudoObject && 12057 BinaryOperator::isAssignmentOp(Opc)) 12058 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12059 12060 // Don't resolve overloads if the other type is overloadable. 12061 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12062 // We can't actually test that if we still have a placeholder, 12063 // though. Fortunately, none of the exceptions we see in that 12064 // code below are valid when the LHS is an overload set. Note 12065 // that an overload set can be dependently-typed, but it never 12066 // instantiates to having an overloadable type. 12067 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12068 if (resolvedRHS.isInvalid()) return ExprError(); 12069 RHSExpr = resolvedRHS.get(); 12070 12071 if (RHSExpr->isTypeDependent() || 12072 RHSExpr->getType()->isOverloadableType()) 12073 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12074 } 12075 12076 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12077 // template, diagnose the missing 'template' keyword instead of diagnosing 12078 // an invalid use of a bound member function. 12079 // 12080 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12081 // to C++1z [over.over]/1.4, but we already checked for that case above. 12082 if (Opc == BO_LT && inTemplateInstantiation() && 12083 (pty->getKind() == BuiltinType::BoundMember || 12084 pty->getKind() == BuiltinType::Overload)) { 12085 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12086 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12087 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12088 return isa<FunctionTemplateDecl>(ND); 12089 })) { 12090 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12091 : OE->getNameLoc(), 12092 diag::err_template_kw_missing) 12093 << OE->getName().getAsString() << ""; 12094 return ExprError(); 12095 } 12096 } 12097 12098 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12099 if (LHS.isInvalid()) return ExprError(); 12100 LHSExpr = LHS.get(); 12101 } 12102 12103 // Handle pseudo-objects in the RHS. 12104 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12105 // An overload in the RHS can potentially be resolved by the type 12106 // being assigned to. 12107 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12108 if (getLangOpts().CPlusPlus && 12109 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12110 LHSExpr->getType()->isOverloadableType())) 12111 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12112 12113 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12114 } 12115 12116 // Don't resolve overloads if the other type is overloadable. 12117 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12118 LHSExpr->getType()->isOverloadableType()) 12119 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12120 12121 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12122 if (!resolvedRHS.isUsable()) return ExprError(); 12123 RHSExpr = resolvedRHS.get(); 12124 } 12125 12126 if (getLangOpts().CPlusPlus) { 12127 // If either expression is type-dependent, always build an 12128 // overloaded op. 12129 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12130 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12131 12132 // Otherwise, build an overloaded op if either expression has an 12133 // overloadable type. 12134 if (LHSExpr->getType()->isOverloadableType() || 12135 RHSExpr->getType()->isOverloadableType()) 12136 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12137 } 12138 12139 // Build a built-in binary operation. 12140 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12141 } 12142 12143 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12144 UnaryOperatorKind Opc, 12145 Expr *InputExpr) { 12146 ExprResult Input = InputExpr; 12147 ExprValueKind VK = VK_RValue; 12148 ExprObjectKind OK = OK_Ordinary; 12149 QualType resultType; 12150 bool ConvertHalfVec = false; 12151 if (getLangOpts().OpenCL) { 12152 QualType Ty = InputExpr->getType(); 12153 // The only legal unary operation for atomics is '&'. 12154 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12155 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12156 // only with a builtin functions and therefore should be disallowed here. 12157 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12158 || Ty->isBlockPointerType())) { 12159 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12160 << InputExpr->getType() 12161 << Input.get()->getSourceRange()); 12162 } 12163 } 12164 switch (Opc) { 12165 case UO_PreInc: 12166 case UO_PreDec: 12167 case UO_PostInc: 12168 case UO_PostDec: 12169 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12170 OpLoc, 12171 Opc == UO_PreInc || 12172 Opc == UO_PostInc, 12173 Opc == UO_PreInc || 12174 Opc == UO_PreDec); 12175 break; 12176 case UO_AddrOf: 12177 resultType = CheckAddressOfOperand(Input, OpLoc); 12178 RecordModifiableNonNullParam(*this, InputExpr); 12179 break; 12180 case UO_Deref: { 12181 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12182 if (Input.isInvalid()) return ExprError(); 12183 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12184 break; 12185 } 12186 case UO_Plus: 12187 case UO_Minus: 12188 Input = UsualUnaryConversions(Input.get()); 12189 if (Input.isInvalid()) return ExprError(); 12190 // Unary plus and minus require promoting an operand of half vector to a 12191 // float vector and truncating the result back to a half vector. For now, we 12192 // do this only when HalfArgsAndReturns is set (that is, when the target is 12193 // arm or arm64). 12194 ConvertHalfVec = 12195 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12196 12197 // If the operand is a half vector, promote it to a float vector. 12198 if (ConvertHalfVec) 12199 Input = convertVector(Input.get(), Context.FloatTy, *this); 12200 resultType = Input.get()->getType(); 12201 if (resultType->isDependentType()) 12202 break; 12203 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12204 break; 12205 else if (resultType->isVectorType() && 12206 // The z vector extensions don't allow + or - with bool vectors. 12207 (!Context.getLangOpts().ZVector || 12208 resultType->getAs<VectorType>()->getVectorKind() != 12209 VectorType::AltiVecBool)) 12210 break; 12211 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12212 Opc == UO_Plus && 12213 resultType->isPointerType()) 12214 break; 12215 12216 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12217 << resultType << Input.get()->getSourceRange()); 12218 12219 case UO_Not: // bitwise complement 12220 Input = UsualUnaryConversions(Input.get()); 12221 if (Input.isInvalid()) 12222 return ExprError(); 12223 resultType = Input.get()->getType(); 12224 if (resultType->isDependentType()) 12225 break; 12226 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12227 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12228 // C99 does not support '~' for complex conjugation. 12229 Diag(OpLoc, diag::ext_integer_complement_complex) 12230 << resultType << Input.get()->getSourceRange(); 12231 else if (resultType->hasIntegerRepresentation()) 12232 break; 12233 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12234 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12235 // on vector float types. 12236 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12237 if (!T->isIntegerType()) 12238 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12239 << resultType << Input.get()->getSourceRange()); 12240 } else { 12241 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12242 << resultType << Input.get()->getSourceRange()); 12243 } 12244 break; 12245 12246 case UO_LNot: // logical negation 12247 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12248 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12249 if (Input.isInvalid()) return ExprError(); 12250 resultType = Input.get()->getType(); 12251 12252 // Though we still have to promote half FP to float... 12253 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12254 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12255 resultType = Context.FloatTy; 12256 } 12257 12258 if (resultType->isDependentType()) 12259 break; 12260 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12261 // C99 6.5.3.3p1: ok, fallthrough; 12262 if (Context.getLangOpts().CPlusPlus) { 12263 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12264 // operand contextually converted to bool. 12265 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12266 ScalarTypeToBooleanCastKind(resultType)); 12267 } else if (Context.getLangOpts().OpenCL && 12268 Context.getLangOpts().OpenCLVersion < 120) { 12269 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12270 // operate on scalar float types. 12271 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12272 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12273 << resultType << Input.get()->getSourceRange()); 12274 } 12275 } else if (resultType->isExtVectorType()) { 12276 if (Context.getLangOpts().OpenCL && 12277 Context.getLangOpts().OpenCLVersion < 120) { 12278 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12279 // operate on vector float types. 12280 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12281 if (!T->isIntegerType()) 12282 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12283 << resultType << Input.get()->getSourceRange()); 12284 } 12285 // Vector logical not returns the signed variant of the operand type. 12286 resultType = GetSignedVectorType(resultType); 12287 break; 12288 } else { 12289 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12290 // type in C++. We should allow that here too. 12291 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12292 << resultType << Input.get()->getSourceRange()); 12293 } 12294 12295 // LNot always has type int. C99 6.5.3.3p5. 12296 // In C++, it's bool. C++ 5.3.1p8 12297 resultType = Context.getLogicalOperationType(); 12298 break; 12299 case UO_Real: 12300 case UO_Imag: 12301 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12302 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12303 // complex l-values to ordinary l-values and all other values to r-values. 12304 if (Input.isInvalid()) return ExprError(); 12305 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12306 if (Input.get()->getValueKind() != VK_RValue && 12307 Input.get()->getObjectKind() == OK_Ordinary) 12308 VK = Input.get()->getValueKind(); 12309 } else if (!getLangOpts().CPlusPlus) { 12310 // In C, a volatile scalar is read by __imag. In C++, it is not. 12311 Input = DefaultLvalueConversion(Input.get()); 12312 } 12313 break; 12314 case UO_Extension: 12315 resultType = Input.get()->getType(); 12316 VK = Input.get()->getValueKind(); 12317 OK = Input.get()->getObjectKind(); 12318 break; 12319 case UO_Coawait: 12320 // It's unnessesary to represent the pass-through operator co_await in the 12321 // AST; just return the input expression instead. 12322 assert(!Input.get()->getType()->isDependentType() && 12323 "the co_await expression must be non-dependant before " 12324 "building operator co_await"); 12325 return Input; 12326 } 12327 if (resultType.isNull() || Input.isInvalid()) 12328 return ExprError(); 12329 12330 // Check for array bounds violations in the operand of the UnaryOperator, 12331 // except for the '*' and '&' operators that have to be handled specially 12332 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12333 // that are explicitly defined as valid by the standard). 12334 if (Opc != UO_AddrOf && Opc != UO_Deref) 12335 CheckArrayAccess(Input.get()); 12336 12337 auto *UO = new (Context) 12338 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 12339 // Convert the result back to a half vector. 12340 if (ConvertHalfVec) 12341 return convertVector(UO, Context.HalfTy, *this); 12342 return UO; 12343 } 12344 12345 /// \brief Determine whether the given expression is a qualified member 12346 /// access expression, of a form that could be turned into a pointer to member 12347 /// with the address-of operator. 12348 static bool isQualifiedMemberAccess(Expr *E) { 12349 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12350 if (!DRE->getQualifier()) 12351 return false; 12352 12353 ValueDecl *VD = DRE->getDecl(); 12354 if (!VD->isCXXClassMember()) 12355 return false; 12356 12357 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12358 return true; 12359 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12360 return Method->isInstance(); 12361 12362 return false; 12363 } 12364 12365 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12366 if (!ULE->getQualifier()) 12367 return false; 12368 12369 for (NamedDecl *D : ULE->decls()) { 12370 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12371 if (Method->isInstance()) 12372 return true; 12373 } else { 12374 // Overload set does not contain methods. 12375 break; 12376 } 12377 } 12378 12379 return false; 12380 } 12381 12382 return false; 12383 } 12384 12385 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12386 UnaryOperatorKind Opc, Expr *Input) { 12387 // First things first: handle placeholders so that the 12388 // overloaded-operator check considers the right type. 12389 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12390 // Increment and decrement of pseudo-object references. 12391 if (pty->getKind() == BuiltinType::PseudoObject && 12392 UnaryOperator::isIncrementDecrementOp(Opc)) 12393 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12394 12395 // extension is always a builtin operator. 12396 if (Opc == UO_Extension) 12397 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12398 12399 // & gets special logic for several kinds of placeholder. 12400 // The builtin code knows what to do. 12401 if (Opc == UO_AddrOf && 12402 (pty->getKind() == BuiltinType::Overload || 12403 pty->getKind() == BuiltinType::UnknownAny || 12404 pty->getKind() == BuiltinType::BoundMember)) 12405 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12406 12407 // Anything else needs to be handled now. 12408 ExprResult Result = CheckPlaceholderExpr(Input); 12409 if (Result.isInvalid()) return ExprError(); 12410 Input = Result.get(); 12411 } 12412 12413 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12414 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12415 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12416 // Find all of the overloaded operators visible from this 12417 // point. We perform both an operator-name lookup from the local 12418 // scope and an argument-dependent lookup based on the types of 12419 // the arguments. 12420 UnresolvedSet<16> Functions; 12421 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12422 if (S && OverOp != OO_None) 12423 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12424 Functions); 12425 12426 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12427 } 12428 12429 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12430 } 12431 12432 // Unary Operators. 'Tok' is the token for the operator. 12433 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12434 tok::TokenKind Op, Expr *Input) { 12435 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12436 } 12437 12438 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12439 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12440 LabelDecl *TheDecl) { 12441 TheDecl->markUsed(Context); 12442 // Create the AST node. The address of a label always has type 'void*'. 12443 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12444 Context.getPointerType(Context.VoidTy)); 12445 } 12446 12447 /// Given the last statement in a statement-expression, check whether 12448 /// the result is a producing expression (like a call to an 12449 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12450 /// release out of the full-expression. Otherwise, return null. 12451 /// Cannot fail. 12452 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12453 // Should always be wrapped with one of these. 12454 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12455 if (!cleanups) return nullptr; 12456 12457 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12458 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12459 return nullptr; 12460 12461 // Splice out the cast. This shouldn't modify any interesting 12462 // features of the statement. 12463 Expr *producer = cast->getSubExpr(); 12464 assert(producer->getType() == cast->getType()); 12465 assert(producer->getValueKind() == cast->getValueKind()); 12466 cleanups->setSubExpr(producer); 12467 return cleanups; 12468 } 12469 12470 void Sema::ActOnStartStmtExpr() { 12471 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12472 } 12473 12474 void Sema::ActOnStmtExprError() { 12475 // Note that function is also called by TreeTransform when leaving a 12476 // StmtExpr scope without rebuilding anything. 12477 12478 DiscardCleanupsInEvaluationContext(); 12479 PopExpressionEvaluationContext(); 12480 } 12481 12482 ExprResult 12483 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12484 SourceLocation RPLoc) { // "({..})" 12485 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12486 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12487 12488 if (hasAnyUnrecoverableErrorsInThisFunction()) 12489 DiscardCleanupsInEvaluationContext(); 12490 assert(!Cleanup.exprNeedsCleanups() && 12491 "cleanups within StmtExpr not correctly bound!"); 12492 PopExpressionEvaluationContext(); 12493 12494 // FIXME: there are a variety of strange constraints to enforce here, for 12495 // example, it is not possible to goto into a stmt expression apparently. 12496 // More semantic analysis is needed. 12497 12498 // If there are sub-stmts in the compound stmt, take the type of the last one 12499 // as the type of the stmtexpr. 12500 QualType Ty = Context.VoidTy; 12501 bool StmtExprMayBindToTemp = false; 12502 if (!Compound->body_empty()) { 12503 Stmt *LastStmt = Compound->body_back(); 12504 LabelStmt *LastLabelStmt = nullptr; 12505 // If LastStmt is a label, skip down through into the body. 12506 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12507 LastLabelStmt = Label; 12508 LastStmt = Label->getSubStmt(); 12509 } 12510 12511 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12512 // Do function/array conversion on the last expression, but not 12513 // lvalue-to-rvalue. However, initialize an unqualified type. 12514 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12515 if (LastExpr.isInvalid()) 12516 return ExprError(); 12517 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12518 12519 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12520 // In ARC, if the final expression ends in a consume, splice 12521 // the consume out and bind it later. In the alternate case 12522 // (when dealing with a retainable type), the result 12523 // initialization will create a produce. In both cases the 12524 // result will be +1, and we'll need to balance that out with 12525 // a bind. 12526 if (Expr *rebuiltLastStmt 12527 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12528 LastExpr = rebuiltLastStmt; 12529 } else { 12530 LastExpr = PerformCopyInitialization( 12531 InitializedEntity::InitializeResult(LPLoc, 12532 Ty, 12533 false), 12534 SourceLocation(), 12535 LastExpr); 12536 } 12537 12538 if (LastExpr.isInvalid()) 12539 return ExprError(); 12540 if (LastExpr.get() != nullptr) { 12541 if (!LastLabelStmt) 12542 Compound->setLastStmt(LastExpr.get()); 12543 else 12544 LastLabelStmt->setSubStmt(LastExpr.get()); 12545 StmtExprMayBindToTemp = true; 12546 } 12547 } 12548 } 12549 } 12550 12551 // FIXME: Check that expression type is complete/non-abstract; statement 12552 // expressions are not lvalues. 12553 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12554 if (StmtExprMayBindToTemp) 12555 return MaybeBindToTemporary(ResStmtExpr); 12556 return ResStmtExpr; 12557 } 12558 12559 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12560 TypeSourceInfo *TInfo, 12561 ArrayRef<OffsetOfComponent> Components, 12562 SourceLocation RParenLoc) { 12563 QualType ArgTy = TInfo->getType(); 12564 bool Dependent = ArgTy->isDependentType(); 12565 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12566 12567 // We must have at least one component that refers to the type, and the first 12568 // one is known to be a field designator. Verify that the ArgTy represents 12569 // a struct/union/class. 12570 if (!Dependent && !ArgTy->isRecordType()) 12571 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12572 << ArgTy << TypeRange); 12573 12574 // Type must be complete per C99 7.17p3 because a declaring a variable 12575 // with an incomplete type would be ill-formed. 12576 if (!Dependent 12577 && RequireCompleteType(BuiltinLoc, ArgTy, 12578 diag::err_offsetof_incomplete_type, TypeRange)) 12579 return ExprError(); 12580 12581 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12582 // GCC extension, diagnose them. 12583 // FIXME: This diagnostic isn't actually visible because the location is in 12584 // a system header! 12585 if (Components.size() != 1) 12586 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12587 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12588 12589 bool DidWarnAboutNonPOD = false; 12590 QualType CurrentType = ArgTy; 12591 SmallVector<OffsetOfNode, 4> Comps; 12592 SmallVector<Expr*, 4> Exprs; 12593 for (const OffsetOfComponent &OC : Components) { 12594 if (OC.isBrackets) { 12595 // Offset of an array sub-field. TODO: Should we allow vector elements? 12596 if (!CurrentType->isDependentType()) { 12597 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12598 if(!AT) 12599 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12600 << CurrentType); 12601 CurrentType = AT->getElementType(); 12602 } else 12603 CurrentType = Context.DependentTy; 12604 12605 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12606 if (IdxRval.isInvalid()) 12607 return ExprError(); 12608 Expr *Idx = IdxRval.get(); 12609 12610 // The expression must be an integral expression. 12611 // FIXME: An integral constant expression? 12612 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12613 !Idx->getType()->isIntegerType()) 12614 return ExprError(Diag(Idx->getLocStart(), 12615 diag::err_typecheck_subscript_not_integer) 12616 << Idx->getSourceRange()); 12617 12618 // Record this array index. 12619 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12620 Exprs.push_back(Idx); 12621 continue; 12622 } 12623 12624 // Offset of a field. 12625 if (CurrentType->isDependentType()) { 12626 // We have the offset of a field, but we can't look into the dependent 12627 // type. Just record the identifier of the field. 12628 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12629 CurrentType = Context.DependentTy; 12630 continue; 12631 } 12632 12633 // We need to have a complete type to look into. 12634 if (RequireCompleteType(OC.LocStart, CurrentType, 12635 diag::err_offsetof_incomplete_type)) 12636 return ExprError(); 12637 12638 // Look for the designated field. 12639 const RecordType *RC = CurrentType->getAs<RecordType>(); 12640 if (!RC) 12641 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12642 << CurrentType); 12643 RecordDecl *RD = RC->getDecl(); 12644 12645 // C++ [lib.support.types]p5: 12646 // The macro offsetof accepts a restricted set of type arguments in this 12647 // International Standard. type shall be a POD structure or a POD union 12648 // (clause 9). 12649 // C++11 [support.types]p4: 12650 // If type is not a standard-layout class (Clause 9), the results are 12651 // undefined. 12652 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12653 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12654 unsigned DiagID = 12655 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12656 : diag::ext_offsetof_non_pod_type; 12657 12658 if (!IsSafe && !DidWarnAboutNonPOD && 12659 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12660 PDiag(DiagID) 12661 << SourceRange(Components[0].LocStart, OC.LocEnd) 12662 << CurrentType)) 12663 DidWarnAboutNonPOD = true; 12664 } 12665 12666 // Look for the field. 12667 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12668 LookupQualifiedName(R, RD); 12669 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12670 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12671 if (!MemberDecl) { 12672 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12673 MemberDecl = IndirectMemberDecl->getAnonField(); 12674 } 12675 12676 if (!MemberDecl) 12677 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12678 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12679 OC.LocEnd)); 12680 12681 // C99 7.17p3: 12682 // (If the specified member is a bit-field, the behavior is undefined.) 12683 // 12684 // We diagnose this as an error. 12685 if (MemberDecl->isBitField()) { 12686 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12687 << MemberDecl->getDeclName() 12688 << SourceRange(BuiltinLoc, RParenLoc); 12689 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12690 return ExprError(); 12691 } 12692 12693 RecordDecl *Parent = MemberDecl->getParent(); 12694 if (IndirectMemberDecl) 12695 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12696 12697 // If the member was found in a base class, introduce OffsetOfNodes for 12698 // the base class indirections. 12699 CXXBasePaths Paths; 12700 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12701 Paths)) { 12702 if (Paths.getDetectedVirtual()) { 12703 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12704 << MemberDecl->getDeclName() 12705 << SourceRange(BuiltinLoc, RParenLoc); 12706 return ExprError(); 12707 } 12708 12709 CXXBasePath &Path = Paths.front(); 12710 for (const CXXBasePathElement &B : Path) 12711 Comps.push_back(OffsetOfNode(B.Base)); 12712 } 12713 12714 if (IndirectMemberDecl) { 12715 for (auto *FI : IndirectMemberDecl->chain()) { 12716 assert(isa<FieldDecl>(FI)); 12717 Comps.push_back(OffsetOfNode(OC.LocStart, 12718 cast<FieldDecl>(FI), OC.LocEnd)); 12719 } 12720 } else 12721 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12722 12723 CurrentType = MemberDecl->getType().getNonReferenceType(); 12724 } 12725 12726 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12727 Comps, Exprs, RParenLoc); 12728 } 12729 12730 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12731 SourceLocation BuiltinLoc, 12732 SourceLocation TypeLoc, 12733 ParsedType ParsedArgTy, 12734 ArrayRef<OffsetOfComponent> Components, 12735 SourceLocation RParenLoc) { 12736 12737 TypeSourceInfo *ArgTInfo; 12738 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12739 if (ArgTy.isNull()) 12740 return ExprError(); 12741 12742 if (!ArgTInfo) 12743 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12744 12745 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12746 } 12747 12748 12749 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12750 Expr *CondExpr, 12751 Expr *LHSExpr, Expr *RHSExpr, 12752 SourceLocation RPLoc) { 12753 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12754 12755 ExprValueKind VK = VK_RValue; 12756 ExprObjectKind OK = OK_Ordinary; 12757 QualType resType; 12758 bool ValueDependent = false; 12759 bool CondIsTrue = false; 12760 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12761 resType = Context.DependentTy; 12762 ValueDependent = true; 12763 } else { 12764 // The conditional expression is required to be a constant expression. 12765 llvm::APSInt condEval(32); 12766 ExprResult CondICE 12767 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12768 diag::err_typecheck_choose_expr_requires_constant, false); 12769 if (CondICE.isInvalid()) 12770 return ExprError(); 12771 CondExpr = CondICE.get(); 12772 CondIsTrue = condEval.getZExtValue(); 12773 12774 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12775 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12776 12777 resType = ActiveExpr->getType(); 12778 ValueDependent = ActiveExpr->isValueDependent(); 12779 VK = ActiveExpr->getValueKind(); 12780 OK = ActiveExpr->getObjectKind(); 12781 } 12782 12783 return new (Context) 12784 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12785 CondIsTrue, resType->isDependentType(), ValueDependent); 12786 } 12787 12788 //===----------------------------------------------------------------------===// 12789 // Clang Extensions. 12790 //===----------------------------------------------------------------------===// 12791 12792 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12793 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12794 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12795 12796 if (LangOpts.CPlusPlus) { 12797 Decl *ManglingContextDecl; 12798 if (MangleNumberingContext *MCtx = 12799 getCurrentMangleNumberContext(Block->getDeclContext(), 12800 ManglingContextDecl)) { 12801 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12802 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12803 } 12804 } 12805 12806 PushBlockScope(CurScope, Block); 12807 CurContext->addDecl(Block); 12808 if (CurScope) 12809 PushDeclContext(CurScope, Block); 12810 else 12811 CurContext = Block; 12812 12813 getCurBlock()->HasImplicitReturnType = true; 12814 12815 // Enter a new evaluation context to insulate the block from any 12816 // cleanups from the enclosing full-expression. 12817 PushExpressionEvaluationContext( 12818 ExpressionEvaluationContext::PotentiallyEvaluated); 12819 } 12820 12821 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12822 Scope *CurScope) { 12823 assert(ParamInfo.getIdentifier() == nullptr && 12824 "block-id should have no identifier!"); 12825 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12826 BlockScopeInfo *CurBlock = getCurBlock(); 12827 12828 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12829 QualType T = Sig->getType(); 12830 12831 // FIXME: We should allow unexpanded parameter packs here, but that would, 12832 // in turn, make the block expression contain unexpanded parameter packs. 12833 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12834 // Drop the parameters. 12835 FunctionProtoType::ExtProtoInfo EPI; 12836 EPI.HasTrailingReturn = false; 12837 EPI.TypeQuals |= DeclSpec::TQ_const; 12838 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12839 Sig = Context.getTrivialTypeSourceInfo(T); 12840 } 12841 12842 // GetTypeForDeclarator always produces a function type for a block 12843 // literal signature. Furthermore, it is always a FunctionProtoType 12844 // unless the function was written with a typedef. 12845 assert(T->isFunctionType() && 12846 "GetTypeForDeclarator made a non-function block signature"); 12847 12848 // Look for an explicit signature in that function type. 12849 FunctionProtoTypeLoc ExplicitSignature; 12850 12851 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12852 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12853 12854 // Check whether that explicit signature was synthesized by 12855 // GetTypeForDeclarator. If so, don't save that as part of the 12856 // written signature. 12857 if (ExplicitSignature.getLocalRangeBegin() == 12858 ExplicitSignature.getLocalRangeEnd()) { 12859 // This would be much cheaper if we stored TypeLocs instead of 12860 // TypeSourceInfos. 12861 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12862 unsigned Size = Result.getFullDataSize(); 12863 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12864 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12865 12866 ExplicitSignature = FunctionProtoTypeLoc(); 12867 } 12868 } 12869 12870 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12871 CurBlock->FunctionType = T; 12872 12873 const FunctionType *Fn = T->getAs<FunctionType>(); 12874 QualType RetTy = Fn->getReturnType(); 12875 bool isVariadic = 12876 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12877 12878 CurBlock->TheDecl->setIsVariadic(isVariadic); 12879 12880 // Context.DependentTy is used as a placeholder for a missing block 12881 // return type. TODO: what should we do with declarators like: 12882 // ^ * { ... } 12883 // If the answer is "apply template argument deduction".... 12884 if (RetTy != Context.DependentTy) { 12885 CurBlock->ReturnType = RetTy; 12886 CurBlock->TheDecl->setBlockMissingReturnType(false); 12887 CurBlock->HasImplicitReturnType = false; 12888 } 12889 12890 // Push block parameters from the declarator if we had them. 12891 SmallVector<ParmVarDecl*, 8> Params; 12892 if (ExplicitSignature) { 12893 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12894 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12895 if (Param->getIdentifier() == nullptr && 12896 !Param->isImplicit() && 12897 !Param->isInvalidDecl() && 12898 !getLangOpts().CPlusPlus) 12899 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12900 Params.push_back(Param); 12901 } 12902 12903 // Fake up parameter variables if we have a typedef, like 12904 // ^ fntype { ... } 12905 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12906 for (const auto &I : Fn->param_types()) { 12907 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12908 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12909 Params.push_back(Param); 12910 } 12911 } 12912 12913 // Set the parameters on the block decl. 12914 if (!Params.empty()) { 12915 CurBlock->TheDecl->setParams(Params); 12916 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12917 /*CheckParameterNames=*/false); 12918 } 12919 12920 // Finally we can process decl attributes. 12921 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12922 12923 // Put the parameter variables in scope. 12924 for (auto AI : CurBlock->TheDecl->parameters()) { 12925 AI->setOwningFunction(CurBlock->TheDecl); 12926 12927 // If this has an identifier, add it to the scope stack. 12928 if (AI->getIdentifier()) { 12929 CheckShadow(CurBlock->TheScope, AI); 12930 12931 PushOnScopeChains(AI, CurBlock->TheScope); 12932 } 12933 } 12934 } 12935 12936 /// ActOnBlockError - If there is an error parsing a block, this callback 12937 /// is invoked to pop the information about the block from the action impl. 12938 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12939 // Leave the expression-evaluation context. 12940 DiscardCleanupsInEvaluationContext(); 12941 PopExpressionEvaluationContext(); 12942 12943 // Pop off CurBlock, handle nested blocks. 12944 PopDeclContext(); 12945 PopFunctionScopeInfo(); 12946 } 12947 12948 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12949 /// literal was successfully completed. ^(int x){...} 12950 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12951 Stmt *Body, Scope *CurScope) { 12952 // If blocks are disabled, emit an error. 12953 if (!LangOpts.Blocks) 12954 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12955 12956 // Leave the expression-evaluation context. 12957 if (hasAnyUnrecoverableErrorsInThisFunction()) 12958 DiscardCleanupsInEvaluationContext(); 12959 assert(!Cleanup.exprNeedsCleanups() && 12960 "cleanups within block not correctly bound!"); 12961 PopExpressionEvaluationContext(); 12962 12963 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12964 12965 if (BSI->HasImplicitReturnType) 12966 deduceClosureReturnType(*BSI); 12967 12968 PopDeclContext(); 12969 12970 QualType RetTy = Context.VoidTy; 12971 if (!BSI->ReturnType.isNull()) 12972 RetTy = BSI->ReturnType; 12973 12974 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12975 QualType BlockTy; 12976 12977 // Set the captured variables on the block. 12978 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12979 SmallVector<BlockDecl::Capture, 4> Captures; 12980 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12981 if (Cap.isThisCapture()) 12982 continue; 12983 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12984 Cap.isNested(), Cap.getInitExpr()); 12985 Captures.push_back(NewCap); 12986 } 12987 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12988 12989 // If the user wrote a function type in some form, try to use that. 12990 if (!BSI->FunctionType.isNull()) { 12991 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12992 12993 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12994 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12995 12996 // Turn protoless block types into nullary block types. 12997 if (isa<FunctionNoProtoType>(FTy)) { 12998 FunctionProtoType::ExtProtoInfo EPI; 12999 EPI.ExtInfo = Ext; 13000 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13001 13002 // Otherwise, if we don't need to change anything about the function type, 13003 // preserve its sugar structure. 13004 } else if (FTy->getReturnType() == RetTy && 13005 (!NoReturn || FTy->getNoReturnAttr())) { 13006 BlockTy = BSI->FunctionType; 13007 13008 // Otherwise, make the minimal modifications to the function type. 13009 } else { 13010 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13011 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13012 EPI.TypeQuals = 0; // FIXME: silently? 13013 EPI.ExtInfo = Ext; 13014 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13015 } 13016 13017 // If we don't have a function type, just build one from nothing. 13018 } else { 13019 FunctionProtoType::ExtProtoInfo EPI; 13020 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13021 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13022 } 13023 13024 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13025 BlockTy = Context.getBlockPointerType(BlockTy); 13026 13027 // If needed, diagnose invalid gotos and switches in the block. 13028 if (getCurFunction()->NeedsScopeChecking() && 13029 !PP.isCodeCompletionEnabled()) 13030 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13031 13032 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13033 13034 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13035 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13036 13037 // Try to apply the named return value optimization. We have to check again 13038 // if we can do this, though, because blocks keep return statements around 13039 // to deduce an implicit return type. 13040 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13041 !BSI->TheDecl->isDependentContext()) 13042 computeNRVO(Body, BSI); 13043 13044 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13045 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13046 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13047 13048 // If the block isn't obviously global, i.e. it captures anything at 13049 // all, then we need to do a few things in the surrounding context: 13050 if (Result->getBlockDecl()->hasCaptures()) { 13051 // First, this expression has a new cleanup object. 13052 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13053 Cleanup.setExprNeedsCleanups(true); 13054 13055 // It also gets a branch-protected scope if any of the captured 13056 // variables needs destruction. 13057 for (const auto &CI : Result->getBlockDecl()->captures()) { 13058 const VarDecl *var = CI.getVariable(); 13059 if (var->getType().isDestructedType() != QualType::DK_none) { 13060 getCurFunction()->setHasBranchProtectedScope(); 13061 break; 13062 } 13063 } 13064 } 13065 13066 return Result; 13067 } 13068 13069 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13070 SourceLocation RPLoc) { 13071 TypeSourceInfo *TInfo; 13072 GetTypeFromParser(Ty, &TInfo); 13073 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13074 } 13075 13076 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13077 Expr *E, TypeSourceInfo *TInfo, 13078 SourceLocation RPLoc) { 13079 Expr *OrigExpr = E; 13080 bool IsMS = false; 13081 13082 // CUDA device code does not support varargs. 13083 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13084 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13085 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13086 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13087 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13088 } 13089 } 13090 13091 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13092 // as Microsoft ABI on an actual Microsoft platform, where 13093 // __builtin_ms_va_list and __builtin_va_list are the same.) 13094 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13095 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13096 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13097 if (Context.hasSameType(MSVaListType, E->getType())) { 13098 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13099 return ExprError(); 13100 IsMS = true; 13101 } 13102 } 13103 13104 // Get the va_list type 13105 QualType VaListType = Context.getBuiltinVaListType(); 13106 if (!IsMS) { 13107 if (VaListType->isArrayType()) { 13108 // Deal with implicit array decay; for example, on x86-64, 13109 // va_list is an array, but it's supposed to decay to 13110 // a pointer for va_arg. 13111 VaListType = Context.getArrayDecayedType(VaListType); 13112 // Make sure the input expression also decays appropriately. 13113 ExprResult Result = UsualUnaryConversions(E); 13114 if (Result.isInvalid()) 13115 return ExprError(); 13116 E = Result.get(); 13117 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13118 // If va_list is a record type and we are compiling in C++ mode, 13119 // check the argument using reference binding. 13120 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13121 Context, Context.getLValueReferenceType(VaListType), false); 13122 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13123 if (Init.isInvalid()) 13124 return ExprError(); 13125 E = Init.getAs<Expr>(); 13126 } else { 13127 // Otherwise, the va_list argument must be an l-value because 13128 // it is modified by va_arg. 13129 if (!E->isTypeDependent() && 13130 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13131 return ExprError(); 13132 } 13133 } 13134 13135 if (!IsMS && !E->isTypeDependent() && 13136 !Context.hasSameType(VaListType, E->getType())) 13137 return ExprError(Diag(E->getLocStart(), 13138 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13139 << OrigExpr->getType() << E->getSourceRange()); 13140 13141 if (!TInfo->getType()->isDependentType()) { 13142 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13143 diag::err_second_parameter_to_va_arg_incomplete, 13144 TInfo->getTypeLoc())) 13145 return ExprError(); 13146 13147 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13148 TInfo->getType(), 13149 diag::err_second_parameter_to_va_arg_abstract, 13150 TInfo->getTypeLoc())) 13151 return ExprError(); 13152 13153 if (!TInfo->getType().isPODType(Context)) { 13154 Diag(TInfo->getTypeLoc().getBeginLoc(), 13155 TInfo->getType()->isObjCLifetimeType() 13156 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13157 : diag::warn_second_parameter_to_va_arg_not_pod) 13158 << TInfo->getType() 13159 << TInfo->getTypeLoc().getSourceRange(); 13160 } 13161 13162 // Check for va_arg where arguments of the given type will be promoted 13163 // (i.e. this va_arg is guaranteed to have undefined behavior). 13164 QualType PromoteType; 13165 if (TInfo->getType()->isPromotableIntegerType()) { 13166 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13167 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13168 PromoteType = QualType(); 13169 } 13170 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13171 PromoteType = Context.DoubleTy; 13172 if (!PromoteType.isNull()) 13173 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13174 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13175 << TInfo->getType() 13176 << PromoteType 13177 << TInfo->getTypeLoc().getSourceRange()); 13178 } 13179 13180 QualType T = TInfo->getType().getNonLValueExprType(Context); 13181 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13182 } 13183 13184 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13185 // The type of __null will be int or long, depending on the size of 13186 // pointers on the target. 13187 QualType Ty; 13188 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13189 if (pw == Context.getTargetInfo().getIntWidth()) 13190 Ty = Context.IntTy; 13191 else if (pw == Context.getTargetInfo().getLongWidth()) 13192 Ty = Context.LongTy; 13193 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13194 Ty = Context.LongLongTy; 13195 else { 13196 llvm_unreachable("I don't know size of pointer!"); 13197 } 13198 13199 return new (Context) GNUNullExpr(Ty, TokenLoc); 13200 } 13201 13202 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13203 bool Diagnose) { 13204 if (!getLangOpts().ObjC1) 13205 return false; 13206 13207 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13208 if (!PT) 13209 return false; 13210 13211 if (!PT->isObjCIdType()) { 13212 // Check if the destination is the 'NSString' interface. 13213 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13214 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13215 return false; 13216 } 13217 13218 // Ignore any parens, implicit casts (should only be 13219 // array-to-pointer decays), and not-so-opaque values. The last is 13220 // important for making this trigger for property assignments. 13221 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13222 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13223 if (OV->getSourceExpr()) 13224 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13225 13226 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13227 if (!SL || !SL->isAscii()) 13228 return false; 13229 if (Diagnose) { 13230 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13231 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13232 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13233 } 13234 return true; 13235 } 13236 13237 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13238 const Expr *SrcExpr) { 13239 if (!DstType->isFunctionPointerType() || 13240 !SrcExpr->getType()->isFunctionType()) 13241 return false; 13242 13243 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13244 if (!DRE) 13245 return false; 13246 13247 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13248 if (!FD) 13249 return false; 13250 13251 return !S.checkAddressOfFunctionIsAvailable(FD, 13252 /*Complain=*/true, 13253 SrcExpr->getLocStart()); 13254 } 13255 13256 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13257 SourceLocation Loc, 13258 QualType DstType, QualType SrcType, 13259 Expr *SrcExpr, AssignmentAction Action, 13260 bool *Complained) { 13261 if (Complained) 13262 *Complained = false; 13263 13264 // Decode the result (notice that AST's are still created for extensions). 13265 bool CheckInferredResultType = false; 13266 bool isInvalid = false; 13267 unsigned DiagKind = 0; 13268 FixItHint Hint; 13269 ConversionFixItGenerator ConvHints; 13270 bool MayHaveConvFixit = false; 13271 bool MayHaveFunctionDiff = false; 13272 const ObjCInterfaceDecl *IFace = nullptr; 13273 const ObjCProtocolDecl *PDecl = nullptr; 13274 13275 switch (ConvTy) { 13276 case Compatible: 13277 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13278 return false; 13279 13280 case PointerToInt: 13281 DiagKind = diag::ext_typecheck_convert_pointer_int; 13282 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13283 MayHaveConvFixit = true; 13284 break; 13285 case IntToPointer: 13286 DiagKind = diag::ext_typecheck_convert_int_pointer; 13287 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13288 MayHaveConvFixit = true; 13289 break; 13290 case IncompatiblePointer: 13291 if (Action == AA_Passing_CFAudited) 13292 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13293 else if (SrcType->isFunctionPointerType() && 13294 DstType->isFunctionPointerType()) 13295 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13296 else 13297 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13298 13299 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13300 SrcType->isObjCObjectPointerType(); 13301 if (Hint.isNull() && !CheckInferredResultType) { 13302 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13303 } 13304 else if (CheckInferredResultType) { 13305 SrcType = SrcType.getUnqualifiedType(); 13306 DstType = DstType.getUnqualifiedType(); 13307 } 13308 MayHaveConvFixit = true; 13309 break; 13310 case IncompatiblePointerSign: 13311 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13312 break; 13313 case FunctionVoidPointer: 13314 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13315 break; 13316 case IncompatiblePointerDiscardsQualifiers: { 13317 // Perform array-to-pointer decay if necessary. 13318 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13319 13320 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13321 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13322 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13323 DiagKind = diag::err_typecheck_incompatible_address_space; 13324 break; 13325 13326 13327 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13328 DiagKind = diag::err_typecheck_incompatible_ownership; 13329 break; 13330 } 13331 13332 llvm_unreachable("unknown error case for discarding qualifiers!"); 13333 // fallthrough 13334 } 13335 case CompatiblePointerDiscardsQualifiers: 13336 // If the qualifiers lost were because we were applying the 13337 // (deprecated) C++ conversion from a string literal to a char* 13338 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13339 // Ideally, this check would be performed in 13340 // checkPointerTypesForAssignment. However, that would require a 13341 // bit of refactoring (so that the second argument is an 13342 // expression, rather than a type), which should be done as part 13343 // of a larger effort to fix checkPointerTypesForAssignment for 13344 // C++ semantics. 13345 if (getLangOpts().CPlusPlus && 13346 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13347 return false; 13348 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13349 break; 13350 case IncompatibleNestedPointerQualifiers: 13351 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13352 break; 13353 case IntToBlockPointer: 13354 DiagKind = diag::err_int_to_block_pointer; 13355 break; 13356 case IncompatibleBlockPointer: 13357 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13358 break; 13359 case IncompatibleObjCQualifiedId: { 13360 if (SrcType->isObjCQualifiedIdType()) { 13361 const ObjCObjectPointerType *srcOPT = 13362 SrcType->getAs<ObjCObjectPointerType>(); 13363 for (auto *srcProto : srcOPT->quals()) { 13364 PDecl = srcProto; 13365 break; 13366 } 13367 if (const ObjCInterfaceType *IFaceT = 13368 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13369 IFace = IFaceT->getDecl(); 13370 } 13371 else if (DstType->isObjCQualifiedIdType()) { 13372 const ObjCObjectPointerType *dstOPT = 13373 DstType->getAs<ObjCObjectPointerType>(); 13374 for (auto *dstProto : dstOPT->quals()) { 13375 PDecl = dstProto; 13376 break; 13377 } 13378 if (const ObjCInterfaceType *IFaceT = 13379 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13380 IFace = IFaceT->getDecl(); 13381 } 13382 DiagKind = diag::warn_incompatible_qualified_id; 13383 break; 13384 } 13385 case IncompatibleVectors: 13386 DiagKind = diag::warn_incompatible_vectors; 13387 break; 13388 case IncompatibleObjCWeakRef: 13389 DiagKind = diag::err_arc_weak_unavailable_assign; 13390 break; 13391 case Incompatible: 13392 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13393 if (Complained) 13394 *Complained = true; 13395 return true; 13396 } 13397 13398 DiagKind = diag::err_typecheck_convert_incompatible; 13399 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13400 MayHaveConvFixit = true; 13401 isInvalid = true; 13402 MayHaveFunctionDiff = true; 13403 break; 13404 } 13405 13406 QualType FirstType, SecondType; 13407 switch (Action) { 13408 case AA_Assigning: 13409 case AA_Initializing: 13410 // The destination type comes first. 13411 FirstType = DstType; 13412 SecondType = SrcType; 13413 break; 13414 13415 case AA_Returning: 13416 case AA_Passing: 13417 case AA_Passing_CFAudited: 13418 case AA_Converting: 13419 case AA_Sending: 13420 case AA_Casting: 13421 // The source type comes first. 13422 FirstType = SrcType; 13423 SecondType = DstType; 13424 break; 13425 } 13426 13427 PartialDiagnostic FDiag = PDiag(DiagKind); 13428 if (Action == AA_Passing_CFAudited) 13429 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13430 else 13431 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13432 13433 // If we can fix the conversion, suggest the FixIts. 13434 assert(ConvHints.isNull() || Hint.isNull()); 13435 if (!ConvHints.isNull()) { 13436 for (FixItHint &H : ConvHints.Hints) 13437 FDiag << H; 13438 } else { 13439 FDiag << Hint; 13440 } 13441 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13442 13443 if (MayHaveFunctionDiff) 13444 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13445 13446 Diag(Loc, FDiag); 13447 if (DiagKind == diag::warn_incompatible_qualified_id && 13448 PDecl && IFace && !IFace->hasDefinition()) 13449 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13450 << IFace->getName() << PDecl->getName(); 13451 13452 if (SecondType == Context.OverloadTy) 13453 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13454 FirstType, /*TakingAddress=*/true); 13455 13456 if (CheckInferredResultType) 13457 EmitRelatedResultTypeNote(SrcExpr); 13458 13459 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13460 EmitRelatedResultTypeNoteForReturn(DstType); 13461 13462 if (Complained) 13463 *Complained = true; 13464 return isInvalid; 13465 } 13466 13467 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13468 llvm::APSInt *Result) { 13469 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13470 public: 13471 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13472 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13473 } 13474 } Diagnoser; 13475 13476 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13477 } 13478 13479 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13480 llvm::APSInt *Result, 13481 unsigned DiagID, 13482 bool AllowFold) { 13483 class IDDiagnoser : public VerifyICEDiagnoser { 13484 unsigned DiagID; 13485 13486 public: 13487 IDDiagnoser(unsigned DiagID) 13488 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13489 13490 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13491 S.Diag(Loc, DiagID) << SR; 13492 } 13493 } Diagnoser(DiagID); 13494 13495 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13496 } 13497 13498 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13499 SourceRange SR) { 13500 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13501 } 13502 13503 ExprResult 13504 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13505 VerifyICEDiagnoser &Diagnoser, 13506 bool AllowFold) { 13507 SourceLocation DiagLoc = E->getLocStart(); 13508 13509 if (getLangOpts().CPlusPlus11) { 13510 // C++11 [expr.const]p5: 13511 // If an expression of literal class type is used in a context where an 13512 // integral constant expression is required, then that class type shall 13513 // have a single non-explicit conversion function to an integral or 13514 // unscoped enumeration type 13515 ExprResult Converted; 13516 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13517 public: 13518 CXX11ConvertDiagnoser(bool Silent) 13519 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13520 Silent, true) {} 13521 13522 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13523 QualType T) override { 13524 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13525 } 13526 13527 SemaDiagnosticBuilder diagnoseIncomplete( 13528 Sema &S, SourceLocation Loc, QualType T) override { 13529 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13530 } 13531 13532 SemaDiagnosticBuilder diagnoseExplicitConv( 13533 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13534 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13535 } 13536 13537 SemaDiagnosticBuilder noteExplicitConv( 13538 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13539 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13540 << ConvTy->isEnumeralType() << ConvTy; 13541 } 13542 13543 SemaDiagnosticBuilder diagnoseAmbiguous( 13544 Sema &S, SourceLocation Loc, QualType T) override { 13545 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13546 } 13547 13548 SemaDiagnosticBuilder noteAmbiguous( 13549 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13550 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13551 << ConvTy->isEnumeralType() << ConvTy; 13552 } 13553 13554 SemaDiagnosticBuilder diagnoseConversion( 13555 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13556 llvm_unreachable("conversion functions are permitted"); 13557 } 13558 } ConvertDiagnoser(Diagnoser.Suppress); 13559 13560 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13561 ConvertDiagnoser); 13562 if (Converted.isInvalid()) 13563 return Converted; 13564 E = Converted.get(); 13565 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13566 return ExprError(); 13567 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13568 // An ICE must be of integral or unscoped enumeration type. 13569 if (!Diagnoser.Suppress) 13570 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13571 return ExprError(); 13572 } 13573 13574 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13575 // in the non-ICE case. 13576 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13577 if (Result) 13578 *Result = E->EvaluateKnownConstInt(Context); 13579 return E; 13580 } 13581 13582 Expr::EvalResult EvalResult; 13583 SmallVector<PartialDiagnosticAt, 8> Notes; 13584 EvalResult.Diag = &Notes; 13585 13586 // Try to evaluate the expression, and produce diagnostics explaining why it's 13587 // not a constant expression as a side-effect. 13588 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13589 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13590 13591 // In C++11, we can rely on diagnostics being produced for any expression 13592 // which is not a constant expression. If no diagnostics were produced, then 13593 // this is a constant expression. 13594 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13595 if (Result) 13596 *Result = EvalResult.Val.getInt(); 13597 return E; 13598 } 13599 13600 // If our only note is the usual "invalid subexpression" note, just point 13601 // the caret at its location rather than producing an essentially 13602 // redundant note. 13603 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13604 diag::note_invalid_subexpr_in_const_expr) { 13605 DiagLoc = Notes[0].first; 13606 Notes.clear(); 13607 } 13608 13609 if (!Folded || !AllowFold) { 13610 if (!Diagnoser.Suppress) { 13611 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13612 for (const PartialDiagnosticAt &Note : Notes) 13613 Diag(Note.first, Note.second); 13614 } 13615 13616 return ExprError(); 13617 } 13618 13619 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13620 for (const PartialDiagnosticAt &Note : Notes) 13621 Diag(Note.first, Note.second); 13622 13623 if (Result) 13624 *Result = EvalResult.Val.getInt(); 13625 return E; 13626 } 13627 13628 namespace { 13629 // Handle the case where we conclude a expression which we speculatively 13630 // considered to be unevaluated is actually evaluated. 13631 class TransformToPE : public TreeTransform<TransformToPE> { 13632 typedef TreeTransform<TransformToPE> BaseTransform; 13633 13634 public: 13635 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13636 13637 // Make sure we redo semantic analysis 13638 bool AlwaysRebuild() { return true; } 13639 13640 // Make sure we handle LabelStmts correctly. 13641 // FIXME: This does the right thing, but maybe we need a more general 13642 // fix to TreeTransform? 13643 StmtResult TransformLabelStmt(LabelStmt *S) { 13644 S->getDecl()->setStmt(nullptr); 13645 return BaseTransform::TransformLabelStmt(S); 13646 } 13647 13648 // We need to special-case DeclRefExprs referring to FieldDecls which 13649 // are not part of a member pointer formation; normal TreeTransforming 13650 // doesn't catch this case because of the way we represent them in the AST. 13651 // FIXME: This is a bit ugly; is it really the best way to handle this 13652 // case? 13653 // 13654 // Error on DeclRefExprs referring to FieldDecls. 13655 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13656 if (isa<FieldDecl>(E->getDecl()) && 13657 !SemaRef.isUnevaluatedContext()) 13658 return SemaRef.Diag(E->getLocation(), 13659 diag::err_invalid_non_static_member_use) 13660 << E->getDecl() << E->getSourceRange(); 13661 13662 return BaseTransform::TransformDeclRefExpr(E); 13663 } 13664 13665 // Exception: filter out member pointer formation 13666 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13667 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13668 return E; 13669 13670 return BaseTransform::TransformUnaryOperator(E); 13671 } 13672 13673 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13674 // Lambdas never need to be transformed. 13675 return E; 13676 } 13677 }; 13678 } 13679 13680 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13681 assert(isUnevaluatedContext() && 13682 "Should only transform unevaluated expressions"); 13683 ExprEvalContexts.back().Context = 13684 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13685 if (isUnevaluatedContext()) 13686 return E; 13687 return TransformToPE(*this).TransformExpr(E); 13688 } 13689 13690 void 13691 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13692 Decl *LambdaContextDecl, 13693 bool IsDecltype) { 13694 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13695 LambdaContextDecl, IsDecltype); 13696 Cleanup.reset(); 13697 if (!MaybeODRUseExprs.empty()) 13698 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13699 } 13700 13701 void 13702 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13703 ReuseLambdaContextDecl_t, 13704 bool IsDecltype) { 13705 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13706 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13707 } 13708 13709 void Sema::PopExpressionEvaluationContext() { 13710 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13711 unsigned NumTypos = Rec.NumTypos; 13712 13713 if (!Rec.Lambdas.empty()) { 13714 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13715 unsigned D; 13716 if (Rec.isUnevaluated()) { 13717 // C++11 [expr.prim.lambda]p2: 13718 // A lambda-expression shall not appear in an unevaluated operand 13719 // (Clause 5). 13720 D = diag::err_lambda_unevaluated_operand; 13721 } else { 13722 // C++1y [expr.const]p2: 13723 // A conditional-expression e is a core constant expression unless the 13724 // evaluation of e, following the rules of the abstract machine, would 13725 // evaluate [...] a lambda-expression. 13726 D = diag::err_lambda_in_constant_expression; 13727 } 13728 13729 // C++1z allows lambda expressions as core constant expressions. 13730 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13731 // 1607) from appearing within template-arguments and array-bounds that 13732 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13733 // unevaluated contexts) might lift some of these restrictions in a 13734 // future version. 13735 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13736 for (const auto *L : Rec.Lambdas) 13737 Diag(L->getLocStart(), D); 13738 } else { 13739 // Mark the capture expressions odr-used. This was deferred 13740 // during lambda expression creation. 13741 for (auto *Lambda : Rec.Lambdas) { 13742 for (auto *C : Lambda->capture_inits()) 13743 MarkDeclarationsReferencedInExpr(C); 13744 } 13745 } 13746 } 13747 13748 // When are coming out of an unevaluated context, clear out any 13749 // temporaries that we may have created as part of the evaluation of 13750 // the expression in that context: they aren't relevant because they 13751 // will never be constructed. 13752 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13753 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13754 ExprCleanupObjects.end()); 13755 Cleanup = Rec.ParentCleanup; 13756 CleanupVarDeclMarking(); 13757 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13758 // Otherwise, merge the contexts together. 13759 } else { 13760 Cleanup.mergeFrom(Rec.ParentCleanup); 13761 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13762 Rec.SavedMaybeODRUseExprs.end()); 13763 } 13764 13765 // Pop the current expression evaluation context off the stack. 13766 ExprEvalContexts.pop_back(); 13767 13768 if (!ExprEvalContexts.empty()) 13769 ExprEvalContexts.back().NumTypos += NumTypos; 13770 else 13771 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13772 "last ExpressionEvaluationContextRecord"); 13773 } 13774 13775 void Sema::DiscardCleanupsInEvaluationContext() { 13776 ExprCleanupObjects.erase( 13777 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13778 ExprCleanupObjects.end()); 13779 Cleanup.reset(); 13780 MaybeODRUseExprs.clear(); 13781 } 13782 13783 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13784 if (!E->getType()->isVariablyModifiedType()) 13785 return E; 13786 return TransformToPotentiallyEvaluated(E); 13787 } 13788 13789 /// Are we within a context in which some evaluation could be performed (be it 13790 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13791 /// captured by C++'s idea of an "unevaluated context". 13792 static bool isEvaluatableContext(Sema &SemaRef) { 13793 switch (SemaRef.ExprEvalContexts.back().Context) { 13794 case Sema::ExpressionEvaluationContext::Unevaluated: 13795 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13796 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13797 // Expressions in this context are never evaluated. 13798 return false; 13799 13800 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13801 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13802 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13803 // Expressions in this context could be evaluated. 13804 return true; 13805 13806 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13807 // Referenced declarations will only be used if the construct in the 13808 // containing expression is used, at which point we'll be given another 13809 // turn to mark them. 13810 return false; 13811 } 13812 llvm_unreachable("Invalid context"); 13813 } 13814 13815 /// Are we within a context in which references to resolved functions or to 13816 /// variables result in odr-use? 13817 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13818 // An expression in a template is not really an expression until it's been 13819 // instantiated, so it doesn't trigger odr-use. 13820 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13821 return false; 13822 13823 switch (SemaRef.ExprEvalContexts.back().Context) { 13824 case Sema::ExpressionEvaluationContext::Unevaluated: 13825 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13826 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13827 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13828 return false; 13829 13830 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13831 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13832 return true; 13833 13834 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13835 return false; 13836 } 13837 llvm_unreachable("Invalid context"); 13838 } 13839 13840 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13841 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13842 return Func->isConstexpr() && 13843 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13844 } 13845 13846 /// \brief Mark a function referenced, and check whether it is odr-used 13847 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13848 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13849 bool MightBeOdrUse) { 13850 assert(Func && "No function?"); 13851 13852 Func->setReferenced(); 13853 13854 // C++11 [basic.def.odr]p3: 13855 // A function whose name appears as a potentially-evaluated expression is 13856 // odr-used if it is the unique lookup result or the selected member of a 13857 // set of overloaded functions [...]. 13858 // 13859 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13860 // can just check that here. 13861 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13862 13863 // Determine whether we require a function definition to exist, per 13864 // C++11 [temp.inst]p3: 13865 // Unless a function template specialization has been explicitly 13866 // instantiated or explicitly specialized, the function template 13867 // specialization is implicitly instantiated when the specialization is 13868 // referenced in a context that requires a function definition to exist. 13869 // 13870 // That is either when this is an odr-use, or when a usage of a constexpr 13871 // function occurs within an evaluatable context. 13872 bool NeedDefinition = 13873 OdrUse || (isEvaluatableContext(*this) && 13874 isImplicitlyDefinableConstexprFunction(Func)); 13875 13876 // C++14 [temp.expl.spec]p6: 13877 // If a template [...] is explicitly specialized then that specialization 13878 // shall be declared before the first use of that specialization that would 13879 // cause an implicit instantiation to take place, in every translation unit 13880 // in which such a use occurs 13881 if (NeedDefinition && 13882 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13883 Func->getMemberSpecializationInfo())) 13884 checkSpecializationVisibility(Loc, Func); 13885 13886 // C++14 [except.spec]p17: 13887 // An exception-specification is considered to be needed when: 13888 // - the function is odr-used or, if it appears in an unevaluated operand, 13889 // would be odr-used if the expression were potentially-evaluated; 13890 // 13891 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13892 // function is a pure virtual function we're calling, and in that case the 13893 // function was selected by overload resolution and we need to resolve its 13894 // exception specification for a different reason. 13895 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13896 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13897 ResolveExceptionSpec(Loc, FPT); 13898 13899 // If we don't need to mark the function as used, and we don't need to 13900 // try to provide a definition, there's nothing more to do. 13901 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13902 (!NeedDefinition || Func->getBody())) 13903 return; 13904 13905 // Note that this declaration has been used. 13906 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13907 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13908 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13909 if (Constructor->isDefaultConstructor()) { 13910 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13911 return; 13912 DefineImplicitDefaultConstructor(Loc, Constructor); 13913 } else if (Constructor->isCopyConstructor()) { 13914 DefineImplicitCopyConstructor(Loc, Constructor); 13915 } else if (Constructor->isMoveConstructor()) { 13916 DefineImplicitMoveConstructor(Loc, Constructor); 13917 } 13918 } else if (Constructor->getInheritedConstructor()) { 13919 DefineInheritingConstructor(Loc, Constructor); 13920 } 13921 } else if (CXXDestructorDecl *Destructor = 13922 dyn_cast<CXXDestructorDecl>(Func)) { 13923 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13924 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13925 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13926 return; 13927 DefineImplicitDestructor(Loc, Destructor); 13928 } 13929 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13930 MarkVTableUsed(Loc, Destructor->getParent()); 13931 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13932 if (MethodDecl->isOverloadedOperator() && 13933 MethodDecl->getOverloadedOperator() == OO_Equal) { 13934 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13935 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13936 if (MethodDecl->isCopyAssignmentOperator()) 13937 DefineImplicitCopyAssignment(Loc, MethodDecl); 13938 else if (MethodDecl->isMoveAssignmentOperator()) 13939 DefineImplicitMoveAssignment(Loc, MethodDecl); 13940 } 13941 } else if (isa<CXXConversionDecl>(MethodDecl) && 13942 MethodDecl->getParent()->isLambda()) { 13943 CXXConversionDecl *Conversion = 13944 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13945 if (Conversion->isLambdaToBlockPointerConversion()) 13946 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13947 else 13948 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13949 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13950 MarkVTableUsed(Loc, MethodDecl->getParent()); 13951 } 13952 13953 // Recursive functions should be marked when used from another function. 13954 // FIXME: Is this really right? 13955 if (CurContext == Func) return; 13956 13957 // Implicit instantiation of function templates and member functions of 13958 // class templates. 13959 if (Func->isImplicitlyInstantiable()) { 13960 bool AlreadyInstantiated = false; 13961 SourceLocation PointOfInstantiation = Loc; 13962 if (FunctionTemplateSpecializationInfo *SpecInfo 13963 = Func->getTemplateSpecializationInfo()) { 13964 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13965 SpecInfo->setPointOfInstantiation(Loc); 13966 else if (SpecInfo->getTemplateSpecializationKind() 13967 == TSK_ImplicitInstantiation) { 13968 AlreadyInstantiated = true; 13969 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13970 } 13971 } else if (MemberSpecializationInfo *MSInfo 13972 = Func->getMemberSpecializationInfo()) { 13973 if (MSInfo->getPointOfInstantiation().isInvalid()) 13974 MSInfo->setPointOfInstantiation(Loc); 13975 else if (MSInfo->getTemplateSpecializationKind() 13976 == TSK_ImplicitInstantiation) { 13977 AlreadyInstantiated = true; 13978 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13979 } 13980 } 13981 13982 if (!AlreadyInstantiated || Func->isConstexpr()) { 13983 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13984 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13985 CodeSynthesisContexts.size()) 13986 PendingLocalImplicitInstantiations.push_back( 13987 std::make_pair(Func, PointOfInstantiation)); 13988 else if (Func->isConstexpr()) 13989 // Do not defer instantiations of constexpr functions, to avoid the 13990 // expression evaluator needing to call back into Sema if it sees a 13991 // call to such a function. 13992 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13993 else { 13994 Func->setInstantiationIsPending(true); 13995 PendingInstantiations.push_back(std::make_pair(Func, 13996 PointOfInstantiation)); 13997 // Notify the consumer that a function was implicitly instantiated. 13998 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13999 } 14000 } 14001 } else { 14002 // Walk redefinitions, as some of them may be instantiable. 14003 for (auto i : Func->redecls()) { 14004 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14005 MarkFunctionReferenced(Loc, i, OdrUse); 14006 } 14007 } 14008 14009 if (!OdrUse) return; 14010 14011 // Keep track of used but undefined functions. 14012 if (!Func->isDefined()) { 14013 if (mightHaveNonExternalLinkage(Func)) 14014 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14015 else if (Func->getMostRecentDecl()->isInlined() && 14016 !LangOpts.GNUInline && 14017 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14018 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14019 else if (isExternalWithNoLinkageType(Func)) 14020 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14021 } 14022 14023 Func->markUsed(Context); 14024 } 14025 14026 static void 14027 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14028 ValueDecl *var, DeclContext *DC) { 14029 DeclContext *VarDC = var->getDeclContext(); 14030 14031 // If the parameter still belongs to the translation unit, then 14032 // we're actually just using one parameter in the declaration of 14033 // the next. 14034 if (isa<ParmVarDecl>(var) && 14035 isa<TranslationUnitDecl>(VarDC)) 14036 return; 14037 14038 // For C code, don't diagnose about capture if we're not actually in code 14039 // right now; it's impossible to write a non-constant expression outside of 14040 // function context, so we'll get other (more useful) diagnostics later. 14041 // 14042 // For C++, things get a bit more nasty... it would be nice to suppress this 14043 // diagnostic for certain cases like using a local variable in an array bound 14044 // for a member of a local class, but the correct predicate is not obvious. 14045 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14046 return; 14047 14048 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14049 unsigned ContextKind = 3; // unknown 14050 if (isa<CXXMethodDecl>(VarDC) && 14051 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14052 ContextKind = 2; 14053 } else if (isa<FunctionDecl>(VarDC)) { 14054 ContextKind = 0; 14055 } else if (isa<BlockDecl>(VarDC)) { 14056 ContextKind = 1; 14057 } 14058 14059 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14060 << var << ValueKind << ContextKind << VarDC; 14061 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14062 << var; 14063 14064 // FIXME: Add additional diagnostic info about class etc. which prevents 14065 // capture. 14066 } 14067 14068 14069 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14070 bool &SubCapturesAreNested, 14071 QualType &CaptureType, 14072 QualType &DeclRefType) { 14073 // Check whether we've already captured it. 14074 if (CSI->CaptureMap.count(Var)) { 14075 // If we found a capture, any subcaptures are nested. 14076 SubCapturesAreNested = true; 14077 14078 // Retrieve the capture type for this variable. 14079 CaptureType = CSI->getCapture(Var).getCaptureType(); 14080 14081 // Compute the type of an expression that refers to this variable. 14082 DeclRefType = CaptureType.getNonReferenceType(); 14083 14084 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14085 // are mutable in the sense that user can change their value - they are 14086 // private instances of the captured declarations. 14087 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 14088 if (Cap.isCopyCapture() && 14089 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14090 !(isa<CapturedRegionScopeInfo>(CSI) && 14091 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14092 DeclRefType.addConst(); 14093 return true; 14094 } 14095 return false; 14096 } 14097 14098 // Only block literals, captured statements, and lambda expressions can 14099 // capture; other scopes don't work. 14100 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14101 SourceLocation Loc, 14102 const bool Diagnose, Sema &S) { 14103 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14104 return getLambdaAwareParentOfDeclContext(DC); 14105 else if (Var->hasLocalStorage()) { 14106 if (Diagnose) 14107 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14108 } 14109 return nullptr; 14110 } 14111 14112 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14113 // certain types of variables (unnamed, variably modified types etc.) 14114 // so check for eligibility. 14115 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14116 SourceLocation Loc, 14117 const bool Diagnose, Sema &S) { 14118 14119 bool IsBlock = isa<BlockScopeInfo>(CSI); 14120 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14121 14122 // Lambdas are not allowed to capture unnamed variables 14123 // (e.g. anonymous unions). 14124 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14125 // assuming that's the intent. 14126 if (IsLambda && !Var->getDeclName()) { 14127 if (Diagnose) { 14128 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14129 S.Diag(Var->getLocation(), diag::note_declared_at); 14130 } 14131 return false; 14132 } 14133 14134 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14135 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14136 if (Diagnose) { 14137 S.Diag(Loc, diag::err_ref_vm_type); 14138 S.Diag(Var->getLocation(), diag::note_previous_decl) 14139 << Var->getDeclName(); 14140 } 14141 return false; 14142 } 14143 // Prohibit structs with flexible array members too. 14144 // We cannot capture what is in the tail end of the struct. 14145 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14146 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14147 if (Diagnose) { 14148 if (IsBlock) 14149 S.Diag(Loc, diag::err_ref_flexarray_type); 14150 else 14151 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14152 << Var->getDeclName(); 14153 S.Diag(Var->getLocation(), diag::note_previous_decl) 14154 << Var->getDeclName(); 14155 } 14156 return false; 14157 } 14158 } 14159 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14160 // Lambdas and captured statements are not allowed to capture __block 14161 // variables; they don't support the expected semantics. 14162 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14163 if (Diagnose) { 14164 S.Diag(Loc, diag::err_capture_block_variable) 14165 << Var->getDeclName() << !IsLambda; 14166 S.Diag(Var->getLocation(), diag::note_previous_decl) 14167 << Var->getDeclName(); 14168 } 14169 return false; 14170 } 14171 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14172 if (S.getLangOpts().OpenCL && IsBlock && 14173 Var->getType()->isBlockPointerType()) { 14174 if (Diagnose) 14175 S.Diag(Loc, diag::err_opencl_block_ref_block); 14176 return false; 14177 } 14178 14179 return true; 14180 } 14181 14182 // Returns true if the capture by block was successful. 14183 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14184 SourceLocation Loc, 14185 const bool BuildAndDiagnose, 14186 QualType &CaptureType, 14187 QualType &DeclRefType, 14188 const bool Nested, 14189 Sema &S) { 14190 Expr *CopyExpr = nullptr; 14191 bool ByRef = false; 14192 14193 // Blocks are not allowed to capture arrays. 14194 if (CaptureType->isArrayType()) { 14195 if (BuildAndDiagnose) { 14196 S.Diag(Loc, diag::err_ref_array_type); 14197 S.Diag(Var->getLocation(), diag::note_previous_decl) 14198 << Var->getDeclName(); 14199 } 14200 return false; 14201 } 14202 14203 // Forbid the block-capture of autoreleasing variables. 14204 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14205 if (BuildAndDiagnose) { 14206 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14207 << /*block*/ 0; 14208 S.Diag(Var->getLocation(), diag::note_previous_decl) 14209 << Var->getDeclName(); 14210 } 14211 return false; 14212 } 14213 14214 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14215 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14216 // This function finds out whether there is an AttributedType of kind 14217 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14218 // attr_objc_ownership implies __autoreleasing was explicitly specified 14219 // rather than being added implicitly by the compiler. 14220 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14221 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14222 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14223 return true; 14224 14225 // Peel off AttributedTypes that are not of kind objc_ownership. 14226 Ty = AttrTy->getModifiedType(); 14227 } 14228 14229 return false; 14230 }; 14231 14232 QualType PointeeTy = PT->getPointeeType(); 14233 14234 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14235 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14236 !IsObjCOwnershipAttributedType(PointeeTy)) { 14237 if (BuildAndDiagnose) { 14238 SourceLocation VarLoc = Var->getLocation(); 14239 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14240 { 14241 auto AddAutoreleaseNote = 14242 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14243 // Provide a fix-it for the '__autoreleasing' keyword at the 14244 // appropriate location in the variable's type. 14245 if (const auto *TSI = Var->getTypeSourceInfo()) { 14246 PointerTypeLoc PTL = 14247 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14248 if (PTL) { 14249 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14250 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14251 S.getLangOpts()); 14252 if (Loc.isValid()) { 14253 StringRef CharAtLoc = Lexer::getSourceText( 14254 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14255 S.getSourceManager(), S.getLangOpts()); 14256 AddAutoreleaseNote << FixItHint::CreateInsertion( 14257 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14258 ? " __autoreleasing " 14259 : " __autoreleasing"); 14260 } 14261 } 14262 } 14263 } 14264 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14265 } 14266 } 14267 } 14268 14269 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14270 if (HasBlocksAttr || CaptureType->isReferenceType() || 14271 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14272 // Block capture by reference does not change the capture or 14273 // declaration reference types. 14274 ByRef = true; 14275 } else { 14276 // Block capture by copy introduces 'const'. 14277 CaptureType = CaptureType.getNonReferenceType().withConst(); 14278 DeclRefType = CaptureType; 14279 14280 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14281 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14282 // The capture logic needs the destructor, so make sure we mark it. 14283 // Usually this is unnecessary because most local variables have 14284 // their destructors marked at declaration time, but parameters are 14285 // an exception because it's technically only the call site that 14286 // actually requires the destructor. 14287 if (isa<ParmVarDecl>(Var)) 14288 S.FinalizeVarWithDestructor(Var, Record); 14289 14290 // Enter a new evaluation context to insulate the copy 14291 // full-expression. 14292 EnterExpressionEvaluationContext scope( 14293 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14294 14295 // According to the blocks spec, the capture of a variable from 14296 // the stack requires a const copy constructor. This is not true 14297 // of the copy/move done to move a __block variable to the heap. 14298 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14299 DeclRefType.withConst(), 14300 VK_LValue, Loc); 14301 14302 ExprResult Result 14303 = S.PerformCopyInitialization( 14304 InitializedEntity::InitializeBlock(Var->getLocation(), 14305 CaptureType, false), 14306 Loc, DeclRef); 14307 14308 // Build a full-expression copy expression if initialization 14309 // succeeded and used a non-trivial constructor. Recover from 14310 // errors by pretending that the copy isn't necessary. 14311 if (!Result.isInvalid() && 14312 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14313 ->isTrivial()) { 14314 Result = S.MaybeCreateExprWithCleanups(Result); 14315 CopyExpr = Result.get(); 14316 } 14317 } 14318 } 14319 } 14320 14321 // Actually capture the variable. 14322 if (BuildAndDiagnose) 14323 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14324 SourceLocation(), CaptureType, CopyExpr); 14325 14326 return true; 14327 14328 } 14329 14330 14331 /// \brief Capture the given variable in the captured region. 14332 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14333 VarDecl *Var, 14334 SourceLocation Loc, 14335 const bool BuildAndDiagnose, 14336 QualType &CaptureType, 14337 QualType &DeclRefType, 14338 const bool RefersToCapturedVariable, 14339 Sema &S) { 14340 // By default, capture variables by reference. 14341 bool ByRef = true; 14342 // Using an LValue reference type is consistent with Lambdas (see below). 14343 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14344 if (S.IsOpenMPCapturedDecl(Var)) 14345 DeclRefType = DeclRefType.getUnqualifiedType(); 14346 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14347 } 14348 14349 if (ByRef) 14350 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14351 else 14352 CaptureType = DeclRefType; 14353 14354 Expr *CopyExpr = nullptr; 14355 if (BuildAndDiagnose) { 14356 // The current implementation assumes that all variables are captured 14357 // by references. Since there is no capture by copy, no expression 14358 // evaluation will be needed. 14359 RecordDecl *RD = RSI->TheRecordDecl; 14360 14361 FieldDecl *Field 14362 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14363 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14364 nullptr, false, ICIS_NoInit); 14365 Field->setImplicit(true); 14366 Field->setAccess(AS_private); 14367 RD->addDecl(Field); 14368 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14369 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14370 14371 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14372 DeclRefType, VK_LValue, Loc); 14373 Var->setReferenced(true); 14374 Var->markUsed(S.Context); 14375 } 14376 14377 // Actually capture the variable. 14378 if (BuildAndDiagnose) 14379 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14380 SourceLocation(), CaptureType, CopyExpr); 14381 14382 14383 return true; 14384 } 14385 14386 /// \brief Create a field within the lambda class for the variable 14387 /// being captured. 14388 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14389 QualType FieldType, QualType DeclRefType, 14390 SourceLocation Loc, 14391 bool RefersToCapturedVariable) { 14392 CXXRecordDecl *Lambda = LSI->Lambda; 14393 14394 // Build the non-static data member. 14395 FieldDecl *Field 14396 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14397 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14398 nullptr, false, ICIS_NoInit); 14399 Field->setImplicit(true); 14400 Field->setAccess(AS_private); 14401 Lambda->addDecl(Field); 14402 } 14403 14404 /// \brief Capture the given variable in the lambda. 14405 static bool captureInLambda(LambdaScopeInfo *LSI, 14406 VarDecl *Var, 14407 SourceLocation Loc, 14408 const bool BuildAndDiagnose, 14409 QualType &CaptureType, 14410 QualType &DeclRefType, 14411 const bool RefersToCapturedVariable, 14412 const Sema::TryCaptureKind Kind, 14413 SourceLocation EllipsisLoc, 14414 const bool IsTopScope, 14415 Sema &S) { 14416 14417 // Determine whether we are capturing by reference or by value. 14418 bool ByRef = false; 14419 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14420 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14421 } else { 14422 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14423 } 14424 14425 // Compute the type of the field that will capture this variable. 14426 if (ByRef) { 14427 // C++11 [expr.prim.lambda]p15: 14428 // An entity is captured by reference if it is implicitly or 14429 // explicitly captured but not captured by copy. It is 14430 // unspecified whether additional unnamed non-static data 14431 // members are declared in the closure type for entities 14432 // captured by reference. 14433 // 14434 // FIXME: It is not clear whether we want to build an lvalue reference 14435 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14436 // to do the former, while EDG does the latter. Core issue 1249 will 14437 // clarify, but for now we follow GCC because it's a more permissive and 14438 // easily defensible position. 14439 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14440 } else { 14441 // C++11 [expr.prim.lambda]p14: 14442 // For each entity captured by copy, an unnamed non-static 14443 // data member is declared in the closure type. The 14444 // declaration order of these members is unspecified. The type 14445 // of such a data member is the type of the corresponding 14446 // captured entity if the entity is not a reference to an 14447 // object, or the referenced type otherwise. [Note: If the 14448 // captured entity is a reference to a function, the 14449 // corresponding data member is also a reference to a 14450 // function. - end note ] 14451 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14452 if (!RefType->getPointeeType()->isFunctionType()) 14453 CaptureType = RefType->getPointeeType(); 14454 } 14455 14456 // Forbid the lambda copy-capture of autoreleasing variables. 14457 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14458 if (BuildAndDiagnose) { 14459 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14460 S.Diag(Var->getLocation(), diag::note_previous_decl) 14461 << Var->getDeclName(); 14462 } 14463 return false; 14464 } 14465 14466 // Make sure that by-copy captures are of a complete and non-abstract type. 14467 if (BuildAndDiagnose) { 14468 if (!CaptureType->isDependentType() && 14469 S.RequireCompleteType(Loc, CaptureType, 14470 diag::err_capture_of_incomplete_type, 14471 Var->getDeclName())) 14472 return false; 14473 14474 if (S.RequireNonAbstractType(Loc, CaptureType, 14475 diag::err_capture_of_abstract_type)) 14476 return false; 14477 } 14478 } 14479 14480 // Capture this variable in the lambda. 14481 if (BuildAndDiagnose) 14482 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14483 RefersToCapturedVariable); 14484 14485 // Compute the type of a reference to this captured variable. 14486 if (ByRef) 14487 DeclRefType = CaptureType.getNonReferenceType(); 14488 else { 14489 // C++ [expr.prim.lambda]p5: 14490 // The closure type for a lambda-expression has a public inline 14491 // function call operator [...]. This function call operator is 14492 // declared const (9.3.1) if and only if the lambda-expression's 14493 // parameter-declaration-clause is not followed by mutable. 14494 DeclRefType = CaptureType.getNonReferenceType(); 14495 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14496 DeclRefType.addConst(); 14497 } 14498 14499 // Add the capture. 14500 if (BuildAndDiagnose) 14501 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14502 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14503 14504 return true; 14505 } 14506 14507 bool Sema::tryCaptureVariable( 14508 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14509 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14510 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14511 // An init-capture is notionally from the context surrounding its 14512 // declaration, but its parent DC is the lambda class. 14513 DeclContext *VarDC = Var->getDeclContext(); 14514 if (Var->isInitCapture()) 14515 VarDC = VarDC->getParent(); 14516 14517 DeclContext *DC = CurContext; 14518 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14519 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14520 // We need to sync up the Declaration Context with the 14521 // FunctionScopeIndexToStopAt 14522 if (FunctionScopeIndexToStopAt) { 14523 unsigned FSIndex = FunctionScopes.size() - 1; 14524 while (FSIndex != MaxFunctionScopesIndex) { 14525 DC = getLambdaAwareParentOfDeclContext(DC); 14526 --FSIndex; 14527 } 14528 } 14529 14530 14531 // If the variable is declared in the current context, there is no need to 14532 // capture it. 14533 if (VarDC == DC) return true; 14534 14535 // Capture global variables if it is required to use private copy of this 14536 // variable. 14537 bool IsGlobal = !Var->hasLocalStorage(); 14538 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14539 return true; 14540 Var = Var->getCanonicalDecl(); 14541 14542 // Walk up the stack to determine whether we can capture the variable, 14543 // performing the "simple" checks that don't depend on type. We stop when 14544 // we've either hit the declared scope of the variable or find an existing 14545 // capture of that variable. We start from the innermost capturing-entity 14546 // (the DC) and ensure that all intervening capturing-entities 14547 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14548 // declcontext can either capture the variable or have already captured 14549 // the variable. 14550 CaptureType = Var->getType(); 14551 DeclRefType = CaptureType.getNonReferenceType(); 14552 bool Nested = false; 14553 bool Explicit = (Kind != TryCapture_Implicit); 14554 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14555 do { 14556 // Only block literals, captured statements, and lambda expressions can 14557 // capture; other scopes don't work. 14558 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14559 ExprLoc, 14560 BuildAndDiagnose, 14561 *this); 14562 // We need to check for the parent *first* because, if we *have* 14563 // private-captured a global variable, we need to recursively capture it in 14564 // intermediate blocks, lambdas, etc. 14565 if (!ParentDC) { 14566 if (IsGlobal) { 14567 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14568 break; 14569 } 14570 return true; 14571 } 14572 14573 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14574 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14575 14576 14577 // Check whether we've already captured it. 14578 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14579 DeclRefType)) { 14580 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14581 break; 14582 } 14583 // If we are instantiating a generic lambda call operator body, 14584 // we do not want to capture new variables. What was captured 14585 // during either a lambdas transformation or initial parsing 14586 // should be used. 14587 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14588 if (BuildAndDiagnose) { 14589 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14590 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14591 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14592 Diag(Var->getLocation(), diag::note_previous_decl) 14593 << Var->getDeclName(); 14594 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14595 } else 14596 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14597 } 14598 return true; 14599 } 14600 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14601 // certain types of variables (unnamed, variably modified types etc.) 14602 // so check for eligibility. 14603 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14604 return true; 14605 14606 // Try to capture variable-length arrays types. 14607 if (Var->getType()->isVariablyModifiedType()) { 14608 // We're going to walk down into the type and look for VLA 14609 // expressions. 14610 QualType QTy = Var->getType(); 14611 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14612 QTy = PVD->getOriginalType(); 14613 captureVariablyModifiedType(Context, QTy, CSI); 14614 } 14615 14616 if (getLangOpts().OpenMP) { 14617 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14618 // OpenMP private variables should not be captured in outer scope, so 14619 // just break here. Similarly, global variables that are captured in a 14620 // target region should not be captured outside the scope of the region. 14621 if (RSI->CapRegionKind == CR_OpenMP) { 14622 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14623 // When we detect target captures we are looking from inside the 14624 // target region, therefore we need to propagate the capture from the 14625 // enclosing region. Therefore, the capture is not initially nested. 14626 if (IsTargetCap) 14627 FunctionScopesIndex--; 14628 14629 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14630 Nested = !IsTargetCap; 14631 DeclRefType = DeclRefType.getUnqualifiedType(); 14632 CaptureType = Context.getLValueReferenceType(DeclRefType); 14633 break; 14634 } 14635 } 14636 } 14637 } 14638 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14639 // No capture-default, and this is not an explicit capture 14640 // so cannot capture this variable. 14641 if (BuildAndDiagnose) { 14642 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14643 Diag(Var->getLocation(), diag::note_previous_decl) 14644 << Var->getDeclName(); 14645 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14646 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14647 diag::note_lambda_decl); 14648 // FIXME: If we error out because an outer lambda can not implicitly 14649 // capture a variable that an inner lambda explicitly captures, we 14650 // should have the inner lambda do the explicit capture - because 14651 // it makes for cleaner diagnostics later. This would purely be done 14652 // so that the diagnostic does not misleadingly claim that a variable 14653 // can not be captured by a lambda implicitly even though it is captured 14654 // explicitly. Suggestion: 14655 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14656 // at the function head 14657 // - cache the StartingDeclContext - this must be a lambda 14658 // - captureInLambda in the innermost lambda the variable. 14659 } 14660 return true; 14661 } 14662 14663 FunctionScopesIndex--; 14664 DC = ParentDC; 14665 Explicit = false; 14666 } while (!VarDC->Equals(DC)); 14667 14668 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14669 // computing the type of the capture at each step, checking type-specific 14670 // requirements, and adding captures if requested. 14671 // If the variable had already been captured previously, we start capturing 14672 // at the lambda nested within that one. 14673 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14674 ++I) { 14675 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14676 14677 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14678 if (!captureInBlock(BSI, Var, ExprLoc, 14679 BuildAndDiagnose, CaptureType, 14680 DeclRefType, Nested, *this)) 14681 return true; 14682 Nested = true; 14683 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14684 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14685 BuildAndDiagnose, CaptureType, 14686 DeclRefType, Nested, *this)) 14687 return true; 14688 Nested = true; 14689 } else { 14690 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14691 if (!captureInLambda(LSI, Var, ExprLoc, 14692 BuildAndDiagnose, CaptureType, 14693 DeclRefType, Nested, Kind, EllipsisLoc, 14694 /*IsTopScope*/I == N - 1, *this)) 14695 return true; 14696 Nested = true; 14697 } 14698 } 14699 return false; 14700 } 14701 14702 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14703 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14704 QualType CaptureType; 14705 QualType DeclRefType; 14706 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14707 /*BuildAndDiagnose=*/true, CaptureType, 14708 DeclRefType, nullptr); 14709 } 14710 14711 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14712 QualType CaptureType; 14713 QualType DeclRefType; 14714 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14715 /*BuildAndDiagnose=*/false, CaptureType, 14716 DeclRefType, nullptr); 14717 } 14718 14719 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14720 QualType CaptureType; 14721 QualType DeclRefType; 14722 14723 // Determine whether we can capture this variable. 14724 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14725 /*BuildAndDiagnose=*/false, CaptureType, 14726 DeclRefType, nullptr)) 14727 return QualType(); 14728 14729 return DeclRefType; 14730 } 14731 14732 14733 14734 // If either the type of the variable or the initializer is dependent, 14735 // return false. Otherwise, determine whether the variable is a constant 14736 // expression. Use this if you need to know if a variable that might or 14737 // might not be dependent is truly a constant expression. 14738 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14739 ASTContext &Context) { 14740 14741 if (Var->getType()->isDependentType()) 14742 return false; 14743 const VarDecl *DefVD = nullptr; 14744 Var->getAnyInitializer(DefVD); 14745 if (!DefVD) 14746 return false; 14747 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14748 Expr *Init = cast<Expr>(Eval->Value); 14749 if (Init->isValueDependent()) 14750 return false; 14751 return IsVariableAConstantExpression(Var, Context); 14752 } 14753 14754 14755 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14756 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14757 // an object that satisfies the requirements for appearing in a 14758 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14759 // is immediately applied." This function handles the lvalue-to-rvalue 14760 // conversion part. 14761 MaybeODRUseExprs.erase(E->IgnoreParens()); 14762 14763 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14764 // to a variable that is a constant expression, and if so, identify it as 14765 // a reference to a variable that does not involve an odr-use of that 14766 // variable. 14767 if (LambdaScopeInfo *LSI = getCurLambda()) { 14768 Expr *SansParensExpr = E->IgnoreParens(); 14769 VarDecl *Var = nullptr; 14770 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14771 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14772 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14773 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14774 14775 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14776 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14777 } 14778 } 14779 14780 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14781 Res = CorrectDelayedTyposInExpr(Res); 14782 14783 if (!Res.isUsable()) 14784 return Res; 14785 14786 // If a constant-expression is a reference to a variable where we delay 14787 // deciding whether it is an odr-use, just assume we will apply the 14788 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14789 // (a non-type template argument), we have special handling anyway. 14790 UpdateMarkingForLValueToRValue(Res.get()); 14791 return Res; 14792 } 14793 14794 void Sema::CleanupVarDeclMarking() { 14795 for (Expr *E : MaybeODRUseExprs) { 14796 VarDecl *Var; 14797 SourceLocation Loc; 14798 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14799 Var = cast<VarDecl>(DRE->getDecl()); 14800 Loc = DRE->getLocation(); 14801 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14802 Var = cast<VarDecl>(ME->getMemberDecl()); 14803 Loc = ME->getMemberLoc(); 14804 } else { 14805 llvm_unreachable("Unexpected expression"); 14806 } 14807 14808 MarkVarDeclODRUsed(Var, Loc, *this, 14809 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14810 } 14811 14812 MaybeODRUseExprs.clear(); 14813 } 14814 14815 14816 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14817 VarDecl *Var, Expr *E) { 14818 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14819 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14820 Var->setReferenced(); 14821 14822 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14823 14824 bool OdrUseContext = isOdrUseContext(SemaRef); 14825 bool NeedDefinition = 14826 OdrUseContext || (isEvaluatableContext(SemaRef) && 14827 Var->isUsableInConstantExpressions(SemaRef.Context)); 14828 14829 VarTemplateSpecializationDecl *VarSpec = 14830 dyn_cast<VarTemplateSpecializationDecl>(Var); 14831 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14832 "Can't instantiate a partial template specialization."); 14833 14834 // If this might be a member specialization of a static data member, check 14835 // the specialization is visible. We already did the checks for variable 14836 // template specializations when we created them. 14837 if (NeedDefinition && TSK != TSK_Undeclared && 14838 !isa<VarTemplateSpecializationDecl>(Var)) 14839 SemaRef.checkSpecializationVisibility(Loc, Var); 14840 14841 // Perform implicit instantiation of static data members, static data member 14842 // templates of class templates, and variable template specializations. Delay 14843 // instantiations of variable templates, except for those that could be used 14844 // in a constant expression. 14845 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14846 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14847 14848 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14849 if (Var->getPointOfInstantiation().isInvalid()) { 14850 // This is a modification of an existing AST node. Notify listeners. 14851 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14852 L->StaticDataMemberInstantiated(Var); 14853 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14854 // Don't bother trying to instantiate it again, unless we might need 14855 // its initializer before we get to the end of the TU. 14856 TryInstantiating = false; 14857 } 14858 14859 if (Var->getPointOfInstantiation().isInvalid()) 14860 Var->setTemplateSpecializationKind(TSK, Loc); 14861 14862 if (TryInstantiating) { 14863 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14864 bool InstantiationDependent = false; 14865 bool IsNonDependent = 14866 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14867 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14868 : true; 14869 14870 // Do not instantiate specializations that are still type-dependent. 14871 if (IsNonDependent) { 14872 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14873 // Do not defer instantiations of variables which could be used in a 14874 // constant expression. 14875 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14876 } else { 14877 SemaRef.PendingInstantiations 14878 .push_back(std::make_pair(Var, PointOfInstantiation)); 14879 } 14880 } 14881 } 14882 } 14883 14884 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14885 // the requirements for appearing in a constant expression (5.19) and, if 14886 // it is an object, the lvalue-to-rvalue conversion (4.1) 14887 // is immediately applied." We check the first part here, and 14888 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14889 // Note that we use the C++11 definition everywhere because nothing in 14890 // C++03 depends on whether we get the C++03 version correct. The second 14891 // part does not apply to references, since they are not objects. 14892 if (OdrUseContext && E && 14893 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14894 // A reference initialized by a constant expression can never be 14895 // odr-used, so simply ignore it. 14896 if (!Var->getType()->isReferenceType() || 14897 (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) 14898 SemaRef.MaybeODRUseExprs.insert(E); 14899 } else if (OdrUseContext) { 14900 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14901 /*MaxFunctionScopeIndex ptr*/ nullptr); 14902 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14903 // If this is a dependent context, we don't need to mark variables as 14904 // odr-used, but we may still need to track them for lambda capture. 14905 // FIXME: Do we also need to do this inside dependent typeid expressions 14906 // (which are modeled as unevaluated at this point)? 14907 const bool RefersToEnclosingScope = 14908 (SemaRef.CurContext != Var->getDeclContext() && 14909 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14910 if (RefersToEnclosingScope) { 14911 LambdaScopeInfo *const LSI = 14912 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14913 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14914 // If a variable could potentially be odr-used, defer marking it so 14915 // until we finish analyzing the full expression for any 14916 // lvalue-to-rvalue 14917 // or discarded value conversions that would obviate odr-use. 14918 // Add it to the list of potential captures that will be analyzed 14919 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14920 // unless the variable is a reference that was initialized by a constant 14921 // expression (this will never need to be captured or odr-used). 14922 assert(E && "Capture variable should be used in an expression."); 14923 if (!Var->getType()->isReferenceType() || 14924 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14925 LSI->addPotentialCapture(E->IgnoreParens()); 14926 } 14927 } 14928 } 14929 } 14930 14931 /// \brief Mark a variable referenced, and check whether it is odr-used 14932 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14933 /// used directly for normal expressions referring to VarDecl. 14934 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14935 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14936 } 14937 14938 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14939 Decl *D, Expr *E, bool MightBeOdrUse) { 14940 if (SemaRef.isInOpenMPDeclareTargetContext()) 14941 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14942 14943 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14944 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14945 return; 14946 } 14947 14948 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14949 14950 // If this is a call to a method via a cast, also mark the method in the 14951 // derived class used in case codegen can devirtualize the call. 14952 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14953 if (!ME) 14954 return; 14955 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14956 if (!MD) 14957 return; 14958 // Only attempt to devirtualize if this is truly a virtual call. 14959 bool IsVirtualCall = MD->isVirtual() && 14960 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14961 if (!IsVirtualCall) 14962 return; 14963 14964 // If it's possible to devirtualize the call, mark the called function 14965 // referenced. 14966 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 14967 ME->getBase(), SemaRef.getLangOpts().AppleKext); 14968 if (DM) 14969 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14970 } 14971 14972 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14973 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 14974 // TODO: update this with DR# once a defect report is filed. 14975 // C++11 defect. The address of a pure member should not be an ODR use, even 14976 // if it's a qualified reference. 14977 bool OdrUse = true; 14978 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14979 if (Method->isVirtual() && 14980 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 14981 OdrUse = false; 14982 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14983 } 14984 14985 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14986 void Sema::MarkMemberReferenced(MemberExpr *E) { 14987 // C++11 [basic.def.odr]p2: 14988 // A non-overloaded function whose name appears as a potentially-evaluated 14989 // expression or a member of a set of candidate functions, if selected by 14990 // overload resolution when referred to from a potentially-evaluated 14991 // expression, is odr-used, unless it is a pure virtual function and its 14992 // name is not explicitly qualified. 14993 bool MightBeOdrUse = true; 14994 if (E->performsVirtualDispatch(getLangOpts())) { 14995 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14996 if (Method->isPure()) 14997 MightBeOdrUse = false; 14998 } 14999 SourceLocation Loc = E->getMemberLoc().isValid() ? 15000 E->getMemberLoc() : E->getLocStart(); 15001 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15002 } 15003 15004 /// \brief Perform marking for a reference to an arbitrary declaration. It 15005 /// marks the declaration referenced, and performs odr-use checking for 15006 /// functions and variables. This method should not be used when building a 15007 /// normal expression which refers to a variable. 15008 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15009 bool MightBeOdrUse) { 15010 if (MightBeOdrUse) { 15011 if (auto *VD = dyn_cast<VarDecl>(D)) { 15012 MarkVariableReferenced(Loc, VD); 15013 return; 15014 } 15015 } 15016 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15017 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15018 return; 15019 } 15020 D->setReferenced(); 15021 } 15022 15023 namespace { 15024 // Mark all of the declarations used by a type as referenced. 15025 // FIXME: Not fully implemented yet! We need to have a better understanding 15026 // of when we're entering a context we should not recurse into. 15027 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15028 // TreeTransforms rebuilding the type in a new context. Rather than 15029 // duplicating the TreeTransform logic, we should consider reusing it here. 15030 // Currently that causes problems when rebuilding LambdaExprs. 15031 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15032 Sema &S; 15033 SourceLocation Loc; 15034 15035 public: 15036 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15037 15038 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15039 15040 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15041 }; 15042 } 15043 15044 bool MarkReferencedDecls::TraverseTemplateArgument( 15045 const TemplateArgument &Arg) { 15046 { 15047 // A non-type template argument is a constant-evaluated context. 15048 EnterExpressionEvaluationContext Evaluated( 15049 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15050 if (Arg.getKind() == TemplateArgument::Declaration) { 15051 if (Decl *D = Arg.getAsDecl()) 15052 S.MarkAnyDeclReferenced(Loc, D, true); 15053 } else if (Arg.getKind() == TemplateArgument::Expression) { 15054 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15055 } 15056 } 15057 15058 return Inherited::TraverseTemplateArgument(Arg); 15059 } 15060 15061 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15062 MarkReferencedDecls Marker(*this, Loc); 15063 Marker.TraverseType(T); 15064 } 15065 15066 namespace { 15067 /// \brief Helper class that marks all of the declarations referenced by 15068 /// potentially-evaluated subexpressions as "referenced". 15069 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15070 Sema &S; 15071 bool SkipLocalVariables; 15072 15073 public: 15074 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15075 15076 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15077 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15078 15079 void VisitDeclRefExpr(DeclRefExpr *E) { 15080 // If we were asked not to visit local variables, don't. 15081 if (SkipLocalVariables) { 15082 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15083 if (VD->hasLocalStorage()) 15084 return; 15085 } 15086 15087 S.MarkDeclRefReferenced(E); 15088 } 15089 15090 void VisitMemberExpr(MemberExpr *E) { 15091 S.MarkMemberReferenced(E); 15092 Inherited::VisitMemberExpr(E); 15093 } 15094 15095 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15096 S.MarkFunctionReferenced(E->getLocStart(), 15097 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15098 Visit(E->getSubExpr()); 15099 } 15100 15101 void VisitCXXNewExpr(CXXNewExpr *E) { 15102 if (E->getOperatorNew()) 15103 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15104 if (E->getOperatorDelete()) 15105 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15106 Inherited::VisitCXXNewExpr(E); 15107 } 15108 15109 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15110 if (E->getOperatorDelete()) 15111 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15112 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15113 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15114 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15115 S.MarkFunctionReferenced(E->getLocStart(), 15116 S.LookupDestructor(Record)); 15117 } 15118 15119 Inherited::VisitCXXDeleteExpr(E); 15120 } 15121 15122 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15123 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15124 Inherited::VisitCXXConstructExpr(E); 15125 } 15126 15127 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15128 Visit(E->getExpr()); 15129 } 15130 15131 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15132 Inherited::VisitImplicitCastExpr(E); 15133 15134 if (E->getCastKind() == CK_LValueToRValue) 15135 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15136 } 15137 }; 15138 } 15139 15140 /// \brief Mark any declarations that appear within this expression or any 15141 /// potentially-evaluated subexpressions as "referenced". 15142 /// 15143 /// \param SkipLocalVariables If true, don't mark local variables as 15144 /// 'referenced'. 15145 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15146 bool SkipLocalVariables) { 15147 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15148 } 15149 15150 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15151 /// of the program being compiled. 15152 /// 15153 /// This routine emits the given diagnostic when the code currently being 15154 /// type-checked is "potentially evaluated", meaning that there is a 15155 /// possibility that the code will actually be executable. Code in sizeof() 15156 /// expressions, code used only during overload resolution, etc., are not 15157 /// potentially evaluated. This routine will suppress such diagnostics or, 15158 /// in the absolutely nutty case of potentially potentially evaluated 15159 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15160 /// later. 15161 /// 15162 /// This routine should be used for all diagnostics that describe the run-time 15163 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15164 /// Failure to do so will likely result in spurious diagnostics or failures 15165 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15166 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15167 const PartialDiagnostic &PD) { 15168 switch (ExprEvalContexts.back().Context) { 15169 case ExpressionEvaluationContext::Unevaluated: 15170 case ExpressionEvaluationContext::UnevaluatedList: 15171 case ExpressionEvaluationContext::UnevaluatedAbstract: 15172 case ExpressionEvaluationContext::DiscardedStatement: 15173 // The argument will never be evaluated, so don't complain. 15174 break; 15175 15176 case ExpressionEvaluationContext::ConstantEvaluated: 15177 // Relevant diagnostics should be produced by constant evaluation. 15178 break; 15179 15180 case ExpressionEvaluationContext::PotentiallyEvaluated: 15181 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15182 if (Statement && getCurFunctionOrMethodDecl()) { 15183 FunctionScopes.back()->PossiblyUnreachableDiags. 15184 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15185 return true; 15186 } 15187 15188 // The initializer of a constexpr variable or of the first declaration of a 15189 // static data member is not syntactically a constant evaluated constant, 15190 // but nonetheless is always required to be a constant expression, so we 15191 // can skip diagnosing. 15192 // FIXME: Using the mangling context here is a hack. 15193 if (auto *VD = dyn_cast_or_null<VarDecl>( 15194 ExprEvalContexts.back().ManglingContextDecl)) { 15195 if (VD->isConstexpr() || 15196 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15197 break; 15198 // FIXME: For any other kind of variable, we should build a CFG for its 15199 // initializer and check whether the context in question is reachable. 15200 } 15201 15202 Diag(Loc, PD); 15203 return true; 15204 } 15205 15206 return false; 15207 } 15208 15209 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15210 CallExpr *CE, FunctionDecl *FD) { 15211 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15212 return false; 15213 15214 // If we're inside a decltype's expression, don't check for a valid return 15215 // type or construct temporaries until we know whether this is the last call. 15216 if (ExprEvalContexts.back().IsDecltype) { 15217 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15218 return false; 15219 } 15220 15221 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15222 FunctionDecl *FD; 15223 CallExpr *CE; 15224 15225 public: 15226 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15227 : FD(FD), CE(CE) { } 15228 15229 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15230 if (!FD) { 15231 S.Diag(Loc, diag::err_call_incomplete_return) 15232 << T << CE->getSourceRange(); 15233 return; 15234 } 15235 15236 S.Diag(Loc, diag::err_call_function_incomplete_return) 15237 << CE->getSourceRange() << FD->getDeclName() << T; 15238 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15239 << FD->getDeclName(); 15240 } 15241 } Diagnoser(FD, CE); 15242 15243 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15244 return true; 15245 15246 return false; 15247 } 15248 15249 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15250 // will prevent this condition from triggering, which is what we want. 15251 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15252 SourceLocation Loc; 15253 15254 unsigned diagnostic = diag::warn_condition_is_assignment; 15255 bool IsOrAssign = false; 15256 15257 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15258 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15259 return; 15260 15261 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15262 15263 // Greylist some idioms by putting them into a warning subcategory. 15264 if (ObjCMessageExpr *ME 15265 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15266 Selector Sel = ME->getSelector(); 15267 15268 // self = [<foo> init...] 15269 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15270 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15271 15272 // <foo> = [<bar> nextObject] 15273 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15274 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15275 } 15276 15277 Loc = Op->getOperatorLoc(); 15278 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15279 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15280 return; 15281 15282 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15283 Loc = Op->getOperatorLoc(); 15284 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15285 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15286 else { 15287 // Not an assignment. 15288 return; 15289 } 15290 15291 Diag(Loc, diagnostic) << E->getSourceRange(); 15292 15293 SourceLocation Open = E->getLocStart(); 15294 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15295 Diag(Loc, diag::note_condition_assign_silence) 15296 << FixItHint::CreateInsertion(Open, "(") 15297 << FixItHint::CreateInsertion(Close, ")"); 15298 15299 if (IsOrAssign) 15300 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15301 << FixItHint::CreateReplacement(Loc, "!="); 15302 else 15303 Diag(Loc, diag::note_condition_assign_to_comparison) 15304 << FixItHint::CreateReplacement(Loc, "=="); 15305 } 15306 15307 /// \brief Redundant parentheses over an equality comparison can indicate 15308 /// that the user intended an assignment used as condition. 15309 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15310 // Don't warn if the parens came from a macro. 15311 SourceLocation parenLoc = ParenE->getLocStart(); 15312 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15313 return; 15314 // Don't warn for dependent expressions. 15315 if (ParenE->isTypeDependent()) 15316 return; 15317 15318 Expr *E = ParenE->IgnoreParens(); 15319 15320 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15321 if (opE->getOpcode() == BO_EQ && 15322 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15323 == Expr::MLV_Valid) { 15324 SourceLocation Loc = opE->getOperatorLoc(); 15325 15326 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15327 SourceRange ParenERange = ParenE->getSourceRange(); 15328 Diag(Loc, diag::note_equality_comparison_silence) 15329 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15330 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15331 Diag(Loc, diag::note_equality_comparison_to_assign) 15332 << FixItHint::CreateReplacement(Loc, "="); 15333 } 15334 } 15335 15336 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15337 bool IsConstexpr) { 15338 DiagnoseAssignmentAsCondition(E); 15339 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15340 DiagnoseEqualityWithExtraParens(parenE); 15341 15342 ExprResult result = CheckPlaceholderExpr(E); 15343 if (result.isInvalid()) return ExprError(); 15344 E = result.get(); 15345 15346 if (!E->isTypeDependent()) { 15347 if (getLangOpts().CPlusPlus) 15348 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15349 15350 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15351 if (ERes.isInvalid()) 15352 return ExprError(); 15353 E = ERes.get(); 15354 15355 QualType T = E->getType(); 15356 if (!T->isScalarType()) { // C99 6.8.4.1p1 15357 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15358 << T << E->getSourceRange(); 15359 return ExprError(); 15360 } 15361 CheckBoolLikeConversion(E, Loc); 15362 } 15363 15364 return E; 15365 } 15366 15367 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15368 Expr *SubExpr, ConditionKind CK) { 15369 // Empty conditions are valid in for-statements. 15370 if (!SubExpr) 15371 return ConditionResult(); 15372 15373 ExprResult Cond; 15374 switch (CK) { 15375 case ConditionKind::Boolean: 15376 Cond = CheckBooleanCondition(Loc, SubExpr); 15377 break; 15378 15379 case ConditionKind::ConstexprIf: 15380 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15381 break; 15382 15383 case ConditionKind::Switch: 15384 Cond = CheckSwitchCondition(Loc, SubExpr); 15385 break; 15386 } 15387 if (Cond.isInvalid()) 15388 return ConditionError(); 15389 15390 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15391 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15392 if (!FullExpr.get()) 15393 return ConditionError(); 15394 15395 return ConditionResult(*this, nullptr, FullExpr, 15396 CK == ConditionKind::ConstexprIf); 15397 } 15398 15399 namespace { 15400 /// A visitor for rebuilding a call to an __unknown_any expression 15401 /// to have an appropriate type. 15402 struct RebuildUnknownAnyFunction 15403 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15404 15405 Sema &S; 15406 15407 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15408 15409 ExprResult VisitStmt(Stmt *S) { 15410 llvm_unreachable("unexpected statement!"); 15411 } 15412 15413 ExprResult VisitExpr(Expr *E) { 15414 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15415 << E->getSourceRange(); 15416 return ExprError(); 15417 } 15418 15419 /// Rebuild an expression which simply semantically wraps another 15420 /// expression which it shares the type and value kind of. 15421 template <class T> ExprResult rebuildSugarExpr(T *E) { 15422 ExprResult SubResult = Visit(E->getSubExpr()); 15423 if (SubResult.isInvalid()) return ExprError(); 15424 15425 Expr *SubExpr = SubResult.get(); 15426 E->setSubExpr(SubExpr); 15427 E->setType(SubExpr->getType()); 15428 E->setValueKind(SubExpr->getValueKind()); 15429 assert(E->getObjectKind() == OK_Ordinary); 15430 return E; 15431 } 15432 15433 ExprResult VisitParenExpr(ParenExpr *E) { 15434 return rebuildSugarExpr(E); 15435 } 15436 15437 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15438 return rebuildSugarExpr(E); 15439 } 15440 15441 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15442 ExprResult SubResult = Visit(E->getSubExpr()); 15443 if (SubResult.isInvalid()) return ExprError(); 15444 15445 Expr *SubExpr = SubResult.get(); 15446 E->setSubExpr(SubExpr); 15447 E->setType(S.Context.getPointerType(SubExpr->getType())); 15448 assert(E->getValueKind() == VK_RValue); 15449 assert(E->getObjectKind() == OK_Ordinary); 15450 return E; 15451 } 15452 15453 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15454 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15455 15456 E->setType(VD->getType()); 15457 15458 assert(E->getValueKind() == VK_RValue); 15459 if (S.getLangOpts().CPlusPlus && 15460 !(isa<CXXMethodDecl>(VD) && 15461 cast<CXXMethodDecl>(VD)->isInstance())) 15462 E->setValueKind(VK_LValue); 15463 15464 return E; 15465 } 15466 15467 ExprResult VisitMemberExpr(MemberExpr *E) { 15468 return resolveDecl(E, E->getMemberDecl()); 15469 } 15470 15471 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15472 return resolveDecl(E, E->getDecl()); 15473 } 15474 }; 15475 } 15476 15477 /// Given a function expression of unknown-any type, try to rebuild it 15478 /// to have a function type. 15479 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15480 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15481 if (Result.isInvalid()) return ExprError(); 15482 return S.DefaultFunctionArrayConversion(Result.get()); 15483 } 15484 15485 namespace { 15486 /// A visitor for rebuilding an expression of type __unknown_anytype 15487 /// into one which resolves the type directly on the referring 15488 /// expression. Strict preservation of the original source 15489 /// structure is not a goal. 15490 struct RebuildUnknownAnyExpr 15491 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15492 15493 Sema &S; 15494 15495 /// The current destination type. 15496 QualType DestType; 15497 15498 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15499 : S(S), DestType(CastType) {} 15500 15501 ExprResult VisitStmt(Stmt *S) { 15502 llvm_unreachable("unexpected statement!"); 15503 } 15504 15505 ExprResult VisitExpr(Expr *E) { 15506 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15507 << E->getSourceRange(); 15508 return ExprError(); 15509 } 15510 15511 ExprResult VisitCallExpr(CallExpr *E); 15512 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15513 15514 /// Rebuild an expression which simply semantically wraps another 15515 /// expression which it shares the type and value kind of. 15516 template <class T> ExprResult rebuildSugarExpr(T *E) { 15517 ExprResult SubResult = Visit(E->getSubExpr()); 15518 if (SubResult.isInvalid()) return ExprError(); 15519 Expr *SubExpr = SubResult.get(); 15520 E->setSubExpr(SubExpr); 15521 E->setType(SubExpr->getType()); 15522 E->setValueKind(SubExpr->getValueKind()); 15523 assert(E->getObjectKind() == OK_Ordinary); 15524 return E; 15525 } 15526 15527 ExprResult VisitParenExpr(ParenExpr *E) { 15528 return rebuildSugarExpr(E); 15529 } 15530 15531 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15532 return rebuildSugarExpr(E); 15533 } 15534 15535 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15536 const PointerType *Ptr = DestType->getAs<PointerType>(); 15537 if (!Ptr) { 15538 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15539 << E->getSourceRange(); 15540 return ExprError(); 15541 } 15542 15543 if (isa<CallExpr>(E->getSubExpr())) { 15544 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15545 << E->getSourceRange(); 15546 return ExprError(); 15547 } 15548 15549 assert(E->getValueKind() == VK_RValue); 15550 assert(E->getObjectKind() == OK_Ordinary); 15551 E->setType(DestType); 15552 15553 // Build the sub-expression as if it were an object of the pointee type. 15554 DestType = Ptr->getPointeeType(); 15555 ExprResult SubResult = Visit(E->getSubExpr()); 15556 if (SubResult.isInvalid()) return ExprError(); 15557 E->setSubExpr(SubResult.get()); 15558 return E; 15559 } 15560 15561 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15562 15563 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15564 15565 ExprResult VisitMemberExpr(MemberExpr *E) { 15566 return resolveDecl(E, E->getMemberDecl()); 15567 } 15568 15569 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15570 return resolveDecl(E, E->getDecl()); 15571 } 15572 }; 15573 } 15574 15575 /// Rebuilds a call expression which yielded __unknown_anytype. 15576 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15577 Expr *CalleeExpr = E->getCallee(); 15578 15579 enum FnKind { 15580 FK_MemberFunction, 15581 FK_FunctionPointer, 15582 FK_BlockPointer 15583 }; 15584 15585 FnKind Kind; 15586 QualType CalleeType = CalleeExpr->getType(); 15587 if (CalleeType == S.Context.BoundMemberTy) { 15588 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15589 Kind = FK_MemberFunction; 15590 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15591 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15592 CalleeType = Ptr->getPointeeType(); 15593 Kind = FK_FunctionPointer; 15594 } else { 15595 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15596 Kind = FK_BlockPointer; 15597 } 15598 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15599 15600 // Verify that this is a legal result type of a function. 15601 if (DestType->isArrayType() || DestType->isFunctionType()) { 15602 unsigned diagID = diag::err_func_returning_array_function; 15603 if (Kind == FK_BlockPointer) 15604 diagID = diag::err_block_returning_array_function; 15605 15606 S.Diag(E->getExprLoc(), diagID) 15607 << DestType->isFunctionType() << DestType; 15608 return ExprError(); 15609 } 15610 15611 // Otherwise, go ahead and set DestType as the call's result. 15612 E->setType(DestType.getNonLValueExprType(S.Context)); 15613 E->setValueKind(Expr::getValueKindForType(DestType)); 15614 assert(E->getObjectKind() == OK_Ordinary); 15615 15616 // Rebuild the function type, replacing the result type with DestType. 15617 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15618 if (Proto) { 15619 // __unknown_anytype(...) is a special case used by the debugger when 15620 // it has no idea what a function's signature is. 15621 // 15622 // We want to build this call essentially under the K&R 15623 // unprototyped rules, but making a FunctionNoProtoType in C++ 15624 // would foul up all sorts of assumptions. However, we cannot 15625 // simply pass all arguments as variadic arguments, nor can we 15626 // portably just call the function under a non-variadic type; see 15627 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15628 // However, it turns out that in practice it is generally safe to 15629 // call a function declared as "A foo(B,C,D);" under the prototype 15630 // "A foo(B,C,D,...);". The only known exception is with the 15631 // Windows ABI, where any variadic function is implicitly cdecl 15632 // regardless of its normal CC. Therefore we change the parameter 15633 // types to match the types of the arguments. 15634 // 15635 // This is a hack, but it is far superior to moving the 15636 // corresponding target-specific code from IR-gen to Sema/AST. 15637 15638 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15639 SmallVector<QualType, 8> ArgTypes; 15640 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15641 ArgTypes.reserve(E->getNumArgs()); 15642 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15643 Expr *Arg = E->getArg(i); 15644 QualType ArgType = Arg->getType(); 15645 if (E->isLValue()) { 15646 ArgType = S.Context.getLValueReferenceType(ArgType); 15647 } else if (E->isXValue()) { 15648 ArgType = S.Context.getRValueReferenceType(ArgType); 15649 } 15650 ArgTypes.push_back(ArgType); 15651 } 15652 ParamTypes = ArgTypes; 15653 } 15654 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15655 Proto->getExtProtoInfo()); 15656 } else { 15657 DestType = S.Context.getFunctionNoProtoType(DestType, 15658 FnType->getExtInfo()); 15659 } 15660 15661 // Rebuild the appropriate pointer-to-function type. 15662 switch (Kind) { 15663 case FK_MemberFunction: 15664 // Nothing to do. 15665 break; 15666 15667 case FK_FunctionPointer: 15668 DestType = S.Context.getPointerType(DestType); 15669 break; 15670 15671 case FK_BlockPointer: 15672 DestType = S.Context.getBlockPointerType(DestType); 15673 break; 15674 } 15675 15676 // Finally, we can recurse. 15677 ExprResult CalleeResult = Visit(CalleeExpr); 15678 if (!CalleeResult.isUsable()) return ExprError(); 15679 E->setCallee(CalleeResult.get()); 15680 15681 // Bind a temporary if necessary. 15682 return S.MaybeBindToTemporary(E); 15683 } 15684 15685 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15686 // Verify that this is a legal result type of a call. 15687 if (DestType->isArrayType() || DestType->isFunctionType()) { 15688 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15689 << DestType->isFunctionType() << DestType; 15690 return ExprError(); 15691 } 15692 15693 // Rewrite the method result type if available. 15694 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15695 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15696 Method->setReturnType(DestType); 15697 } 15698 15699 // Change the type of the message. 15700 E->setType(DestType.getNonReferenceType()); 15701 E->setValueKind(Expr::getValueKindForType(DestType)); 15702 15703 return S.MaybeBindToTemporary(E); 15704 } 15705 15706 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15707 // The only case we should ever see here is a function-to-pointer decay. 15708 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15709 assert(E->getValueKind() == VK_RValue); 15710 assert(E->getObjectKind() == OK_Ordinary); 15711 15712 E->setType(DestType); 15713 15714 // Rebuild the sub-expression as the pointee (function) type. 15715 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15716 15717 ExprResult Result = Visit(E->getSubExpr()); 15718 if (!Result.isUsable()) return ExprError(); 15719 15720 E->setSubExpr(Result.get()); 15721 return E; 15722 } else if (E->getCastKind() == CK_LValueToRValue) { 15723 assert(E->getValueKind() == VK_RValue); 15724 assert(E->getObjectKind() == OK_Ordinary); 15725 15726 assert(isa<BlockPointerType>(E->getType())); 15727 15728 E->setType(DestType); 15729 15730 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15731 DestType = S.Context.getLValueReferenceType(DestType); 15732 15733 ExprResult Result = Visit(E->getSubExpr()); 15734 if (!Result.isUsable()) return ExprError(); 15735 15736 E->setSubExpr(Result.get()); 15737 return E; 15738 } else { 15739 llvm_unreachable("Unhandled cast type!"); 15740 } 15741 } 15742 15743 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15744 ExprValueKind ValueKind = VK_LValue; 15745 QualType Type = DestType; 15746 15747 // We know how to make this work for certain kinds of decls: 15748 15749 // - functions 15750 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15751 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15752 DestType = Ptr->getPointeeType(); 15753 ExprResult Result = resolveDecl(E, VD); 15754 if (Result.isInvalid()) return ExprError(); 15755 return S.ImpCastExprToType(Result.get(), Type, 15756 CK_FunctionToPointerDecay, VK_RValue); 15757 } 15758 15759 if (!Type->isFunctionType()) { 15760 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15761 << VD << E->getSourceRange(); 15762 return ExprError(); 15763 } 15764 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15765 // We must match the FunctionDecl's type to the hack introduced in 15766 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15767 // type. See the lengthy commentary in that routine. 15768 QualType FDT = FD->getType(); 15769 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15770 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15771 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15772 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15773 SourceLocation Loc = FD->getLocation(); 15774 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15775 FD->getDeclContext(), 15776 Loc, Loc, FD->getNameInfo().getName(), 15777 DestType, FD->getTypeSourceInfo(), 15778 SC_None, false/*isInlineSpecified*/, 15779 FD->hasPrototype(), 15780 false/*isConstexprSpecified*/); 15781 15782 if (FD->getQualifier()) 15783 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15784 15785 SmallVector<ParmVarDecl*, 16> Params; 15786 for (const auto &AI : FT->param_types()) { 15787 ParmVarDecl *Param = 15788 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15789 Param->setScopeInfo(0, Params.size()); 15790 Params.push_back(Param); 15791 } 15792 NewFD->setParams(Params); 15793 DRE->setDecl(NewFD); 15794 VD = DRE->getDecl(); 15795 } 15796 } 15797 15798 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15799 if (MD->isInstance()) { 15800 ValueKind = VK_RValue; 15801 Type = S.Context.BoundMemberTy; 15802 } 15803 15804 // Function references aren't l-values in C. 15805 if (!S.getLangOpts().CPlusPlus) 15806 ValueKind = VK_RValue; 15807 15808 // - variables 15809 } else if (isa<VarDecl>(VD)) { 15810 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15811 Type = RefTy->getPointeeType(); 15812 } else if (Type->isFunctionType()) { 15813 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15814 << VD << E->getSourceRange(); 15815 return ExprError(); 15816 } 15817 15818 // - nothing else 15819 } else { 15820 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15821 << VD << E->getSourceRange(); 15822 return ExprError(); 15823 } 15824 15825 // Modifying the declaration like this is friendly to IR-gen but 15826 // also really dangerous. 15827 VD->setType(DestType); 15828 E->setType(Type); 15829 E->setValueKind(ValueKind); 15830 return E; 15831 } 15832 15833 /// Check a cast of an unknown-any type. We intentionally only 15834 /// trigger this for C-style casts. 15835 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15836 Expr *CastExpr, CastKind &CastKind, 15837 ExprValueKind &VK, CXXCastPath &Path) { 15838 // The type we're casting to must be either void or complete. 15839 if (!CastType->isVoidType() && 15840 RequireCompleteType(TypeRange.getBegin(), CastType, 15841 diag::err_typecheck_cast_to_incomplete)) 15842 return ExprError(); 15843 15844 // Rewrite the casted expression from scratch. 15845 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15846 if (!result.isUsable()) return ExprError(); 15847 15848 CastExpr = result.get(); 15849 VK = CastExpr->getValueKind(); 15850 CastKind = CK_NoOp; 15851 15852 return CastExpr; 15853 } 15854 15855 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15856 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15857 } 15858 15859 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15860 Expr *arg, QualType ¶mType) { 15861 // If the syntactic form of the argument is not an explicit cast of 15862 // any sort, just do default argument promotion. 15863 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15864 if (!castArg) { 15865 ExprResult result = DefaultArgumentPromotion(arg); 15866 if (result.isInvalid()) return ExprError(); 15867 paramType = result.get()->getType(); 15868 return result; 15869 } 15870 15871 // Otherwise, use the type that was written in the explicit cast. 15872 assert(!arg->hasPlaceholderType()); 15873 paramType = castArg->getTypeAsWritten(); 15874 15875 // Copy-initialize a parameter of that type. 15876 InitializedEntity entity = 15877 InitializedEntity::InitializeParameter(Context, paramType, 15878 /*consumed*/ false); 15879 return PerformCopyInitialization(entity, callLoc, arg); 15880 } 15881 15882 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15883 Expr *orig = E; 15884 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15885 while (true) { 15886 E = E->IgnoreParenImpCasts(); 15887 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15888 E = call->getCallee(); 15889 diagID = diag::err_uncasted_call_of_unknown_any; 15890 } else { 15891 break; 15892 } 15893 } 15894 15895 SourceLocation loc; 15896 NamedDecl *d; 15897 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15898 loc = ref->getLocation(); 15899 d = ref->getDecl(); 15900 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15901 loc = mem->getMemberLoc(); 15902 d = mem->getMemberDecl(); 15903 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15904 diagID = diag::err_uncasted_call_of_unknown_any; 15905 loc = msg->getSelectorStartLoc(); 15906 d = msg->getMethodDecl(); 15907 if (!d) { 15908 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15909 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15910 << orig->getSourceRange(); 15911 return ExprError(); 15912 } 15913 } else { 15914 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15915 << E->getSourceRange(); 15916 return ExprError(); 15917 } 15918 15919 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15920 15921 // Never recoverable. 15922 return ExprError(); 15923 } 15924 15925 /// Check for operands with placeholder types and complain if found. 15926 /// Returns ExprError() if there was an error and no recovery was possible. 15927 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15928 if (!getLangOpts().CPlusPlus) { 15929 // C cannot handle TypoExpr nodes on either side of a binop because it 15930 // doesn't handle dependent types properly, so make sure any TypoExprs have 15931 // been dealt with before checking the operands. 15932 ExprResult Result = CorrectDelayedTyposInExpr(E); 15933 if (!Result.isUsable()) return ExprError(); 15934 E = Result.get(); 15935 } 15936 15937 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15938 if (!placeholderType) return E; 15939 15940 switch (placeholderType->getKind()) { 15941 15942 // Overloaded expressions. 15943 case BuiltinType::Overload: { 15944 // Try to resolve a single function template specialization. 15945 // This is obligatory. 15946 ExprResult Result = E; 15947 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15948 return Result; 15949 15950 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15951 // leaves Result unchanged on failure. 15952 Result = E; 15953 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15954 return Result; 15955 15956 // If that failed, try to recover with a call. 15957 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15958 /*complain*/ true); 15959 return Result; 15960 } 15961 15962 // Bound member functions. 15963 case BuiltinType::BoundMember: { 15964 ExprResult result = E; 15965 const Expr *BME = E->IgnoreParens(); 15966 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15967 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15968 if (isa<CXXPseudoDestructorExpr>(BME)) { 15969 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15970 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15971 if (ME->getMemberNameInfo().getName().getNameKind() == 15972 DeclarationName::CXXDestructorName) 15973 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15974 } 15975 tryToRecoverWithCall(result, PD, 15976 /*complain*/ true); 15977 return result; 15978 } 15979 15980 // ARC unbridged casts. 15981 case BuiltinType::ARCUnbridgedCast: { 15982 Expr *realCast = stripARCUnbridgedCast(E); 15983 diagnoseARCUnbridgedCast(realCast); 15984 return realCast; 15985 } 15986 15987 // Expressions of unknown type. 15988 case BuiltinType::UnknownAny: 15989 return diagnoseUnknownAnyExpr(*this, E); 15990 15991 // Pseudo-objects. 15992 case BuiltinType::PseudoObject: 15993 return checkPseudoObjectRValue(E); 15994 15995 case BuiltinType::BuiltinFn: { 15996 // Accept __noop without parens by implicitly converting it to a call expr. 15997 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15998 if (DRE) { 15999 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16000 if (FD->getBuiltinID() == Builtin::BI__noop) { 16001 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16002 CK_BuiltinFnToFnPtr).get(); 16003 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16004 VK_RValue, SourceLocation()); 16005 } 16006 } 16007 16008 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16009 return ExprError(); 16010 } 16011 16012 // Expressions of unknown type. 16013 case BuiltinType::OMPArraySection: 16014 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16015 return ExprError(); 16016 16017 // Everything else should be impossible. 16018 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16019 case BuiltinType::Id: 16020 #include "clang/Basic/OpenCLImageTypes.def" 16021 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16022 #define PLACEHOLDER_TYPE(Id, SingletonId) 16023 #include "clang/AST/BuiltinTypes.def" 16024 break; 16025 } 16026 16027 llvm_unreachable("invalid placeholder type!"); 16028 } 16029 16030 bool Sema::CheckCaseExpression(Expr *E) { 16031 if (E->isTypeDependent()) 16032 return true; 16033 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16034 return E->getType()->isIntegralOrEnumerationType(); 16035 return false; 16036 } 16037 16038 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16039 ExprResult 16040 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16041 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16042 "Unknown Objective-C Boolean value!"); 16043 QualType BoolT = Context.ObjCBuiltinBoolTy; 16044 if (!Context.getBOOLDecl()) { 16045 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16046 Sema::LookupOrdinaryName); 16047 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16048 NamedDecl *ND = Result.getFoundDecl(); 16049 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16050 Context.setBOOLDecl(TD); 16051 } 16052 } 16053 if (Context.getBOOLDecl()) 16054 BoolT = Context.getBOOLType(); 16055 return new (Context) 16056 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16057 } 16058 16059 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16060 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16061 SourceLocation RParen) { 16062 16063 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16064 16065 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16066 [&](const AvailabilitySpec &Spec) { 16067 return Spec.getPlatform() == Platform; 16068 }); 16069 16070 VersionTuple Version; 16071 if (Spec != AvailSpecs.end()) 16072 Version = Spec->getVersion(); 16073 16074 // The use of `@available` in the enclosing function should be analyzed to 16075 // warn when it's used inappropriately (i.e. not if(@available)). 16076 if (getCurFunctionOrMethodDecl()) 16077 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16078 else if (getCurBlock() || getCurLambda()) 16079 getCurFunction()->HasPotentialAvailabilityViolations = true; 16080 16081 return new (Context) 16082 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16083 } 16084