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 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 92 if (!OMD) 93 return false; 94 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 95 if (!OID) 96 return false; 97 98 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 99 if (ObjCMethodDecl *CatMeth = 100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 101 if (!CatMeth->hasAttr<AvailabilityAttr>()) 102 return true; 103 return false; 104 } 105 106 AvailabilityResult Sema::ShouldDiagnoseAvailabilityOfDecl( 107 NamedDecl *&D, VersionTuple ContextVersion, std::string *Message) { 108 AvailabilityResult Result = D->getAvailability(Message, ContextVersion); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(Message, ContextVersion); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(Message, ContextVersion); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(Message, ContextVersion); 136 } 137 138 switch (Result) { 139 case AR_Available: 140 return Result; 141 142 case AR_Unavailable: 143 case AR_Deprecated: 144 return getCurContextAvailability() != Result ? Result : AR_Available; 145 146 case AR_NotYetIntroduced: { 147 // Don't do this for enums, they can't be redeclared. 148 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 149 return AR_Available; 150 151 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 152 // Objective-C method declarations in categories are not modelled as 153 // redeclarations, so manually look for a redeclaration in a category 154 // if necessary. 155 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 156 Warn = false; 157 // In general, D will point to the most recent redeclaration. However, 158 // for `@class A;` decls, this isn't true -- manually go through the 159 // redecl chain in that case. 160 if (Warn && isa<ObjCInterfaceDecl>(D)) 161 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 162 Redecl = Redecl->getPreviousDecl()) 163 if (!Redecl->hasAttr<AvailabilityAttr>() || 164 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 165 Warn = false; 166 167 return Warn ? AR_NotYetIntroduced : AR_Available; 168 } 169 } 170 llvm_unreachable("Unknown availability result!"); 171 } 172 173 static void 174 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 175 const ObjCInterfaceDecl *UnknownObjCClass, 176 bool ObjCPropertyAccess) { 177 VersionTuple ContextVersion; 178 if (const DeclContext *DC = S.getCurObjCLexicalContext()) 179 ContextVersion = S.getVersionForDecl(cast<Decl>(DC)); 180 181 std::string Message; 182 // See if this declaration is unavailable, deprecated, or partial in the 183 // current context. 184 if (AvailabilityResult Result = 185 S.ShouldDiagnoseAvailabilityOfDecl(D, ContextVersion, &Message)) { 186 187 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) { 188 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 189 return; 190 } 191 192 const ObjCPropertyDecl *ObjCPDecl = nullptr; 193 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 194 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 195 AvailabilityResult PDeclResult = 196 PD->getAvailability(nullptr, ContextVersion); 197 if (PDeclResult == Result) 198 ObjCPDecl = PD; 199 } 200 } 201 202 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 203 ObjCPDecl, ObjCPropertyAccess); 204 } 205 } 206 207 /// \brief Emit a note explaining that this function is deleted. 208 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 209 assert(Decl->isDeleted()); 210 211 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 212 213 if (Method && Method->isDeleted() && Method->isDefaulted()) { 214 // If the method was explicitly defaulted, point at that declaration. 215 if (!Method->isImplicit()) 216 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 217 218 // Try to diagnose why this special member function was implicitly 219 // deleted. This might fail, if that reason no longer applies. 220 CXXSpecialMember CSM = getSpecialMember(Method); 221 if (CSM != CXXInvalid) 222 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 223 224 return; 225 } 226 227 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 228 if (Ctor && Ctor->isInheritingConstructor()) 229 return NoteDeletedInheritingConstructor(Ctor); 230 231 Diag(Decl->getLocation(), diag::note_availability_specified_here) 232 << Decl << true; 233 } 234 235 /// \brief Determine whether a FunctionDecl was ever declared with an 236 /// explicit storage class. 237 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 238 for (auto I : D->redecls()) { 239 if (I->getStorageClass() != SC_None) 240 return true; 241 } 242 return false; 243 } 244 245 /// \brief Check whether we're in an extern inline function and referring to a 246 /// variable or function with internal linkage (C11 6.7.4p3). 247 /// 248 /// This is only a warning because we used to silently accept this code, but 249 /// in many cases it will not behave correctly. This is not enabled in C++ mode 250 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 251 /// and so while there may still be user mistakes, most of the time we can't 252 /// prove that there are errors. 253 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 254 const NamedDecl *D, 255 SourceLocation Loc) { 256 // This is disabled under C++; there are too many ways for this to fire in 257 // contexts where the warning is a false positive, or where it is technically 258 // correct but benign. 259 if (S.getLangOpts().CPlusPlus) 260 return; 261 262 // Check if this is an inlined function or method. 263 FunctionDecl *Current = S.getCurFunctionDecl(); 264 if (!Current) 265 return; 266 if (!Current->isInlined()) 267 return; 268 if (!Current->isExternallyVisible()) 269 return; 270 271 // Check if the decl has internal linkage. 272 if (D->getFormalLinkage() != InternalLinkage) 273 return; 274 275 // Downgrade from ExtWarn to Extension if 276 // (1) the supposedly external inline function is in the main file, 277 // and probably won't be included anywhere else. 278 // (2) the thing we're referencing is a pure function. 279 // (3) the thing we're referencing is another inline function. 280 // This last can give us false negatives, but it's better than warning on 281 // wrappers for simple C library functions. 282 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 283 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 284 if (!DowngradeWarning && UsedFn) 285 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 286 287 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 288 : diag::ext_internal_in_extern_inline) 289 << /*IsVar=*/!UsedFn << D; 290 291 S.MaybeSuggestAddingStaticToDecl(Current); 292 293 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 294 << D; 295 } 296 297 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 298 const FunctionDecl *First = Cur->getFirstDecl(); 299 300 // Suggest "static" on the function, if possible. 301 if (!hasAnyExplicitStorageClass(First)) { 302 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 303 Diag(DeclBegin, diag::note_convert_inline_to_static) 304 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 305 } 306 } 307 308 /// \brief Determine whether the use of this declaration is valid, and 309 /// emit any corresponding diagnostics. 310 /// 311 /// This routine diagnoses various problems with referencing 312 /// declarations that can occur when using a declaration. For example, 313 /// it might warn if a deprecated or unavailable declaration is being 314 /// used, or produce an error (and return true) if a C++0x deleted 315 /// function is being used. 316 /// 317 /// \returns true if there was an error (this declaration cannot be 318 /// referenced), false otherwise. 319 /// 320 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 321 const ObjCInterfaceDecl *UnknownObjCClass, 322 bool ObjCPropertyAccess) { 323 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 324 // If there were any diagnostics suppressed by template argument deduction, 325 // emit them now. 326 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 327 if (Pos != SuppressedDiagnostics.end()) { 328 for (const PartialDiagnosticAt &Suppressed : Pos->second) 329 Diag(Suppressed.first, Suppressed.second); 330 331 // Clear out the list of suppressed diagnostics, so that we don't emit 332 // them again for this specialization. However, we don't obsolete this 333 // entry from the table, because we want to avoid ever emitting these 334 // diagnostics again. 335 Pos->second.clear(); 336 } 337 338 // C++ [basic.start.main]p3: 339 // The function 'main' shall not be used within a program. 340 if (cast<FunctionDecl>(D)->isMain()) 341 Diag(Loc, diag::ext_main_used); 342 } 343 344 // See if this is an auto-typed variable whose initializer we are parsing. 345 if (ParsingInitForAutoVars.count(D)) { 346 if (isa<BindingDecl>(D)) { 347 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 348 << D->getDeclName(); 349 } else { 350 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 351 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName() << (unsigned)AT->getKeyword(); 354 } 355 return true; 356 } 357 358 // See if this is a deleted function. 359 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 360 if (FD->isDeleted()) { 361 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 362 if (Ctor && Ctor->isInheritingConstructor()) 363 Diag(Loc, diag::err_deleted_inherited_ctor_use) 364 << Ctor->getParent() 365 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 366 else 367 Diag(Loc, diag::err_deleted_function_use); 368 NoteDeletedFunction(FD); 369 return true; 370 } 371 372 // If the function has a deduced return type, and we can't deduce it, 373 // then we can't use it either. 374 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 375 DeduceReturnType(FD, Loc)) 376 return true; 377 378 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 379 return true; 380 } 381 382 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 383 // Only the variables omp_in and omp_out are allowed in the combiner. 384 // Only the variables omp_priv and omp_orig are allowed in the 385 // initializer-clause. 386 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 387 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 388 isa<VarDecl>(D)) { 389 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 390 << getCurFunction()->HasOMPDeclareReductionCombiner; 391 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 392 return true; 393 } 394 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 395 ObjCPropertyAccess); 396 397 DiagnoseUnusedOfDecl(*this, D, Loc); 398 399 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 400 401 return false; 402 } 403 404 /// \brief Retrieve the message suffix that should be added to a 405 /// diagnostic complaining about the given function being deleted or 406 /// unavailable. 407 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 408 std::string Message; 409 if (FD->getAvailability(&Message)) 410 return ": " + Message; 411 412 return std::string(); 413 } 414 415 /// DiagnoseSentinelCalls - This routine checks whether a call or 416 /// message-send is to a declaration with the sentinel attribute, and 417 /// if so, it checks that the requirements of the sentinel are 418 /// satisfied. 419 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 420 ArrayRef<Expr *> Args) { 421 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 422 if (!attr) 423 return; 424 425 // The number of formal parameters of the declaration. 426 unsigned numFormalParams; 427 428 // The kind of declaration. This is also an index into a %select in 429 // the diagnostic. 430 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 431 432 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 433 numFormalParams = MD->param_size(); 434 calleeType = CT_Method; 435 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 436 numFormalParams = FD->param_size(); 437 calleeType = CT_Function; 438 } else if (isa<VarDecl>(D)) { 439 QualType type = cast<ValueDecl>(D)->getType(); 440 const FunctionType *fn = nullptr; 441 if (const PointerType *ptr = type->getAs<PointerType>()) { 442 fn = ptr->getPointeeType()->getAs<FunctionType>(); 443 if (!fn) return; 444 calleeType = CT_Function; 445 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 446 fn = ptr->getPointeeType()->castAs<FunctionType>(); 447 calleeType = CT_Block; 448 } else { 449 return; 450 } 451 452 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 453 numFormalParams = proto->getNumParams(); 454 } else { 455 numFormalParams = 0; 456 } 457 } else { 458 return; 459 } 460 461 // "nullPos" is the number of formal parameters at the end which 462 // effectively count as part of the variadic arguments. This is 463 // useful if you would prefer to not have *any* formal parameters, 464 // but the language forces you to have at least one. 465 unsigned nullPos = attr->getNullPos(); 466 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 467 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 468 469 // The number of arguments which should follow the sentinel. 470 unsigned numArgsAfterSentinel = attr->getSentinel(); 471 472 // If there aren't enough arguments for all the formal parameters, 473 // the sentinel, and the args after the sentinel, complain. 474 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 475 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 476 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 477 return; 478 } 479 480 // Otherwise, find the sentinel expression. 481 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 482 if (!sentinelExpr) return; 483 if (sentinelExpr->isValueDependent()) return; 484 if (Context.isSentinelNullExpr(sentinelExpr)) return; 485 486 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 487 // or 'NULL' if those are actually defined in the context. Only use 488 // 'nil' for ObjC methods, where it's much more likely that the 489 // variadic arguments form a list of object pointers. 490 SourceLocation MissingNilLoc 491 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 492 std::string NullValue; 493 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 494 NullValue = "nil"; 495 else if (getLangOpts().CPlusPlus11) 496 NullValue = "nullptr"; 497 else if (PP.isMacroDefined("NULL")) 498 NullValue = "NULL"; 499 else 500 NullValue = "(void*) 0"; 501 502 if (MissingNilLoc.isInvalid()) 503 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 504 else 505 Diag(MissingNilLoc, diag::warn_missing_sentinel) 506 << int(calleeType) 507 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 508 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 509 } 510 511 SourceRange Sema::getExprRange(Expr *E) const { 512 return E ? E->getSourceRange() : SourceRange(); 513 } 514 515 //===----------------------------------------------------------------------===// 516 // Standard Promotions and Conversions 517 //===----------------------------------------------------------------------===// 518 519 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 520 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 521 // Handle any placeholder expressions which made it here. 522 if (E->getType()->isPlaceholderType()) { 523 ExprResult result = CheckPlaceholderExpr(E); 524 if (result.isInvalid()) return ExprError(); 525 E = result.get(); 526 } 527 528 QualType Ty = E->getType(); 529 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 530 531 if (Ty->isFunctionType()) { 532 // If we are here, we are not calling a function but taking 533 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 534 if (getLangOpts().OpenCL) { 535 if (Diagnose) 536 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 537 return ExprError(); 538 } 539 540 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 541 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 542 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 543 return ExprError(); 544 545 E = ImpCastExprToType(E, Context.getPointerType(Ty), 546 CK_FunctionToPointerDecay).get(); 547 } else if (Ty->isArrayType()) { 548 // In C90 mode, arrays only promote to pointers if the array expression is 549 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 550 // type 'array of type' is converted to an expression that has type 'pointer 551 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 552 // that has type 'array of type' ...". The relevant change is "an lvalue" 553 // (C90) to "an expression" (C99). 554 // 555 // C++ 4.2p1: 556 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 557 // T" can be converted to an rvalue of type "pointer to T". 558 // 559 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 560 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 561 CK_ArrayToPointerDecay).get(); 562 } 563 return E; 564 } 565 566 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 567 // Check to see if we are dereferencing a null pointer. If so, 568 // and if not volatile-qualified, this is undefined behavior that the 569 // optimizer will delete, so warn about it. People sometimes try to use this 570 // to get a deterministic trap and are surprised by clang's behavior. This 571 // only handles the pattern "*null", which is a very syntactic check. 572 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 573 if (UO->getOpcode() == UO_Deref && 574 UO->getSubExpr()->IgnoreParenCasts()-> 575 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 576 !UO->getType().isVolatileQualified()) { 577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 578 S.PDiag(diag::warn_indirection_through_null) 579 << UO->getSubExpr()->getSourceRange()); 580 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 581 S.PDiag(diag::note_indirection_through_null)); 582 } 583 } 584 585 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 586 SourceLocation AssignLoc, 587 const Expr* RHS) { 588 const ObjCIvarDecl *IV = OIRE->getDecl(); 589 if (!IV) 590 return; 591 592 DeclarationName MemberName = IV->getDeclName(); 593 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 594 if (!Member || !Member->isStr("isa")) 595 return; 596 597 const Expr *Base = OIRE->getBase(); 598 QualType BaseType = Base->getType(); 599 if (OIRE->isArrow()) 600 BaseType = BaseType->getPointeeType(); 601 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 602 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 603 ObjCInterfaceDecl *ClassDeclared = nullptr; 604 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 605 if (!ClassDeclared->getSuperClass() 606 && (*ClassDeclared->ivar_begin()) == IV) { 607 if (RHS) { 608 NamedDecl *ObjectSetClass = 609 S.LookupSingleName(S.TUScope, 610 &S.Context.Idents.get("object_setClass"), 611 SourceLocation(), S.LookupOrdinaryName); 612 if (ObjectSetClass) { 613 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 614 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 615 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 616 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 617 AssignLoc), ",") << 618 FixItHint::CreateInsertion(RHSLocEnd, ")"); 619 } 620 else 621 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 622 } else { 623 NamedDecl *ObjectGetClass = 624 S.LookupSingleName(S.TUScope, 625 &S.Context.Idents.get("object_getClass"), 626 SourceLocation(), S.LookupOrdinaryName); 627 if (ObjectGetClass) 628 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 629 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 630 FixItHint::CreateReplacement( 631 SourceRange(OIRE->getOpLoc(), 632 OIRE->getLocEnd()), ")"); 633 else 634 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 635 } 636 S.Diag(IV->getLocation(), diag::note_ivar_decl); 637 } 638 } 639 } 640 641 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 642 // Handle any placeholder expressions which made it here. 643 if (E->getType()->isPlaceholderType()) { 644 ExprResult result = CheckPlaceholderExpr(E); 645 if (result.isInvalid()) return ExprError(); 646 E = result.get(); 647 } 648 649 // C++ [conv.lval]p1: 650 // A glvalue of a non-function, non-array type T can be 651 // converted to a prvalue. 652 if (!E->isGLValue()) return E; 653 654 QualType T = E->getType(); 655 assert(!T.isNull() && "r-value conversion on typeless expression?"); 656 657 // We don't want to throw lvalue-to-rvalue casts on top of 658 // expressions of certain types in C++. 659 if (getLangOpts().CPlusPlus && 660 (E->getType() == Context.OverloadTy || 661 T->isDependentType() || 662 T->isRecordType())) 663 return E; 664 665 // The C standard is actually really unclear on this point, and 666 // DR106 tells us what the result should be but not why. It's 667 // generally best to say that void types just doesn't undergo 668 // lvalue-to-rvalue at all. Note that expressions of unqualified 669 // 'void' type are never l-values, but qualified void can be. 670 if (T->isVoidType()) 671 return E; 672 673 // OpenCL usually rejects direct accesses to values of 'half' type. 674 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 675 T->isHalfType()) { 676 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 677 << 0 << T; 678 return ExprError(); 679 } 680 681 CheckForNullPointerDereference(*this, E); 682 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 683 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 684 &Context.Idents.get("object_getClass"), 685 SourceLocation(), LookupOrdinaryName); 686 if (ObjectGetClass) 687 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 688 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 689 FixItHint::CreateReplacement( 690 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 691 else 692 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 693 } 694 else if (const ObjCIvarRefExpr *OIRE = 695 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 696 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 697 698 // C++ [conv.lval]p1: 699 // [...] If T is a non-class type, the type of the prvalue is the 700 // cv-unqualified version of T. Otherwise, the type of the 701 // rvalue is T. 702 // 703 // C99 6.3.2.1p2: 704 // If the lvalue has qualified type, the value has the unqualified 705 // version of the type of the lvalue; otherwise, the value has the 706 // type of the lvalue. 707 if (T.hasQualifiers()) 708 T = T.getUnqualifiedType(); 709 710 // Under the MS ABI, lock down the inheritance model now. 711 if (T->isMemberPointerType() && 712 Context.getTargetInfo().getCXXABI().isMicrosoft()) 713 (void)isCompleteType(E->getExprLoc(), T); 714 715 UpdateMarkingForLValueToRValue(E); 716 717 // Loading a __weak object implicitly retains the value, so we need a cleanup to 718 // balance that. 719 if (getLangOpts().ObjCAutoRefCount && 720 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 721 Cleanup.setExprNeedsCleanups(true); 722 723 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 724 nullptr, VK_RValue); 725 726 // C11 6.3.2.1p2: 727 // ... if the lvalue has atomic type, the value has the non-atomic version 728 // of the type of the lvalue ... 729 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 730 T = Atomic->getValueType().getUnqualifiedType(); 731 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 732 nullptr, VK_RValue); 733 } 734 735 return Res; 736 } 737 738 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 739 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 740 if (Res.isInvalid()) 741 return ExprError(); 742 Res = DefaultLvalueConversion(Res.get()); 743 if (Res.isInvalid()) 744 return ExprError(); 745 return Res; 746 } 747 748 /// CallExprUnaryConversions - a special case of an unary conversion 749 /// performed on a function designator of a call expression. 750 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 751 QualType Ty = E->getType(); 752 ExprResult Res = E; 753 // Only do implicit cast for a function type, but not for a pointer 754 // to function type. 755 if (Ty->isFunctionType()) { 756 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 757 CK_FunctionToPointerDecay).get(); 758 if (Res.isInvalid()) 759 return ExprError(); 760 } 761 Res = DefaultLvalueConversion(Res.get()); 762 if (Res.isInvalid()) 763 return ExprError(); 764 return Res.get(); 765 } 766 767 /// UsualUnaryConversions - Performs various conversions that are common to most 768 /// operators (C99 6.3). The conversions of array and function types are 769 /// sometimes suppressed. For example, the array->pointer conversion doesn't 770 /// apply if the array is an argument to the sizeof or address (&) operators. 771 /// In these instances, this routine should *not* be called. 772 ExprResult Sema::UsualUnaryConversions(Expr *E) { 773 // First, convert to an r-value. 774 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 775 if (Res.isInvalid()) 776 return ExprError(); 777 E = Res.get(); 778 779 QualType Ty = E->getType(); 780 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 781 782 // Half FP have to be promoted to float unless it is natively supported 783 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 784 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 785 786 // Try to perform integral promotions if the object has a theoretically 787 // promotable type. 788 if (Ty->isIntegralOrUnscopedEnumerationType()) { 789 // C99 6.3.1.1p2: 790 // 791 // The following may be used in an expression wherever an int or 792 // unsigned int may be used: 793 // - an object or expression with an integer type whose integer 794 // conversion rank is less than or equal to the rank of int 795 // and unsigned int. 796 // - A bit-field of type _Bool, int, signed int, or unsigned int. 797 // 798 // If an int can represent all values of the original type, the 799 // value is converted to an int; otherwise, it is converted to an 800 // unsigned int. These are called the integer promotions. All 801 // other types are unchanged by the integer promotions. 802 803 QualType PTy = Context.isPromotableBitField(E); 804 if (!PTy.isNull()) { 805 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 806 return E; 807 } 808 if (Ty->isPromotableIntegerType()) { 809 QualType PT = Context.getPromotedIntegerType(Ty); 810 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 811 return E; 812 } 813 } 814 return E; 815 } 816 817 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 818 /// do not have a prototype. Arguments that have type float or __fp16 819 /// are promoted to double. All other argument types are converted by 820 /// UsualUnaryConversions(). 821 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 822 QualType Ty = E->getType(); 823 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 824 825 ExprResult Res = UsualUnaryConversions(E); 826 if (Res.isInvalid()) 827 return ExprError(); 828 E = Res.get(); 829 830 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 831 // double. 832 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 833 if (BTy && (BTy->getKind() == BuiltinType::Half || 834 BTy->getKind() == BuiltinType::Float)) 835 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 836 837 // C++ performs lvalue-to-rvalue conversion as a default argument 838 // promotion, even on class types, but note: 839 // C++11 [conv.lval]p2: 840 // When an lvalue-to-rvalue conversion occurs in an unevaluated 841 // operand or a subexpression thereof the value contained in the 842 // referenced object is not accessed. Otherwise, if the glvalue 843 // has a class type, the conversion copy-initializes a temporary 844 // of type T from the glvalue and the result of the conversion 845 // is a prvalue for the temporary. 846 // FIXME: add some way to gate this entire thing for correctness in 847 // potentially potentially evaluated contexts. 848 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 849 ExprResult Temp = PerformCopyInitialization( 850 InitializedEntity::InitializeTemporary(E->getType()), 851 E->getExprLoc(), E); 852 if (Temp.isInvalid()) 853 return ExprError(); 854 E = Temp.get(); 855 } 856 857 return E; 858 } 859 860 /// Determine the degree of POD-ness for an expression. 861 /// Incomplete types are considered POD, since this check can be performed 862 /// when we're in an unevaluated context. 863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 864 if (Ty->isIncompleteType()) { 865 // C++11 [expr.call]p7: 866 // After these conversions, if the argument does not have arithmetic, 867 // enumeration, pointer, pointer to member, or class type, the program 868 // is ill-formed. 869 // 870 // Since we've already performed array-to-pointer and function-to-pointer 871 // decay, the only such type in C++ is cv void. This also handles 872 // initializer lists as variadic arguments. 873 if (Ty->isVoidType()) 874 return VAK_Invalid; 875 876 if (Ty->isObjCObjectType()) 877 return VAK_Invalid; 878 return VAK_Valid; 879 } 880 881 if (Ty.isCXX98PODType(Context)) 882 return VAK_Valid; 883 884 // C++11 [expr.call]p7: 885 // Passing a potentially-evaluated argument of class type (Clause 9) 886 // having a non-trivial copy constructor, a non-trivial move constructor, 887 // or a non-trivial destructor, with no corresponding parameter, 888 // is conditionally-supported with implementation-defined semantics. 889 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 890 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 891 if (!Record->hasNonTrivialCopyConstructor() && 892 !Record->hasNonTrivialMoveConstructor() && 893 !Record->hasNonTrivialDestructor()) 894 return VAK_ValidInCXX11; 895 896 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 897 return VAK_Valid; 898 899 if (Ty->isObjCObjectType()) 900 return VAK_Invalid; 901 902 if (getLangOpts().MSVCCompat) 903 return VAK_MSVCUndefined; 904 905 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 906 // permitted to reject them. We should consider doing so. 907 return VAK_Undefined; 908 } 909 910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 911 // Don't allow one to pass an Objective-C interface to a vararg. 912 const QualType &Ty = E->getType(); 913 VarArgKind VAK = isValidVarArgType(Ty); 914 915 // Complain about passing non-POD types through varargs. 916 switch (VAK) { 917 case VAK_ValidInCXX11: 918 DiagRuntimeBehavior( 919 E->getLocStart(), nullptr, 920 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 921 << Ty << CT); 922 // Fall through. 923 case VAK_Valid: 924 if (Ty->isRecordType()) { 925 // This is unlikely to be what the user intended. If the class has a 926 // 'c_str' member function, the user probably meant to call that. 927 DiagRuntimeBehavior(E->getLocStart(), nullptr, 928 PDiag(diag::warn_pass_class_arg_to_vararg) 929 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 930 } 931 break; 932 933 case VAK_Undefined: 934 case VAK_MSVCUndefined: 935 DiagRuntimeBehavior( 936 E->getLocStart(), nullptr, 937 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 938 << getLangOpts().CPlusPlus11 << Ty << CT); 939 break; 940 941 case VAK_Invalid: 942 if (Ty->isObjCObjectType()) 943 DiagRuntimeBehavior( 944 E->getLocStart(), nullptr, 945 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 946 << Ty << CT); 947 else 948 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 949 << isa<InitListExpr>(E) << Ty << CT; 950 break; 951 } 952 } 953 954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 955 /// will create a trap if the resulting type is not a POD type. 956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 957 FunctionDecl *FDecl) { 958 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 959 // Strip the unbridged-cast placeholder expression off, if applicable. 960 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 961 (CT == VariadicMethod || 962 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 963 E = stripARCUnbridgedCast(E); 964 965 // Otherwise, do normal placeholder checking. 966 } else { 967 ExprResult ExprRes = CheckPlaceholderExpr(E); 968 if (ExprRes.isInvalid()) 969 return ExprError(); 970 E = ExprRes.get(); 971 } 972 } 973 974 ExprResult ExprRes = DefaultArgumentPromotion(E); 975 if (ExprRes.isInvalid()) 976 return ExprError(); 977 E = ExprRes.get(); 978 979 // Diagnostics regarding non-POD argument types are 980 // emitted along with format string checking in Sema::CheckFunctionCall(). 981 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 982 // Turn this into a trap. 983 CXXScopeSpec SS; 984 SourceLocation TemplateKWLoc; 985 UnqualifiedId Name; 986 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 987 E->getLocStart()); 988 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 989 Name, true, false); 990 if (TrapFn.isInvalid()) 991 return ExprError(); 992 993 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 994 E->getLocStart(), None, 995 E->getLocEnd()); 996 if (Call.isInvalid()) 997 return ExprError(); 998 999 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 1000 Call.get(), E); 1001 if (Comma.isInvalid()) 1002 return ExprError(); 1003 return Comma.get(); 1004 } 1005 1006 if (!getLangOpts().CPlusPlus && 1007 RequireCompleteType(E->getExprLoc(), E->getType(), 1008 diag::err_call_incomplete_argument)) 1009 return ExprError(); 1010 1011 return E; 1012 } 1013 1014 /// \brief Converts an integer to complex float type. Helper function of 1015 /// UsualArithmeticConversions() 1016 /// 1017 /// \return false if the integer expression is an integer type and is 1018 /// successfully converted to the complex type. 1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1020 ExprResult &ComplexExpr, 1021 QualType IntTy, 1022 QualType ComplexTy, 1023 bool SkipCast) { 1024 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1025 if (SkipCast) return false; 1026 if (IntTy->isIntegerType()) { 1027 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1029 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1030 CK_FloatingRealToComplex); 1031 } else { 1032 assert(IntTy->isComplexIntegerType()); 1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1034 CK_IntegralComplexToFloatingComplex); 1035 } 1036 return false; 1037 } 1038 1039 /// \brief Handle arithmetic conversion with complex types. Helper function of 1040 /// UsualArithmeticConversions() 1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1042 ExprResult &RHS, QualType LHSType, 1043 QualType RHSType, 1044 bool IsCompAssign) { 1045 // if we have an integer operand, the result is the complex type. 1046 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1047 /*skipCast*/false)) 1048 return LHSType; 1049 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1050 /*skipCast*/IsCompAssign)) 1051 return RHSType; 1052 1053 // This handles complex/complex, complex/float, or float/complex. 1054 // When both operands are complex, the shorter operand is converted to the 1055 // type of the longer, and that is the type of the result. This corresponds 1056 // to what is done when combining two real floating-point operands. 1057 // The fun begins when size promotion occur across type domains. 1058 // From H&S 6.3.4: When one operand is complex and the other is a real 1059 // floating-point type, the less precise type is converted, within it's 1060 // real or complex domain, to the precision of the other type. For example, 1061 // when combining a "long double" with a "double _Complex", the 1062 // "double _Complex" is promoted to "long double _Complex". 1063 1064 // Compute the rank of the two types, regardless of whether they are complex. 1065 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1066 1067 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1068 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1069 QualType LHSElementType = 1070 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1071 QualType RHSElementType = 1072 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1073 1074 QualType ResultType = S.Context.getComplexType(LHSElementType); 1075 if (Order < 0) { 1076 // Promote the precision of the LHS if not an assignment. 1077 ResultType = S.Context.getComplexType(RHSElementType); 1078 if (!IsCompAssign) { 1079 if (LHSComplexType) 1080 LHS = 1081 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1082 else 1083 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1084 } 1085 } else if (Order > 0) { 1086 // Promote the precision of the RHS. 1087 if (RHSComplexType) 1088 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1089 else 1090 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1091 } 1092 return ResultType; 1093 } 1094 1095 /// \brief Hande arithmetic conversion from integer to float. Helper function 1096 /// of UsualArithmeticConversions() 1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1098 ExprResult &IntExpr, 1099 QualType FloatTy, QualType IntTy, 1100 bool ConvertFloat, bool ConvertInt) { 1101 if (IntTy->isIntegerType()) { 1102 if (ConvertInt) 1103 // Convert intExpr to the lhs floating point type. 1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1105 CK_IntegralToFloating); 1106 return FloatTy; 1107 } 1108 1109 // Convert both sides to the appropriate complex float. 1110 assert(IntTy->isComplexIntegerType()); 1111 QualType result = S.Context.getComplexType(FloatTy); 1112 1113 // _Complex int -> _Complex float 1114 if (ConvertInt) 1115 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1116 CK_IntegralComplexToFloatingComplex); 1117 1118 // float -> _Complex float 1119 if (ConvertFloat) 1120 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1121 CK_FloatingRealToComplex); 1122 1123 return result; 1124 } 1125 1126 /// \brief Handle arithmethic conversion with floating point types. Helper 1127 /// function of UsualArithmeticConversions() 1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1129 ExprResult &RHS, QualType LHSType, 1130 QualType RHSType, bool IsCompAssign) { 1131 bool LHSFloat = LHSType->isRealFloatingType(); 1132 bool RHSFloat = RHSType->isRealFloatingType(); 1133 1134 // If we have two real floating types, convert the smaller operand 1135 // to the bigger result. 1136 if (LHSFloat && RHSFloat) { 1137 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1138 if (order > 0) { 1139 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1140 return LHSType; 1141 } 1142 1143 assert(order < 0 && "illegal float comparison"); 1144 if (!IsCompAssign) 1145 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1146 return RHSType; 1147 } 1148 1149 if (LHSFloat) { 1150 // Half FP has to be promoted to float unless it is natively supported 1151 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1152 LHSType = S.Context.FloatTy; 1153 1154 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1155 /*convertFloat=*/!IsCompAssign, 1156 /*convertInt=*/ true); 1157 } 1158 assert(RHSFloat); 1159 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1160 /*convertInt=*/ true, 1161 /*convertFloat=*/!IsCompAssign); 1162 } 1163 1164 /// \brief Diagnose attempts to convert between __float128 and long double if 1165 /// there is no support for such conversion. Helper function of 1166 /// UsualArithmeticConversions(). 1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1168 QualType RHSType) { 1169 /* No issue converting if at least one of the types is not a floating point 1170 type or the two types have the same rank. 1171 */ 1172 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1173 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1174 return false; 1175 1176 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1177 "The remaining types must be floating point types."); 1178 1179 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1180 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1181 1182 QualType LHSElemType = LHSComplex ? 1183 LHSComplex->getElementType() : LHSType; 1184 QualType RHSElemType = RHSComplex ? 1185 RHSComplex->getElementType() : RHSType; 1186 1187 // No issue if the two types have the same representation 1188 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1189 &S.Context.getFloatTypeSemantics(RHSElemType)) 1190 return false; 1191 1192 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1193 RHSElemType == S.Context.LongDoubleTy); 1194 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1195 RHSElemType == S.Context.Float128Ty); 1196 1197 /* We've handled the situation where __float128 and long double have the same 1198 representation. The only other allowable conversion is if long double is 1199 really just double. 1200 */ 1201 return Float128AndLongDouble && 1202 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1203 &llvm::APFloat::IEEEdouble); 1204 } 1205 1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1207 1208 namespace { 1209 /// These helper callbacks are placed in an anonymous namespace to 1210 /// permit their use as function template parameters. 1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1212 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1213 } 1214 1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1216 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1217 CK_IntegralComplexCast); 1218 } 1219 } 1220 1221 /// \brief Handle integer arithmetic conversions. Helper function of 1222 /// UsualArithmeticConversions() 1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1225 ExprResult &RHS, QualType LHSType, 1226 QualType RHSType, bool IsCompAssign) { 1227 // The rules for this case are in C99 6.3.1.8 1228 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1229 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1230 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1231 if (LHSSigned == RHSSigned) { 1232 // Same signedness; use the higher-ranked type 1233 if (order >= 0) { 1234 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1235 return LHSType; 1236 } else if (!IsCompAssign) 1237 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1238 return RHSType; 1239 } else if (order != (LHSSigned ? 1 : -1)) { 1240 // The unsigned type has greater than or equal rank to the 1241 // signed type, so use the unsigned type 1242 if (RHSSigned) { 1243 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1244 return LHSType; 1245 } else if (!IsCompAssign) 1246 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1247 return RHSType; 1248 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1249 // The two types are different widths; if we are here, that 1250 // means the signed type is larger than the unsigned type, so 1251 // use the signed type. 1252 if (LHSSigned) { 1253 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1254 return LHSType; 1255 } else if (!IsCompAssign) 1256 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1257 return RHSType; 1258 } else { 1259 // The signed type is higher-ranked than the unsigned type, 1260 // but isn't actually any bigger (like unsigned int and long 1261 // on most 32-bit systems). Use the unsigned type corresponding 1262 // to the signed type. 1263 QualType result = 1264 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1265 RHS = (*doRHSCast)(S, RHS.get(), result); 1266 if (!IsCompAssign) 1267 LHS = (*doLHSCast)(S, LHS.get(), result); 1268 return result; 1269 } 1270 } 1271 1272 /// \brief Handle conversions with GCC complex int extension. Helper function 1273 /// of UsualArithmeticConversions() 1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1275 ExprResult &RHS, QualType LHSType, 1276 QualType RHSType, 1277 bool IsCompAssign) { 1278 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1279 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1280 1281 if (LHSComplexInt && RHSComplexInt) { 1282 QualType LHSEltType = LHSComplexInt->getElementType(); 1283 QualType RHSEltType = RHSComplexInt->getElementType(); 1284 QualType ScalarType = 1285 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1286 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1287 1288 return S.Context.getComplexType(ScalarType); 1289 } 1290 1291 if (LHSComplexInt) { 1292 QualType LHSEltType = LHSComplexInt->getElementType(); 1293 QualType ScalarType = 1294 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1295 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1296 QualType ComplexType = S.Context.getComplexType(ScalarType); 1297 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1298 CK_IntegralRealToComplex); 1299 1300 return ComplexType; 1301 } 1302 1303 assert(RHSComplexInt); 1304 1305 QualType RHSEltType = RHSComplexInt->getElementType(); 1306 QualType ScalarType = 1307 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1308 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1309 QualType ComplexType = S.Context.getComplexType(ScalarType); 1310 1311 if (!IsCompAssign) 1312 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1313 CK_IntegralRealToComplex); 1314 return ComplexType; 1315 } 1316 1317 /// UsualArithmeticConversions - Performs various conversions that are common to 1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1319 /// routine returns the first non-arithmetic type found. The client is 1320 /// responsible for emitting appropriate error diagnostics. 1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1322 bool IsCompAssign) { 1323 if (!IsCompAssign) { 1324 LHS = UsualUnaryConversions(LHS.get()); 1325 if (LHS.isInvalid()) 1326 return QualType(); 1327 } 1328 1329 RHS = UsualUnaryConversions(RHS.get()); 1330 if (RHS.isInvalid()) 1331 return QualType(); 1332 1333 // For conversion purposes, we ignore any qualifiers. 1334 // For example, "const float" and "float" are equivalent. 1335 QualType LHSType = 1336 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1337 QualType RHSType = 1338 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1339 1340 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1341 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1342 LHSType = AtomicLHS->getValueType(); 1343 1344 // If both types are identical, no conversion is needed. 1345 if (LHSType == RHSType) 1346 return LHSType; 1347 1348 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1349 // The caller can deal with this (e.g. pointer + int). 1350 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1351 return QualType(); 1352 1353 // Apply unary and bitfield promotions to the LHS's type. 1354 QualType LHSUnpromotedType = LHSType; 1355 if (LHSType->isPromotableIntegerType()) 1356 LHSType = Context.getPromotedIntegerType(LHSType); 1357 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1358 if (!LHSBitfieldPromoteTy.isNull()) 1359 LHSType = LHSBitfieldPromoteTy; 1360 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1361 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1362 1363 // If both types are identical, no conversion is needed. 1364 if (LHSType == RHSType) 1365 return LHSType; 1366 1367 // At this point, we have two different arithmetic types. 1368 1369 // Diagnose attempts to convert between __float128 and long double where 1370 // such conversions currently can't be handled. 1371 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1372 return QualType(); 1373 1374 // Handle complex types first (C99 6.3.1.8p1). 1375 if (LHSType->isComplexType() || RHSType->isComplexType()) 1376 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1377 IsCompAssign); 1378 1379 // Now handle "real" floating types (i.e. float, double, long double). 1380 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1381 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1382 IsCompAssign); 1383 1384 // Handle GCC complex int extension. 1385 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1386 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1387 IsCompAssign); 1388 1389 // Finally, we have two differing integer types. 1390 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1391 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1392 } 1393 1394 1395 //===----------------------------------------------------------------------===// 1396 // Semantic Analysis for various Expression Types 1397 //===----------------------------------------------------------------------===// 1398 1399 1400 ExprResult 1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1402 SourceLocation DefaultLoc, 1403 SourceLocation RParenLoc, 1404 Expr *ControllingExpr, 1405 ArrayRef<ParsedType> ArgTypes, 1406 ArrayRef<Expr *> ArgExprs) { 1407 unsigned NumAssocs = ArgTypes.size(); 1408 assert(NumAssocs == ArgExprs.size()); 1409 1410 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1411 for (unsigned i = 0; i < NumAssocs; ++i) { 1412 if (ArgTypes[i]) 1413 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1414 else 1415 Types[i] = nullptr; 1416 } 1417 1418 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1419 ControllingExpr, 1420 llvm::makeArrayRef(Types, NumAssocs), 1421 ArgExprs); 1422 delete [] Types; 1423 return ER; 1424 } 1425 1426 ExprResult 1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1428 SourceLocation DefaultLoc, 1429 SourceLocation RParenLoc, 1430 Expr *ControllingExpr, 1431 ArrayRef<TypeSourceInfo *> Types, 1432 ArrayRef<Expr *> Exprs) { 1433 unsigned NumAssocs = Types.size(); 1434 assert(NumAssocs == Exprs.size()); 1435 1436 // Decay and strip qualifiers for the controlling expression type, and handle 1437 // placeholder type replacement. See committee discussion from WG14 DR423. 1438 { 1439 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1440 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1441 if (R.isInvalid()) 1442 return ExprError(); 1443 ControllingExpr = R.get(); 1444 } 1445 1446 // The controlling expression is an unevaluated operand, so side effects are 1447 // likely unintended. 1448 if (ActiveTemplateInstantiations.empty() && 1449 ControllingExpr->HasSideEffects(Context, false)) 1450 Diag(ControllingExpr->getExprLoc(), 1451 diag::warn_side_effects_unevaluated_context); 1452 1453 bool TypeErrorFound = false, 1454 IsResultDependent = ControllingExpr->isTypeDependent(), 1455 ContainsUnexpandedParameterPack 1456 = ControllingExpr->containsUnexpandedParameterPack(); 1457 1458 for (unsigned i = 0; i < NumAssocs; ++i) { 1459 if (Exprs[i]->containsUnexpandedParameterPack()) 1460 ContainsUnexpandedParameterPack = true; 1461 1462 if (Types[i]) { 1463 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1464 ContainsUnexpandedParameterPack = true; 1465 1466 if (Types[i]->getType()->isDependentType()) { 1467 IsResultDependent = true; 1468 } else { 1469 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1470 // complete object type other than a variably modified type." 1471 unsigned D = 0; 1472 if (Types[i]->getType()->isIncompleteType()) 1473 D = diag::err_assoc_type_incomplete; 1474 else if (!Types[i]->getType()->isObjectType()) 1475 D = diag::err_assoc_type_nonobject; 1476 else if (Types[i]->getType()->isVariablyModifiedType()) 1477 D = diag::err_assoc_type_variably_modified; 1478 1479 if (D != 0) { 1480 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1481 << Types[i]->getTypeLoc().getSourceRange() 1482 << Types[i]->getType(); 1483 TypeErrorFound = true; 1484 } 1485 1486 // C11 6.5.1.1p2 "No two generic associations in the same generic 1487 // selection shall specify compatible types." 1488 for (unsigned j = i+1; j < NumAssocs; ++j) 1489 if (Types[j] && !Types[j]->getType()->isDependentType() && 1490 Context.typesAreCompatible(Types[i]->getType(), 1491 Types[j]->getType())) { 1492 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1493 diag::err_assoc_compatible_types) 1494 << Types[j]->getTypeLoc().getSourceRange() 1495 << Types[j]->getType() 1496 << Types[i]->getType(); 1497 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1498 diag::note_compat_assoc) 1499 << Types[i]->getTypeLoc().getSourceRange() 1500 << Types[i]->getType(); 1501 TypeErrorFound = true; 1502 } 1503 } 1504 } 1505 } 1506 if (TypeErrorFound) 1507 return ExprError(); 1508 1509 // If we determined that the generic selection is result-dependent, don't 1510 // try to compute the result expression. 1511 if (IsResultDependent) 1512 return new (Context) GenericSelectionExpr( 1513 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1514 ContainsUnexpandedParameterPack); 1515 1516 SmallVector<unsigned, 1> CompatIndices; 1517 unsigned DefaultIndex = -1U; 1518 for (unsigned i = 0; i < NumAssocs; ++i) { 1519 if (!Types[i]) 1520 DefaultIndex = i; 1521 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1522 Types[i]->getType())) 1523 CompatIndices.push_back(i); 1524 } 1525 1526 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1527 // type compatible with at most one of the types named in its generic 1528 // association list." 1529 if (CompatIndices.size() > 1) { 1530 // We strip parens here because the controlling expression is typically 1531 // parenthesized in macro definitions. 1532 ControllingExpr = ControllingExpr->IgnoreParens(); 1533 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1534 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1535 << (unsigned) CompatIndices.size(); 1536 for (unsigned I : CompatIndices) { 1537 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1538 diag::note_compat_assoc) 1539 << Types[I]->getTypeLoc().getSourceRange() 1540 << Types[I]->getType(); 1541 } 1542 return ExprError(); 1543 } 1544 1545 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1546 // its controlling expression shall have type compatible with exactly one of 1547 // the types named in its generic association list." 1548 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1549 // We strip parens here because the controlling expression is typically 1550 // parenthesized in macro definitions. 1551 ControllingExpr = ControllingExpr->IgnoreParens(); 1552 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1553 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1554 return ExprError(); 1555 } 1556 1557 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1558 // type name that is compatible with the type of the controlling expression, 1559 // then the result expression of the generic selection is the expression 1560 // in that generic association. Otherwise, the result expression of the 1561 // generic selection is the expression in the default generic association." 1562 unsigned ResultIndex = 1563 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1564 1565 return new (Context) GenericSelectionExpr( 1566 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1567 ContainsUnexpandedParameterPack, ResultIndex); 1568 } 1569 1570 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1571 /// location of the token and the offset of the ud-suffix within it. 1572 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1573 unsigned Offset) { 1574 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1575 S.getLangOpts()); 1576 } 1577 1578 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1579 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1580 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1581 IdentifierInfo *UDSuffix, 1582 SourceLocation UDSuffixLoc, 1583 ArrayRef<Expr*> Args, 1584 SourceLocation LitEndLoc) { 1585 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1586 1587 QualType ArgTy[2]; 1588 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1589 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1590 if (ArgTy[ArgIdx]->isArrayType()) 1591 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1592 } 1593 1594 DeclarationName OpName = 1595 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1596 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1597 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1598 1599 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1600 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1601 /*AllowRaw*/false, /*AllowTemplate*/false, 1602 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1603 return ExprError(); 1604 1605 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1606 } 1607 1608 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1609 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1610 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1611 /// multiple tokens. However, the common case is that StringToks points to one 1612 /// string. 1613 /// 1614 ExprResult 1615 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1616 assert(!StringToks.empty() && "Must have at least one string!"); 1617 1618 StringLiteralParser Literal(StringToks, PP); 1619 if (Literal.hadError) 1620 return ExprError(); 1621 1622 SmallVector<SourceLocation, 4> StringTokLocs; 1623 for (const Token &Tok : StringToks) 1624 StringTokLocs.push_back(Tok.getLocation()); 1625 1626 QualType CharTy = Context.CharTy; 1627 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1628 if (Literal.isWide()) { 1629 CharTy = Context.getWideCharType(); 1630 Kind = StringLiteral::Wide; 1631 } else if (Literal.isUTF8()) { 1632 Kind = StringLiteral::UTF8; 1633 } else if (Literal.isUTF16()) { 1634 CharTy = Context.Char16Ty; 1635 Kind = StringLiteral::UTF16; 1636 } else if (Literal.isUTF32()) { 1637 CharTy = Context.Char32Ty; 1638 Kind = StringLiteral::UTF32; 1639 } else if (Literal.isPascal()) { 1640 CharTy = Context.UnsignedCharTy; 1641 } 1642 1643 QualType CharTyConst = CharTy; 1644 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1645 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1646 CharTyConst.addConst(); 1647 1648 // Get an array type for the string, according to C99 6.4.5. This includes 1649 // the nul terminator character as well as the string length for pascal 1650 // strings. 1651 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1652 llvm::APInt(32, Literal.GetNumStringChars()+1), 1653 ArrayType::Normal, 0); 1654 1655 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1656 if (getLangOpts().OpenCL) { 1657 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1658 } 1659 1660 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1661 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1662 Kind, Literal.Pascal, StrTy, 1663 &StringTokLocs[0], 1664 StringTokLocs.size()); 1665 if (Literal.getUDSuffix().empty()) 1666 return Lit; 1667 1668 // We're building a user-defined literal. 1669 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1670 SourceLocation UDSuffixLoc = 1671 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1672 Literal.getUDSuffixOffset()); 1673 1674 // Make sure we're allowed user-defined literals here. 1675 if (!UDLScope) 1676 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1677 1678 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1679 // operator "" X (str, len) 1680 QualType SizeType = Context.getSizeType(); 1681 1682 DeclarationName OpName = 1683 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1684 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1685 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1686 1687 QualType ArgTy[] = { 1688 Context.getArrayDecayedType(StrTy), SizeType 1689 }; 1690 1691 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1692 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1693 /*AllowRaw*/false, /*AllowTemplate*/false, 1694 /*AllowStringTemplate*/true)) { 1695 1696 case LOLR_Cooked: { 1697 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1698 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1699 StringTokLocs[0]); 1700 Expr *Args[] = { Lit, LenArg }; 1701 1702 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1703 } 1704 1705 case LOLR_StringTemplate: { 1706 TemplateArgumentListInfo ExplicitArgs; 1707 1708 unsigned CharBits = Context.getIntWidth(CharTy); 1709 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1710 llvm::APSInt Value(CharBits, CharIsUnsigned); 1711 1712 TemplateArgument TypeArg(CharTy); 1713 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1714 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1715 1716 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1717 Value = Lit->getCodeUnit(I); 1718 TemplateArgument Arg(Context, Value, CharTy); 1719 TemplateArgumentLocInfo ArgInfo; 1720 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1721 } 1722 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1723 &ExplicitArgs); 1724 } 1725 case LOLR_Raw: 1726 case LOLR_Template: 1727 llvm_unreachable("unexpected literal operator lookup result"); 1728 case LOLR_Error: 1729 return ExprError(); 1730 } 1731 llvm_unreachable("unexpected literal operator lookup result"); 1732 } 1733 1734 ExprResult 1735 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1736 SourceLocation Loc, 1737 const CXXScopeSpec *SS) { 1738 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1739 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1740 } 1741 1742 /// BuildDeclRefExpr - Build an expression that references a 1743 /// declaration that does not require a closure capture. 1744 ExprResult 1745 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1746 const DeclarationNameInfo &NameInfo, 1747 const CXXScopeSpec *SS, NamedDecl *FoundD, 1748 const TemplateArgumentListInfo *TemplateArgs) { 1749 bool RefersToCapturedVariable = 1750 isa<VarDecl>(D) && 1751 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1752 1753 DeclRefExpr *E; 1754 if (isa<VarTemplateSpecializationDecl>(D)) { 1755 VarTemplateSpecializationDecl *VarSpec = 1756 cast<VarTemplateSpecializationDecl>(D); 1757 1758 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1759 : NestedNameSpecifierLoc(), 1760 VarSpec->getTemplateKeywordLoc(), D, 1761 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1762 FoundD, TemplateArgs); 1763 } else { 1764 assert(!TemplateArgs && "No template arguments for non-variable" 1765 " template specialization references"); 1766 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1767 : NestedNameSpecifierLoc(), 1768 SourceLocation(), D, RefersToCapturedVariable, 1769 NameInfo, Ty, VK, FoundD); 1770 } 1771 1772 MarkDeclRefReferenced(E); 1773 1774 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1775 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1776 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1777 recordUseOfEvaluatedWeak(E); 1778 1779 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1780 UnusedPrivateFields.remove(FD); 1781 // Just in case we're building an illegal pointer-to-member. 1782 if (FD->isBitField()) 1783 E->setObjectKind(OK_BitField); 1784 } 1785 1786 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1787 // designates a bit-field. 1788 if (auto *BD = dyn_cast<BindingDecl>(D)) 1789 if (auto *BE = BD->getBinding()) 1790 E->setObjectKind(BE->getObjectKind()); 1791 1792 return E; 1793 } 1794 1795 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1796 /// possibly a list of template arguments. 1797 /// 1798 /// If this produces template arguments, it is permitted to call 1799 /// DecomposeTemplateName. 1800 /// 1801 /// This actually loses a lot of source location information for 1802 /// non-standard name kinds; we should consider preserving that in 1803 /// some way. 1804 void 1805 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1806 TemplateArgumentListInfo &Buffer, 1807 DeclarationNameInfo &NameInfo, 1808 const TemplateArgumentListInfo *&TemplateArgs) { 1809 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1810 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1811 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1812 1813 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1814 Id.TemplateId->NumArgs); 1815 translateTemplateArguments(TemplateArgsPtr, Buffer); 1816 1817 TemplateName TName = Id.TemplateId->Template.get(); 1818 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1819 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1820 TemplateArgs = &Buffer; 1821 } else { 1822 NameInfo = GetNameFromUnqualifiedId(Id); 1823 TemplateArgs = nullptr; 1824 } 1825 } 1826 1827 static void emitEmptyLookupTypoDiagnostic( 1828 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1829 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1830 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1831 DeclContext *Ctx = 1832 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1833 if (!TC) { 1834 // Emit a special diagnostic for failed member lookups. 1835 // FIXME: computing the declaration context might fail here (?) 1836 if (Ctx) 1837 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1838 << SS.getRange(); 1839 else 1840 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1841 return; 1842 } 1843 1844 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1845 bool DroppedSpecifier = 1846 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1847 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1848 ? diag::note_implicit_param_decl 1849 : diag::note_previous_decl; 1850 if (!Ctx) 1851 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1852 SemaRef.PDiag(NoteID)); 1853 else 1854 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1855 << Typo << Ctx << DroppedSpecifier 1856 << SS.getRange(), 1857 SemaRef.PDiag(NoteID)); 1858 } 1859 1860 /// Diagnose an empty lookup. 1861 /// 1862 /// \return false if new lookup candidates were found 1863 bool 1864 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1865 std::unique_ptr<CorrectionCandidateCallback> CCC, 1866 TemplateArgumentListInfo *ExplicitTemplateArgs, 1867 ArrayRef<Expr *> Args, TypoExpr **Out) { 1868 DeclarationName Name = R.getLookupName(); 1869 1870 unsigned diagnostic = diag::err_undeclared_var_use; 1871 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1872 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1873 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1874 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1875 diagnostic = diag::err_undeclared_use; 1876 diagnostic_suggest = diag::err_undeclared_use_suggest; 1877 } 1878 1879 // If the original lookup was an unqualified lookup, fake an 1880 // unqualified lookup. This is useful when (for example) the 1881 // original lookup would not have found something because it was a 1882 // dependent name. 1883 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1884 while (DC) { 1885 if (isa<CXXRecordDecl>(DC)) { 1886 LookupQualifiedName(R, DC); 1887 1888 if (!R.empty()) { 1889 // Don't give errors about ambiguities in this lookup. 1890 R.suppressDiagnostics(); 1891 1892 // During a default argument instantiation the CurContext points 1893 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1894 // function parameter list, hence add an explicit check. 1895 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1896 ActiveTemplateInstantiations.back().Kind == 1897 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1898 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1899 bool isInstance = CurMethod && 1900 CurMethod->isInstance() && 1901 DC == CurMethod->getParent() && !isDefaultArgument; 1902 1903 // Give a code modification hint to insert 'this->'. 1904 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1905 // Actually quite difficult! 1906 if (getLangOpts().MSVCCompat) 1907 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1908 if (isInstance) { 1909 Diag(R.getNameLoc(), diagnostic) << Name 1910 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1911 CheckCXXThisCapture(R.getNameLoc()); 1912 } else { 1913 Diag(R.getNameLoc(), diagnostic) << Name; 1914 } 1915 1916 // Do we really want to note all of these? 1917 for (NamedDecl *D : R) 1918 Diag(D->getLocation(), diag::note_dependent_var_use); 1919 1920 // Return true if we are inside a default argument instantiation 1921 // and the found name refers to an instance member function, otherwise 1922 // the function calling DiagnoseEmptyLookup will try to create an 1923 // implicit member call and this is wrong for default argument. 1924 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1925 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1926 return true; 1927 } 1928 1929 // Tell the callee to try to recover. 1930 return false; 1931 } 1932 1933 R.clear(); 1934 } 1935 1936 // In Microsoft mode, if we are performing lookup from within a friend 1937 // function definition declared at class scope then we must set 1938 // DC to the lexical parent to be able to search into the parent 1939 // class. 1940 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1941 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1942 DC->getLexicalParent()->isRecord()) 1943 DC = DC->getLexicalParent(); 1944 else 1945 DC = DC->getParent(); 1946 } 1947 1948 // We didn't find anything, so try to correct for a typo. 1949 TypoCorrection Corrected; 1950 if (S && Out) { 1951 SourceLocation TypoLoc = R.getNameLoc(); 1952 assert(!ExplicitTemplateArgs && 1953 "Diagnosing an empty lookup with explicit template args!"); 1954 *Out = CorrectTypoDelayed( 1955 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1956 [=](const TypoCorrection &TC) { 1957 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1958 diagnostic, diagnostic_suggest); 1959 }, 1960 nullptr, CTK_ErrorRecovery); 1961 if (*Out) 1962 return true; 1963 } else if (S && (Corrected = 1964 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1965 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1966 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1967 bool DroppedSpecifier = 1968 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1969 R.setLookupName(Corrected.getCorrection()); 1970 1971 bool AcceptableWithRecovery = false; 1972 bool AcceptableWithoutRecovery = false; 1973 NamedDecl *ND = Corrected.getFoundDecl(); 1974 if (ND) { 1975 if (Corrected.isOverloaded()) { 1976 OverloadCandidateSet OCS(R.getNameLoc(), 1977 OverloadCandidateSet::CSK_Normal); 1978 OverloadCandidateSet::iterator Best; 1979 for (NamedDecl *CD : Corrected) { 1980 if (FunctionTemplateDecl *FTD = 1981 dyn_cast<FunctionTemplateDecl>(CD)) 1982 AddTemplateOverloadCandidate( 1983 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1984 Args, OCS); 1985 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1986 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1987 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1988 Args, OCS); 1989 } 1990 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1991 case OR_Success: 1992 ND = Best->FoundDecl; 1993 Corrected.setCorrectionDecl(ND); 1994 break; 1995 default: 1996 // FIXME: Arbitrarily pick the first declaration for the note. 1997 Corrected.setCorrectionDecl(ND); 1998 break; 1999 } 2000 } 2001 R.addDecl(ND); 2002 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2003 CXXRecordDecl *Record = nullptr; 2004 if (Corrected.getCorrectionSpecifier()) { 2005 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2006 Record = Ty->getAsCXXRecordDecl(); 2007 } 2008 if (!Record) 2009 Record = cast<CXXRecordDecl>( 2010 ND->getDeclContext()->getRedeclContext()); 2011 R.setNamingClass(Record); 2012 } 2013 2014 auto *UnderlyingND = ND->getUnderlyingDecl(); 2015 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2016 isa<FunctionTemplateDecl>(UnderlyingND); 2017 // FIXME: If we ended up with a typo for a type name or 2018 // Objective-C class name, we're in trouble because the parser 2019 // is in the wrong place to recover. Suggest the typo 2020 // correction, but don't make it a fix-it since we're not going 2021 // to recover well anyway. 2022 AcceptableWithoutRecovery = 2023 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2024 } else { 2025 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2026 // because we aren't able to recover. 2027 AcceptableWithoutRecovery = true; 2028 } 2029 2030 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2031 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2032 ? diag::note_implicit_param_decl 2033 : diag::note_previous_decl; 2034 if (SS.isEmpty()) 2035 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2036 PDiag(NoteID), AcceptableWithRecovery); 2037 else 2038 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2039 << Name << computeDeclContext(SS, false) 2040 << DroppedSpecifier << SS.getRange(), 2041 PDiag(NoteID), AcceptableWithRecovery); 2042 2043 // Tell the callee whether to try to recover. 2044 return !AcceptableWithRecovery; 2045 } 2046 } 2047 R.clear(); 2048 2049 // Emit a special diagnostic for failed member lookups. 2050 // FIXME: computing the declaration context might fail here (?) 2051 if (!SS.isEmpty()) { 2052 Diag(R.getNameLoc(), diag::err_no_member) 2053 << Name << computeDeclContext(SS, false) 2054 << SS.getRange(); 2055 return true; 2056 } 2057 2058 // Give up, we can't recover. 2059 Diag(R.getNameLoc(), diagnostic) << Name; 2060 return true; 2061 } 2062 2063 /// In Microsoft mode, if we are inside a template class whose parent class has 2064 /// dependent base classes, and we can't resolve an unqualified identifier, then 2065 /// assume the identifier is a member of a dependent base class. We can only 2066 /// recover successfully in static methods, instance methods, and other contexts 2067 /// where 'this' is available. This doesn't precisely match MSVC's 2068 /// instantiation model, but it's close enough. 2069 static Expr * 2070 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2071 DeclarationNameInfo &NameInfo, 2072 SourceLocation TemplateKWLoc, 2073 const TemplateArgumentListInfo *TemplateArgs) { 2074 // Only try to recover from lookup into dependent bases in static methods or 2075 // contexts where 'this' is available. 2076 QualType ThisType = S.getCurrentThisType(); 2077 const CXXRecordDecl *RD = nullptr; 2078 if (!ThisType.isNull()) 2079 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2080 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2081 RD = MD->getParent(); 2082 if (!RD || !RD->hasAnyDependentBases()) 2083 return nullptr; 2084 2085 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2086 // is available, suggest inserting 'this->' as a fixit. 2087 SourceLocation Loc = NameInfo.getLoc(); 2088 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2089 DB << NameInfo.getName() << RD; 2090 2091 if (!ThisType.isNull()) { 2092 DB << FixItHint::CreateInsertion(Loc, "this->"); 2093 return CXXDependentScopeMemberExpr::Create( 2094 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2095 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2096 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2097 } 2098 2099 // Synthesize a fake NNS that points to the derived class. This will 2100 // perform name lookup during template instantiation. 2101 CXXScopeSpec SS; 2102 auto *NNS = 2103 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2104 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2105 return DependentScopeDeclRefExpr::Create( 2106 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2107 TemplateArgs); 2108 } 2109 2110 ExprResult 2111 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2112 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2113 bool HasTrailingLParen, bool IsAddressOfOperand, 2114 std::unique_ptr<CorrectionCandidateCallback> CCC, 2115 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2116 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2117 "cannot be direct & operand and have a trailing lparen"); 2118 if (SS.isInvalid()) 2119 return ExprError(); 2120 2121 TemplateArgumentListInfo TemplateArgsBuffer; 2122 2123 // Decompose the UnqualifiedId into the following data. 2124 DeclarationNameInfo NameInfo; 2125 const TemplateArgumentListInfo *TemplateArgs; 2126 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2127 2128 DeclarationName Name = NameInfo.getName(); 2129 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2130 SourceLocation NameLoc = NameInfo.getLoc(); 2131 2132 // C++ [temp.dep.expr]p3: 2133 // An id-expression is type-dependent if it contains: 2134 // -- an identifier that was declared with a dependent type, 2135 // (note: handled after lookup) 2136 // -- a template-id that is dependent, 2137 // (note: handled in BuildTemplateIdExpr) 2138 // -- a conversion-function-id that specifies a dependent type, 2139 // -- a nested-name-specifier that contains a class-name that 2140 // names a dependent type. 2141 // Determine whether this is a member of an unknown specialization; 2142 // we need to handle these differently. 2143 bool DependentID = false; 2144 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2145 Name.getCXXNameType()->isDependentType()) { 2146 DependentID = true; 2147 } else if (SS.isSet()) { 2148 if (DeclContext *DC = computeDeclContext(SS, false)) { 2149 if (RequireCompleteDeclContext(SS, DC)) 2150 return ExprError(); 2151 } else { 2152 DependentID = true; 2153 } 2154 } 2155 2156 if (DependentID) 2157 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2158 IsAddressOfOperand, TemplateArgs); 2159 2160 // Perform the required lookup. 2161 LookupResult R(*this, NameInfo, 2162 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2163 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2164 if (TemplateArgs) { 2165 // Lookup the template name again to correctly establish the context in 2166 // which it was found. This is really unfortunate as we already did the 2167 // lookup to determine that it was a template name in the first place. If 2168 // this becomes a performance hit, we can work harder to preserve those 2169 // results until we get here but it's likely not worth it. 2170 bool MemberOfUnknownSpecialization; 2171 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2172 MemberOfUnknownSpecialization); 2173 2174 if (MemberOfUnknownSpecialization || 2175 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2176 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2177 IsAddressOfOperand, TemplateArgs); 2178 } else { 2179 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2180 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2181 2182 // If the result might be in a dependent base class, this is a dependent 2183 // id-expression. 2184 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2185 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2186 IsAddressOfOperand, TemplateArgs); 2187 2188 // If this reference is in an Objective-C method, then we need to do 2189 // some special Objective-C lookup, too. 2190 if (IvarLookupFollowUp) { 2191 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2192 if (E.isInvalid()) 2193 return ExprError(); 2194 2195 if (Expr *Ex = E.getAs<Expr>()) 2196 return Ex; 2197 } 2198 } 2199 2200 if (R.isAmbiguous()) 2201 return ExprError(); 2202 2203 // This could be an implicitly declared function reference (legal in C90, 2204 // extension in C99, forbidden in C++). 2205 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2206 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2207 if (D) R.addDecl(D); 2208 } 2209 2210 // Determine whether this name might be a candidate for 2211 // argument-dependent lookup. 2212 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2213 2214 if (R.empty() && !ADL) { 2215 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2216 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2217 TemplateKWLoc, TemplateArgs)) 2218 return E; 2219 } 2220 2221 // Don't diagnose an empty lookup for inline assembly. 2222 if (IsInlineAsmIdentifier) 2223 return ExprError(); 2224 2225 // If this name wasn't predeclared and if this is not a function 2226 // call, diagnose the problem. 2227 TypoExpr *TE = nullptr; 2228 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2229 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2230 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2231 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2232 "Typo correction callback misconfigured"); 2233 if (CCC) { 2234 // Make sure the callback knows what the typo being diagnosed is. 2235 CCC->setTypoName(II); 2236 if (SS.isValid()) 2237 CCC->setTypoNNS(SS.getScopeRep()); 2238 } 2239 if (DiagnoseEmptyLookup(S, SS, R, 2240 CCC ? std::move(CCC) : std::move(DefaultValidator), 2241 nullptr, None, &TE)) { 2242 if (TE && KeywordReplacement) { 2243 auto &State = getTypoExprState(TE); 2244 auto BestTC = State.Consumer->getNextCorrection(); 2245 if (BestTC.isKeyword()) { 2246 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2247 if (State.DiagHandler) 2248 State.DiagHandler(BestTC); 2249 KeywordReplacement->startToken(); 2250 KeywordReplacement->setKind(II->getTokenID()); 2251 KeywordReplacement->setIdentifierInfo(II); 2252 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2253 // Clean up the state associated with the TypoExpr, since it has 2254 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2255 clearDelayedTypo(TE); 2256 // Signal that a correction to a keyword was performed by returning a 2257 // valid-but-null ExprResult. 2258 return (Expr*)nullptr; 2259 } 2260 State.Consumer->resetCorrectionStream(); 2261 } 2262 return TE ? TE : ExprError(); 2263 } 2264 2265 assert(!R.empty() && 2266 "DiagnoseEmptyLookup returned false but added no results"); 2267 2268 // If we found an Objective-C instance variable, let 2269 // LookupInObjCMethod build the appropriate expression to 2270 // reference the ivar. 2271 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2272 R.clear(); 2273 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2274 // In a hopelessly buggy code, Objective-C instance variable 2275 // lookup fails and no expression will be built to reference it. 2276 if (!E.isInvalid() && !E.get()) 2277 return ExprError(); 2278 return E; 2279 } 2280 } 2281 2282 // This is guaranteed from this point on. 2283 assert(!R.empty() || ADL); 2284 2285 // Check whether this might be a C++ implicit instance member access. 2286 // C++ [class.mfct.non-static]p3: 2287 // When an id-expression that is not part of a class member access 2288 // syntax and not used to form a pointer to member is used in the 2289 // body of a non-static member function of class X, if name lookup 2290 // resolves the name in the id-expression to a non-static non-type 2291 // member of some class C, the id-expression is transformed into a 2292 // class member access expression using (*this) as the 2293 // postfix-expression to the left of the . operator. 2294 // 2295 // But we don't actually need to do this for '&' operands if R 2296 // resolved to a function or overloaded function set, because the 2297 // expression is ill-formed if it actually works out to be a 2298 // non-static member function: 2299 // 2300 // C++ [expr.ref]p4: 2301 // Otherwise, if E1.E2 refers to a non-static member function. . . 2302 // [t]he expression can be used only as the left-hand operand of a 2303 // member function call. 2304 // 2305 // There are other safeguards against such uses, but it's important 2306 // to get this right here so that we don't end up making a 2307 // spuriously dependent expression if we're inside a dependent 2308 // instance method. 2309 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2310 bool MightBeImplicitMember; 2311 if (!IsAddressOfOperand) 2312 MightBeImplicitMember = true; 2313 else if (!SS.isEmpty()) 2314 MightBeImplicitMember = false; 2315 else if (R.isOverloadedResult()) 2316 MightBeImplicitMember = false; 2317 else if (R.isUnresolvableResult()) 2318 MightBeImplicitMember = true; 2319 else 2320 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2321 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2322 isa<MSPropertyDecl>(R.getFoundDecl()); 2323 2324 if (MightBeImplicitMember) 2325 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2326 R, TemplateArgs, S); 2327 } 2328 2329 if (TemplateArgs || TemplateKWLoc.isValid()) { 2330 2331 // In C++1y, if this is a variable template id, then check it 2332 // in BuildTemplateIdExpr(). 2333 // The single lookup result must be a variable template declaration. 2334 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2335 Id.TemplateId->Kind == TNK_Var_template) { 2336 assert(R.getAsSingle<VarTemplateDecl>() && 2337 "There should only be one declaration found."); 2338 } 2339 2340 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2341 } 2342 2343 return BuildDeclarationNameExpr(SS, R, ADL); 2344 } 2345 2346 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2347 /// declaration name, generally during template instantiation. 2348 /// There's a large number of things which don't need to be done along 2349 /// this path. 2350 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2351 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2352 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2353 DeclContext *DC = computeDeclContext(SS, false); 2354 if (!DC) 2355 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2356 NameInfo, /*TemplateArgs=*/nullptr); 2357 2358 if (RequireCompleteDeclContext(SS, DC)) 2359 return ExprError(); 2360 2361 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2362 LookupQualifiedName(R, DC); 2363 2364 if (R.isAmbiguous()) 2365 return ExprError(); 2366 2367 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2368 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2369 NameInfo, /*TemplateArgs=*/nullptr); 2370 2371 if (R.empty()) { 2372 Diag(NameInfo.getLoc(), diag::err_no_member) 2373 << NameInfo.getName() << DC << SS.getRange(); 2374 return ExprError(); 2375 } 2376 2377 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2378 // Diagnose a missing typename if this resolved unambiguously to a type in 2379 // a dependent context. If we can recover with a type, downgrade this to 2380 // a warning in Microsoft compatibility mode. 2381 unsigned DiagID = diag::err_typename_missing; 2382 if (RecoveryTSI && getLangOpts().MSVCCompat) 2383 DiagID = diag::ext_typename_missing; 2384 SourceLocation Loc = SS.getBeginLoc(); 2385 auto D = Diag(Loc, DiagID); 2386 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2387 << SourceRange(Loc, NameInfo.getEndLoc()); 2388 2389 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2390 // context. 2391 if (!RecoveryTSI) 2392 return ExprError(); 2393 2394 // Only issue the fixit if we're prepared to recover. 2395 D << FixItHint::CreateInsertion(Loc, "typename "); 2396 2397 // Recover by pretending this was an elaborated type. 2398 QualType Ty = Context.getTypeDeclType(TD); 2399 TypeLocBuilder TLB; 2400 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2401 2402 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2403 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2404 QTL.setElaboratedKeywordLoc(SourceLocation()); 2405 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2406 2407 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2408 2409 return ExprEmpty(); 2410 } 2411 2412 // Defend against this resolving to an implicit member access. We usually 2413 // won't get here if this might be a legitimate a class member (we end up in 2414 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2415 // a pointer-to-member or in an unevaluated context in C++11. 2416 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2417 return BuildPossibleImplicitMemberExpr(SS, 2418 /*TemplateKWLoc=*/SourceLocation(), 2419 R, /*TemplateArgs=*/nullptr, S); 2420 2421 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2422 } 2423 2424 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2425 /// detected that we're currently inside an ObjC method. Perform some 2426 /// additional lookup. 2427 /// 2428 /// Ideally, most of this would be done by lookup, but there's 2429 /// actually quite a lot of extra work involved. 2430 /// 2431 /// Returns a null sentinel to indicate trivial success. 2432 ExprResult 2433 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2434 IdentifierInfo *II, bool AllowBuiltinCreation) { 2435 SourceLocation Loc = Lookup.getNameLoc(); 2436 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2437 2438 // Check for error condition which is already reported. 2439 if (!CurMethod) 2440 return ExprError(); 2441 2442 // There are two cases to handle here. 1) scoped lookup could have failed, 2443 // in which case we should look for an ivar. 2) scoped lookup could have 2444 // found a decl, but that decl is outside the current instance method (i.e. 2445 // a global variable). In these two cases, we do a lookup for an ivar with 2446 // this name, if the lookup sucedes, we replace it our current decl. 2447 2448 // If we're in a class method, we don't normally want to look for 2449 // ivars. But if we don't find anything else, and there's an 2450 // ivar, that's an error. 2451 bool IsClassMethod = CurMethod->isClassMethod(); 2452 2453 bool LookForIvars; 2454 if (Lookup.empty()) 2455 LookForIvars = true; 2456 else if (IsClassMethod) 2457 LookForIvars = false; 2458 else 2459 LookForIvars = (Lookup.isSingleResult() && 2460 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2461 ObjCInterfaceDecl *IFace = nullptr; 2462 if (LookForIvars) { 2463 IFace = CurMethod->getClassInterface(); 2464 ObjCInterfaceDecl *ClassDeclared; 2465 ObjCIvarDecl *IV = nullptr; 2466 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2467 // Diagnose using an ivar in a class method. 2468 if (IsClassMethod) 2469 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2470 << IV->getDeclName()); 2471 2472 // If we're referencing an invalid decl, just return this as a silent 2473 // error node. The error diagnostic was already emitted on the decl. 2474 if (IV->isInvalidDecl()) 2475 return ExprError(); 2476 2477 // Check if referencing a field with __attribute__((deprecated)). 2478 if (DiagnoseUseOfDecl(IV, Loc)) 2479 return ExprError(); 2480 2481 // Diagnose the use of an ivar outside of the declaring class. 2482 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2483 !declaresSameEntity(ClassDeclared, IFace) && 2484 !getLangOpts().DebuggerSupport) 2485 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2486 2487 // FIXME: This should use a new expr for a direct reference, don't 2488 // turn this into Self->ivar, just return a BareIVarExpr or something. 2489 IdentifierInfo &II = Context.Idents.get("self"); 2490 UnqualifiedId SelfName; 2491 SelfName.setIdentifier(&II, SourceLocation()); 2492 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2493 CXXScopeSpec SelfScopeSpec; 2494 SourceLocation TemplateKWLoc; 2495 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2496 SelfName, false, false); 2497 if (SelfExpr.isInvalid()) 2498 return ExprError(); 2499 2500 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2501 if (SelfExpr.isInvalid()) 2502 return ExprError(); 2503 2504 MarkAnyDeclReferenced(Loc, IV, true); 2505 2506 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2507 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2508 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2509 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2510 2511 ObjCIvarRefExpr *Result = new (Context) 2512 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2513 IV->getLocation(), SelfExpr.get(), true, true); 2514 2515 if (getLangOpts().ObjCAutoRefCount) { 2516 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2517 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2518 recordUseOfEvaluatedWeak(Result); 2519 } 2520 if (CurContext->isClosure()) 2521 Diag(Loc, diag::warn_implicitly_retains_self) 2522 << FixItHint::CreateInsertion(Loc, "self->"); 2523 } 2524 2525 return Result; 2526 } 2527 } else if (CurMethod->isInstanceMethod()) { 2528 // We should warn if a local variable hides an ivar. 2529 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2530 ObjCInterfaceDecl *ClassDeclared; 2531 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2532 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2533 declaresSameEntity(IFace, ClassDeclared)) 2534 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2535 } 2536 } 2537 } else if (Lookup.isSingleResult() && 2538 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2539 // If accessing a stand-alone ivar in a class method, this is an error. 2540 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2541 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2542 << IV->getDeclName()); 2543 } 2544 2545 if (Lookup.empty() && II && AllowBuiltinCreation) { 2546 // FIXME. Consolidate this with similar code in LookupName. 2547 if (unsigned BuiltinID = II->getBuiltinID()) { 2548 if (!(getLangOpts().CPlusPlus && 2549 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2550 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2551 S, Lookup.isForRedeclaration(), 2552 Lookup.getNameLoc()); 2553 if (D) Lookup.addDecl(D); 2554 } 2555 } 2556 } 2557 // Sentinel value saying that we didn't do anything special. 2558 return ExprResult((Expr *)nullptr); 2559 } 2560 2561 /// \brief Cast a base object to a member's actual type. 2562 /// 2563 /// Logically this happens in three phases: 2564 /// 2565 /// * First we cast from the base type to the naming class. 2566 /// The naming class is the class into which we were looking 2567 /// when we found the member; it's the qualifier type if a 2568 /// qualifier was provided, and otherwise it's the base type. 2569 /// 2570 /// * Next we cast from the naming class to the declaring class. 2571 /// If the member we found was brought into a class's scope by 2572 /// a using declaration, this is that class; otherwise it's 2573 /// the class declaring the member. 2574 /// 2575 /// * Finally we cast from the declaring class to the "true" 2576 /// declaring class of the member. This conversion does not 2577 /// obey access control. 2578 ExprResult 2579 Sema::PerformObjectMemberConversion(Expr *From, 2580 NestedNameSpecifier *Qualifier, 2581 NamedDecl *FoundDecl, 2582 NamedDecl *Member) { 2583 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2584 if (!RD) 2585 return From; 2586 2587 QualType DestRecordType; 2588 QualType DestType; 2589 QualType FromRecordType; 2590 QualType FromType = From->getType(); 2591 bool PointerConversions = false; 2592 if (isa<FieldDecl>(Member)) { 2593 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2594 2595 if (FromType->getAs<PointerType>()) { 2596 DestType = Context.getPointerType(DestRecordType); 2597 FromRecordType = FromType->getPointeeType(); 2598 PointerConversions = true; 2599 } else { 2600 DestType = DestRecordType; 2601 FromRecordType = FromType; 2602 } 2603 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2604 if (Method->isStatic()) 2605 return From; 2606 2607 DestType = Method->getThisType(Context); 2608 DestRecordType = DestType->getPointeeType(); 2609 2610 if (FromType->getAs<PointerType>()) { 2611 FromRecordType = FromType->getPointeeType(); 2612 PointerConversions = true; 2613 } else { 2614 FromRecordType = FromType; 2615 DestType = DestRecordType; 2616 } 2617 } else { 2618 // No conversion necessary. 2619 return From; 2620 } 2621 2622 if (DestType->isDependentType() || FromType->isDependentType()) 2623 return From; 2624 2625 // If the unqualified types are the same, no conversion is necessary. 2626 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2627 return From; 2628 2629 SourceRange FromRange = From->getSourceRange(); 2630 SourceLocation FromLoc = FromRange.getBegin(); 2631 2632 ExprValueKind VK = From->getValueKind(); 2633 2634 // C++ [class.member.lookup]p8: 2635 // [...] Ambiguities can often be resolved by qualifying a name with its 2636 // class name. 2637 // 2638 // If the member was a qualified name and the qualified referred to a 2639 // specific base subobject type, we'll cast to that intermediate type 2640 // first and then to the object in which the member is declared. That allows 2641 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2642 // 2643 // class Base { public: int x; }; 2644 // class Derived1 : public Base { }; 2645 // class Derived2 : public Base { }; 2646 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2647 // 2648 // void VeryDerived::f() { 2649 // x = 17; // error: ambiguous base subobjects 2650 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2651 // } 2652 if (Qualifier && Qualifier->getAsType()) { 2653 QualType QType = QualType(Qualifier->getAsType(), 0); 2654 assert(QType->isRecordType() && "lookup done with non-record type"); 2655 2656 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2657 2658 // In C++98, the qualifier type doesn't actually have to be a base 2659 // type of the object type, in which case we just ignore it. 2660 // Otherwise build the appropriate casts. 2661 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2662 CXXCastPath BasePath; 2663 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2664 FromLoc, FromRange, &BasePath)) 2665 return ExprError(); 2666 2667 if (PointerConversions) 2668 QType = Context.getPointerType(QType); 2669 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2670 VK, &BasePath).get(); 2671 2672 FromType = QType; 2673 FromRecordType = QRecordType; 2674 2675 // If the qualifier type was the same as the destination type, 2676 // we're done. 2677 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2678 return From; 2679 } 2680 } 2681 2682 bool IgnoreAccess = false; 2683 2684 // If we actually found the member through a using declaration, cast 2685 // down to the using declaration's type. 2686 // 2687 // Pointer equality is fine here because only one declaration of a 2688 // class ever has member declarations. 2689 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2690 assert(isa<UsingShadowDecl>(FoundDecl)); 2691 QualType URecordType = Context.getTypeDeclType( 2692 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2693 2694 // We only need to do this if the naming-class to declaring-class 2695 // conversion is non-trivial. 2696 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2697 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2698 CXXCastPath BasePath; 2699 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2700 FromLoc, FromRange, &BasePath)) 2701 return ExprError(); 2702 2703 QualType UType = URecordType; 2704 if (PointerConversions) 2705 UType = Context.getPointerType(UType); 2706 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2707 VK, &BasePath).get(); 2708 FromType = UType; 2709 FromRecordType = URecordType; 2710 } 2711 2712 // We don't do access control for the conversion from the 2713 // declaring class to the true declaring class. 2714 IgnoreAccess = true; 2715 } 2716 2717 CXXCastPath BasePath; 2718 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2719 FromLoc, FromRange, &BasePath, 2720 IgnoreAccess)) 2721 return ExprError(); 2722 2723 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2724 VK, &BasePath); 2725 } 2726 2727 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2728 const LookupResult &R, 2729 bool HasTrailingLParen) { 2730 // Only when used directly as the postfix-expression of a call. 2731 if (!HasTrailingLParen) 2732 return false; 2733 2734 // Never if a scope specifier was provided. 2735 if (SS.isSet()) 2736 return false; 2737 2738 // Only in C++ or ObjC++. 2739 if (!getLangOpts().CPlusPlus) 2740 return false; 2741 2742 // Turn off ADL when we find certain kinds of declarations during 2743 // normal lookup: 2744 for (NamedDecl *D : R) { 2745 // C++0x [basic.lookup.argdep]p3: 2746 // -- a declaration of a class member 2747 // Since using decls preserve this property, we check this on the 2748 // original decl. 2749 if (D->isCXXClassMember()) 2750 return false; 2751 2752 // C++0x [basic.lookup.argdep]p3: 2753 // -- a block-scope function declaration that is not a 2754 // using-declaration 2755 // NOTE: we also trigger this for function templates (in fact, we 2756 // don't check the decl type at all, since all other decl types 2757 // turn off ADL anyway). 2758 if (isa<UsingShadowDecl>(D)) 2759 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2760 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2761 return false; 2762 2763 // C++0x [basic.lookup.argdep]p3: 2764 // -- a declaration that is neither a function or a function 2765 // template 2766 // And also for builtin functions. 2767 if (isa<FunctionDecl>(D)) { 2768 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2769 2770 // But also builtin functions. 2771 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2772 return false; 2773 } else if (!isa<FunctionTemplateDecl>(D)) 2774 return false; 2775 } 2776 2777 return true; 2778 } 2779 2780 2781 /// Diagnoses obvious problems with the use of the given declaration 2782 /// as an expression. This is only actually called for lookups that 2783 /// were not overloaded, and it doesn't promise that the declaration 2784 /// will in fact be used. 2785 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2786 if (isa<TypedefNameDecl>(D)) { 2787 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2788 return true; 2789 } 2790 2791 if (isa<ObjCInterfaceDecl>(D)) { 2792 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2793 return true; 2794 } 2795 2796 if (isa<NamespaceDecl>(D)) { 2797 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2798 return true; 2799 } 2800 2801 return false; 2802 } 2803 2804 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2805 LookupResult &R, bool NeedsADL, 2806 bool AcceptInvalidDecl) { 2807 // If this is a single, fully-resolved result and we don't need ADL, 2808 // just build an ordinary singleton decl ref. 2809 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2810 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2811 R.getRepresentativeDecl(), nullptr, 2812 AcceptInvalidDecl); 2813 2814 // We only need to check the declaration if there's exactly one 2815 // result, because in the overloaded case the results can only be 2816 // functions and function templates. 2817 if (R.isSingleResult() && 2818 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2819 return ExprError(); 2820 2821 // Otherwise, just build an unresolved lookup expression. Suppress 2822 // any lookup-related diagnostics; we'll hash these out later, when 2823 // we've picked a target. 2824 R.suppressDiagnostics(); 2825 2826 UnresolvedLookupExpr *ULE 2827 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2828 SS.getWithLocInContext(Context), 2829 R.getLookupNameInfo(), 2830 NeedsADL, R.isOverloadedResult(), 2831 R.begin(), R.end()); 2832 2833 return ULE; 2834 } 2835 2836 static void 2837 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2838 ValueDecl *var, DeclContext *DC); 2839 2840 /// \brief Complete semantic analysis for a reference to the given declaration. 2841 ExprResult Sema::BuildDeclarationNameExpr( 2842 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2843 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2844 bool AcceptInvalidDecl) { 2845 assert(D && "Cannot refer to a NULL declaration"); 2846 assert(!isa<FunctionTemplateDecl>(D) && 2847 "Cannot refer unambiguously to a function template"); 2848 2849 SourceLocation Loc = NameInfo.getLoc(); 2850 if (CheckDeclInExpr(*this, Loc, D)) 2851 return ExprError(); 2852 2853 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2854 // Specifically diagnose references to class templates that are missing 2855 // a template argument list. 2856 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2857 << Template << SS.getRange(); 2858 Diag(Template->getLocation(), diag::note_template_decl_here); 2859 return ExprError(); 2860 } 2861 2862 // Make sure that we're referring to a value. 2863 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2864 if (!VD) { 2865 Diag(Loc, diag::err_ref_non_value) 2866 << D << SS.getRange(); 2867 Diag(D->getLocation(), diag::note_declared_at); 2868 return ExprError(); 2869 } 2870 2871 // Check whether this declaration can be used. Note that we suppress 2872 // this check when we're going to perform argument-dependent lookup 2873 // on this function name, because this might not be the function 2874 // that overload resolution actually selects. 2875 if (DiagnoseUseOfDecl(VD, Loc)) 2876 return ExprError(); 2877 2878 // Only create DeclRefExpr's for valid Decl's. 2879 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2880 return ExprError(); 2881 2882 // Handle members of anonymous structs and unions. If we got here, 2883 // and the reference is to a class member indirect field, then this 2884 // must be the subject of a pointer-to-member expression. 2885 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2886 if (!indirectField->isCXXClassMember()) 2887 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2888 indirectField); 2889 2890 { 2891 QualType type = VD->getType(); 2892 ExprValueKind valueKind = VK_RValue; 2893 2894 switch (D->getKind()) { 2895 // Ignore all the non-ValueDecl kinds. 2896 #define ABSTRACT_DECL(kind) 2897 #define VALUE(type, base) 2898 #define DECL(type, base) \ 2899 case Decl::type: 2900 #include "clang/AST/DeclNodes.inc" 2901 llvm_unreachable("invalid value decl kind"); 2902 2903 // These shouldn't make it here. 2904 case Decl::ObjCAtDefsField: 2905 case Decl::ObjCIvar: 2906 llvm_unreachable("forming non-member reference to ivar?"); 2907 2908 // Enum constants are always r-values and never references. 2909 // Unresolved using declarations are dependent. 2910 case Decl::EnumConstant: 2911 case Decl::UnresolvedUsingValue: 2912 case Decl::OMPDeclareReduction: 2913 valueKind = VK_RValue; 2914 break; 2915 2916 // Fields and indirect fields that got here must be for 2917 // pointer-to-member expressions; we just call them l-values for 2918 // internal consistency, because this subexpression doesn't really 2919 // exist in the high-level semantics. 2920 case Decl::Field: 2921 case Decl::IndirectField: 2922 assert(getLangOpts().CPlusPlus && 2923 "building reference to field in C?"); 2924 2925 // These can't have reference type in well-formed programs, but 2926 // for internal consistency we do this anyway. 2927 type = type.getNonReferenceType(); 2928 valueKind = VK_LValue; 2929 break; 2930 2931 // Non-type template parameters are either l-values or r-values 2932 // depending on the type. 2933 case Decl::NonTypeTemplateParm: { 2934 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2935 type = reftype->getPointeeType(); 2936 valueKind = VK_LValue; // even if the parameter is an r-value reference 2937 break; 2938 } 2939 2940 // For non-references, we need to strip qualifiers just in case 2941 // the template parameter was declared as 'const int' or whatever. 2942 valueKind = VK_RValue; 2943 type = type.getUnqualifiedType(); 2944 break; 2945 } 2946 2947 case Decl::Var: 2948 case Decl::VarTemplateSpecialization: 2949 case Decl::VarTemplatePartialSpecialization: 2950 case Decl::Decomposition: 2951 case Decl::OMPCapturedExpr: 2952 // In C, "extern void blah;" is valid and is an r-value. 2953 if (!getLangOpts().CPlusPlus && 2954 !type.hasQualifiers() && 2955 type->isVoidType()) { 2956 valueKind = VK_RValue; 2957 break; 2958 } 2959 // fallthrough 2960 2961 case Decl::ImplicitParam: 2962 case Decl::ParmVar: { 2963 // These are always l-values. 2964 valueKind = VK_LValue; 2965 type = type.getNonReferenceType(); 2966 2967 // FIXME: Does the addition of const really only apply in 2968 // potentially-evaluated contexts? Since the variable isn't actually 2969 // captured in an unevaluated context, it seems that the answer is no. 2970 if (!isUnevaluatedContext()) { 2971 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2972 if (!CapturedType.isNull()) 2973 type = CapturedType; 2974 } 2975 2976 break; 2977 } 2978 2979 case Decl::Binding: { 2980 // These are always lvalues. 2981 valueKind = VK_LValue; 2982 type = type.getNonReferenceType(); 2983 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2984 // decides how that's supposed to work. 2985 auto *BD = cast<BindingDecl>(VD); 2986 if (BD->getDeclContext()->isFunctionOrMethod() && 2987 BD->getDeclContext() != CurContext) 2988 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2989 break; 2990 } 2991 2992 case Decl::Function: { 2993 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2994 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2995 type = Context.BuiltinFnTy; 2996 valueKind = VK_RValue; 2997 break; 2998 } 2999 } 3000 3001 const FunctionType *fty = type->castAs<FunctionType>(); 3002 3003 // If we're referring to a function with an __unknown_anytype 3004 // result type, make the entire expression __unknown_anytype. 3005 if (fty->getReturnType() == Context.UnknownAnyTy) { 3006 type = Context.UnknownAnyTy; 3007 valueKind = VK_RValue; 3008 break; 3009 } 3010 3011 // Functions are l-values in C++. 3012 if (getLangOpts().CPlusPlus) { 3013 valueKind = VK_LValue; 3014 break; 3015 } 3016 3017 // C99 DR 316 says that, if a function type comes from a 3018 // function definition (without a prototype), that type is only 3019 // used for checking compatibility. Therefore, when referencing 3020 // the function, we pretend that we don't have the full function 3021 // type. 3022 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3023 isa<FunctionProtoType>(fty)) 3024 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3025 fty->getExtInfo()); 3026 3027 // Functions are r-values in C. 3028 valueKind = VK_RValue; 3029 break; 3030 } 3031 3032 case Decl::MSProperty: 3033 valueKind = VK_LValue; 3034 break; 3035 3036 case Decl::CXXMethod: 3037 // If we're referring to a method with an __unknown_anytype 3038 // result type, make the entire expression __unknown_anytype. 3039 // This should only be possible with a type written directly. 3040 if (const FunctionProtoType *proto 3041 = dyn_cast<FunctionProtoType>(VD->getType())) 3042 if (proto->getReturnType() == Context.UnknownAnyTy) { 3043 type = Context.UnknownAnyTy; 3044 valueKind = VK_RValue; 3045 break; 3046 } 3047 3048 // C++ methods are l-values if static, r-values if non-static. 3049 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3050 valueKind = VK_LValue; 3051 break; 3052 } 3053 // fallthrough 3054 3055 case Decl::CXXConversion: 3056 case Decl::CXXDestructor: 3057 case Decl::CXXConstructor: 3058 valueKind = VK_RValue; 3059 break; 3060 } 3061 3062 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3063 TemplateArgs); 3064 } 3065 } 3066 3067 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3068 SmallString<32> &Target) { 3069 Target.resize(CharByteWidth * (Source.size() + 1)); 3070 char *ResultPtr = &Target[0]; 3071 const llvm::UTF8 *ErrorPtr; 3072 bool success = 3073 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3074 (void)success; 3075 assert(success); 3076 Target.resize(ResultPtr - &Target[0]); 3077 } 3078 3079 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3080 PredefinedExpr::IdentType IT) { 3081 // Pick the current block, lambda, captured statement or function. 3082 Decl *currentDecl = nullptr; 3083 if (const BlockScopeInfo *BSI = getCurBlock()) 3084 currentDecl = BSI->TheDecl; 3085 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3086 currentDecl = LSI->CallOperator; 3087 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3088 currentDecl = CSI->TheCapturedDecl; 3089 else 3090 currentDecl = getCurFunctionOrMethodDecl(); 3091 3092 if (!currentDecl) { 3093 Diag(Loc, diag::ext_predef_outside_function); 3094 currentDecl = Context.getTranslationUnitDecl(); 3095 } 3096 3097 QualType ResTy; 3098 StringLiteral *SL = nullptr; 3099 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3100 ResTy = Context.DependentTy; 3101 else { 3102 // Pre-defined identifiers are of type char[x], where x is the length of 3103 // the string. 3104 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3105 unsigned Length = Str.length(); 3106 3107 llvm::APInt LengthI(32, Length + 1); 3108 if (IT == PredefinedExpr::LFunction) { 3109 ResTy = Context.WideCharTy.withConst(); 3110 SmallString<32> RawChars; 3111 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3112 Str, RawChars); 3113 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3114 /*IndexTypeQuals*/ 0); 3115 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3116 /*Pascal*/ false, ResTy, Loc); 3117 } else { 3118 ResTy = Context.CharTy.withConst(); 3119 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3120 /*IndexTypeQuals*/ 0); 3121 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3122 /*Pascal*/ false, ResTy, Loc); 3123 } 3124 } 3125 3126 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3127 } 3128 3129 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3130 PredefinedExpr::IdentType IT; 3131 3132 switch (Kind) { 3133 default: llvm_unreachable("Unknown simple primary expr!"); 3134 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3135 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3136 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3137 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3138 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3139 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3140 } 3141 3142 return BuildPredefinedExpr(Loc, IT); 3143 } 3144 3145 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3146 SmallString<16> CharBuffer; 3147 bool Invalid = false; 3148 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3149 if (Invalid) 3150 return ExprError(); 3151 3152 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3153 PP, Tok.getKind()); 3154 if (Literal.hadError()) 3155 return ExprError(); 3156 3157 QualType Ty; 3158 if (Literal.isWide()) 3159 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3160 else if (Literal.isUTF16()) 3161 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3162 else if (Literal.isUTF32()) 3163 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3164 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3165 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3166 else 3167 Ty = Context.CharTy; // 'x' -> char in C++ 3168 3169 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3170 if (Literal.isWide()) 3171 Kind = CharacterLiteral::Wide; 3172 else if (Literal.isUTF16()) 3173 Kind = CharacterLiteral::UTF16; 3174 else if (Literal.isUTF32()) 3175 Kind = CharacterLiteral::UTF32; 3176 else if (Literal.isUTF8()) 3177 Kind = CharacterLiteral::UTF8; 3178 3179 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3180 Tok.getLocation()); 3181 3182 if (Literal.getUDSuffix().empty()) 3183 return Lit; 3184 3185 // We're building a user-defined literal. 3186 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3187 SourceLocation UDSuffixLoc = 3188 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3189 3190 // Make sure we're allowed user-defined literals here. 3191 if (!UDLScope) 3192 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3193 3194 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3195 // operator "" X (ch) 3196 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3197 Lit, Tok.getLocation()); 3198 } 3199 3200 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3201 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3202 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3203 Context.IntTy, Loc); 3204 } 3205 3206 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3207 QualType Ty, SourceLocation Loc) { 3208 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3209 3210 using llvm::APFloat; 3211 APFloat Val(Format); 3212 3213 APFloat::opStatus result = Literal.GetFloatValue(Val); 3214 3215 // Overflow is always an error, but underflow is only an error if 3216 // we underflowed to zero (APFloat reports denormals as underflow). 3217 if ((result & APFloat::opOverflow) || 3218 ((result & APFloat::opUnderflow) && Val.isZero())) { 3219 unsigned diagnostic; 3220 SmallString<20> buffer; 3221 if (result & APFloat::opOverflow) { 3222 diagnostic = diag::warn_float_overflow; 3223 APFloat::getLargest(Format).toString(buffer); 3224 } else { 3225 diagnostic = diag::warn_float_underflow; 3226 APFloat::getSmallest(Format).toString(buffer); 3227 } 3228 3229 S.Diag(Loc, diagnostic) 3230 << Ty 3231 << StringRef(buffer.data(), buffer.size()); 3232 } 3233 3234 bool isExact = (result == APFloat::opOK); 3235 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3236 } 3237 3238 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3239 assert(E && "Invalid expression"); 3240 3241 if (E->isValueDependent()) 3242 return false; 3243 3244 QualType QT = E->getType(); 3245 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3246 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3247 return true; 3248 } 3249 3250 llvm::APSInt ValueAPS; 3251 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3252 3253 if (R.isInvalid()) 3254 return true; 3255 3256 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3257 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3258 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3259 << ValueAPS.toString(10) << ValueIsPositive; 3260 return true; 3261 } 3262 3263 return false; 3264 } 3265 3266 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3267 // Fast path for a single digit (which is quite common). A single digit 3268 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3269 if (Tok.getLength() == 1) { 3270 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3271 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3272 } 3273 3274 SmallString<128> SpellingBuffer; 3275 // NumericLiteralParser wants to overread by one character. Add padding to 3276 // the buffer in case the token is copied to the buffer. If getSpelling() 3277 // returns a StringRef to the memory buffer, it should have a null char at 3278 // the EOF, so it is also safe. 3279 SpellingBuffer.resize(Tok.getLength() + 1); 3280 3281 // Get the spelling of the token, which eliminates trigraphs, etc. 3282 bool Invalid = false; 3283 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3284 if (Invalid) 3285 return ExprError(); 3286 3287 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3288 if (Literal.hadError) 3289 return ExprError(); 3290 3291 if (Literal.hasUDSuffix()) { 3292 // We're building a user-defined literal. 3293 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3294 SourceLocation UDSuffixLoc = 3295 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3296 3297 // Make sure we're allowed user-defined literals here. 3298 if (!UDLScope) 3299 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3300 3301 QualType CookedTy; 3302 if (Literal.isFloatingLiteral()) { 3303 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3304 // long double, the literal is treated as a call of the form 3305 // operator "" X (f L) 3306 CookedTy = Context.LongDoubleTy; 3307 } else { 3308 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3309 // unsigned long long, the literal is treated as a call of the form 3310 // operator "" X (n ULL) 3311 CookedTy = Context.UnsignedLongLongTy; 3312 } 3313 3314 DeclarationName OpName = 3315 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3316 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3317 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3318 3319 SourceLocation TokLoc = Tok.getLocation(); 3320 3321 // Perform literal operator lookup to determine if we're building a raw 3322 // literal or a cooked one. 3323 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3324 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3325 /*AllowRaw*/true, /*AllowTemplate*/true, 3326 /*AllowStringTemplate*/false)) { 3327 case LOLR_Error: 3328 return ExprError(); 3329 3330 case LOLR_Cooked: { 3331 Expr *Lit; 3332 if (Literal.isFloatingLiteral()) { 3333 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3334 } else { 3335 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3336 if (Literal.GetIntegerValue(ResultVal)) 3337 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3338 << /* Unsigned */ 1; 3339 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3340 Tok.getLocation()); 3341 } 3342 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3343 } 3344 3345 case LOLR_Raw: { 3346 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3347 // literal is treated as a call of the form 3348 // operator "" X ("n") 3349 unsigned Length = Literal.getUDSuffixOffset(); 3350 QualType StrTy = Context.getConstantArrayType( 3351 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3352 ArrayType::Normal, 0); 3353 Expr *Lit = StringLiteral::Create( 3354 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3355 /*Pascal*/false, StrTy, &TokLoc, 1); 3356 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3357 } 3358 3359 case LOLR_Template: { 3360 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3361 // template), L is treated as a call fo the form 3362 // operator "" X <'c1', 'c2', ... 'ck'>() 3363 // where n is the source character sequence c1 c2 ... ck. 3364 TemplateArgumentListInfo ExplicitArgs; 3365 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3366 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3367 llvm::APSInt Value(CharBits, CharIsUnsigned); 3368 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3369 Value = TokSpelling[I]; 3370 TemplateArgument Arg(Context, Value, Context.CharTy); 3371 TemplateArgumentLocInfo ArgInfo; 3372 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3373 } 3374 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3375 &ExplicitArgs); 3376 } 3377 case LOLR_StringTemplate: 3378 llvm_unreachable("unexpected literal operator lookup result"); 3379 } 3380 } 3381 3382 Expr *Res; 3383 3384 if (Literal.isFloatingLiteral()) { 3385 QualType Ty; 3386 if (Literal.isHalf){ 3387 if (getOpenCLOptions().cl_khr_fp16) 3388 Ty = Context.HalfTy; 3389 else { 3390 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3391 return ExprError(); 3392 } 3393 } else if (Literal.isFloat) 3394 Ty = Context.FloatTy; 3395 else if (Literal.isLong) 3396 Ty = Context.LongDoubleTy; 3397 else if (Literal.isFloat128) 3398 Ty = Context.Float128Ty; 3399 else 3400 Ty = Context.DoubleTy; 3401 3402 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3403 3404 if (Ty == Context.DoubleTy) { 3405 if (getLangOpts().SinglePrecisionConstants) { 3406 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3407 } else if (getLangOpts().OpenCL && 3408 !((getLangOpts().OpenCLVersion >= 120) || 3409 getOpenCLOptions().cl_khr_fp64)) { 3410 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3411 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3412 } 3413 } 3414 } else if (!Literal.isIntegerLiteral()) { 3415 return ExprError(); 3416 } else { 3417 QualType Ty; 3418 3419 // 'long long' is a C99 or C++11 feature. 3420 if (!getLangOpts().C99 && Literal.isLongLong) { 3421 if (getLangOpts().CPlusPlus) 3422 Diag(Tok.getLocation(), 3423 getLangOpts().CPlusPlus11 ? 3424 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3425 else 3426 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3427 } 3428 3429 // Get the value in the widest-possible width. 3430 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3431 llvm::APInt ResultVal(MaxWidth, 0); 3432 3433 if (Literal.GetIntegerValue(ResultVal)) { 3434 // If this value didn't fit into uintmax_t, error and force to ull. 3435 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3436 << /* Unsigned */ 1; 3437 Ty = Context.UnsignedLongLongTy; 3438 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3439 "long long is not intmax_t?"); 3440 } else { 3441 // If this value fits into a ULL, try to figure out what else it fits into 3442 // according to the rules of C99 6.4.4.1p5. 3443 3444 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3445 // be an unsigned int. 3446 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3447 3448 // Check from smallest to largest, picking the smallest type we can. 3449 unsigned Width = 0; 3450 3451 // Microsoft specific integer suffixes are explicitly sized. 3452 if (Literal.MicrosoftInteger) { 3453 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3454 Width = 8; 3455 Ty = Context.CharTy; 3456 } else { 3457 Width = Literal.MicrosoftInteger; 3458 Ty = Context.getIntTypeForBitwidth(Width, 3459 /*Signed=*/!Literal.isUnsigned); 3460 } 3461 } 3462 3463 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3464 // Are int/unsigned possibilities? 3465 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3466 3467 // Does it fit in a unsigned int? 3468 if (ResultVal.isIntN(IntSize)) { 3469 // Does it fit in a signed int? 3470 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3471 Ty = Context.IntTy; 3472 else if (AllowUnsigned) 3473 Ty = Context.UnsignedIntTy; 3474 Width = IntSize; 3475 } 3476 } 3477 3478 // Are long/unsigned long possibilities? 3479 if (Ty.isNull() && !Literal.isLongLong) { 3480 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3481 3482 // Does it fit in a unsigned long? 3483 if (ResultVal.isIntN(LongSize)) { 3484 // Does it fit in a signed long? 3485 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3486 Ty = Context.LongTy; 3487 else if (AllowUnsigned) 3488 Ty = Context.UnsignedLongTy; 3489 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3490 // is compatible. 3491 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3492 const unsigned LongLongSize = 3493 Context.getTargetInfo().getLongLongWidth(); 3494 Diag(Tok.getLocation(), 3495 getLangOpts().CPlusPlus 3496 ? Literal.isLong 3497 ? diag::warn_old_implicitly_unsigned_long_cxx 3498 : /*C++98 UB*/ diag:: 3499 ext_old_implicitly_unsigned_long_cxx 3500 : diag::warn_old_implicitly_unsigned_long) 3501 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3502 : /*will be ill-formed*/ 1); 3503 Ty = Context.UnsignedLongTy; 3504 } 3505 Width = LongSize; 3506 } 3507 } 3508 3509 // Check long long if needed. 3510 if (Ty.isNull()) { 3511 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3512 3513 // Does it fit in a unsigned long long? 3514 if (ResultVal.isIntN(LongLongSize)) { 3515 // Does it fit in a signed long long? 3516 // To be compatible with MSVC, hex integer literals ending with the 3517 // LL or i64 suffix are always signed in Microsoft mode. 3518 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3519 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3520 Ty = Context.LongLongTy; 3521 else if (AllowUnsigned) 3522 Ty = Context.UnsignedLongLongTy; 3523 Width = LongLongSize; 3524 } 3525 } 3526 3527 // If we still couldn't decide a type, we probably have something that 3528 // does not fit in a signed long long, but has no U suffix. 3529 if (Ty.isNull()) { 3530 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3531 Ty = Context.UnsignedLongLongTy; 3532 Width = Context.getTargetInfo().getLongLongWidth(); 3533 } 3534 3535 if (ResultVal.getBitWidth() != Width) 3536 ResultVal = ResultVal.trunc(Width); 3537 } 3538 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3539 } 3540 3541 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3542 if (Literal.isImaginary) 3543 Res = new (Context) ImaginaryLiteral(Res, 3544 Context.getComplexType(Res->getType())); 3545 3546 return Res; 3547 } 3548 3549 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3550 assert(E && "ActOnParenExpr() missing expr"); 3551 return new (Context) ParenExpr(L, R, E); 3552 } 3553 3554 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3555 SourceLocation Loc, 3556 SourceRange ArgRange) { 3557 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3558 // scalar or vector data type argument..." 3559 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3560 // type (C99 6.2.5p18) or void. 3561 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3562 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3563 << T << ArgRange; 3564 return true; 3565 } 3566 3567 assert((T->isVoidType() || !T->isIncompleteType()) && 3568 "Scalar types should always be complete"); 3569 return false; 3570 } 3571 3572 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3573 SourceLocation Loc, 3574 SourceRange ArgRange, 3575 UnaryExprOrTypeTrait TraitKind) { 3576 // Invalid types must be hard errors for SFINAE in C++. 3577 if (S.LangOpts.CPlusPlus) 3578 return true; 3579 3580 // C99 6.5.3.4p1: 3581 if (T->isFunctionType() && 3582 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3583 // sizeof(function)/alignof(function) is allowed as an extension. 3584 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3585 << TraitKind << ArgRange; 3586 return false; 3587 } 3588 3589 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3590 // this is an error (OpenCL v1.1 s6.3.k) 3591 if (T->isVoidType()) { 3592 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3593 : diag::ext_sizeof_alignof_void_type; 3594 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3595 return false; 3596 } 3597 3598 return true; 3599 } 3600 3601 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3602 SourceLocation Loc, 3603 SourceRange ArgRange, 3604 UnaryExprOrTypeTrait TraitKind) { 3605 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3606 // runtime doesn't allow it. 3607 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3608 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3609 << T << (TraitKind == UETT_SizeOf) 3610 << ArgRange; 3611 return true; 3612 } 3613 3614 return false; 3615 } 3616 3617 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3618 /// pointer type is equal to T) and emit a warning if it is. 3619 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3620 Expr *E) { 3621 // Don't warn if the operation changed the type. 3622 if (T != E->getType()) 3623 return; 3624 3625 // Now look for array decays. 3626 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3627 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3628 return; 3629 3630 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3631 << ICE->getType() 3632 << ICE->getSubExpr()->getType(); 3633 } 3634 3635 /// \brief Check the constraints on expression operands to unary type expression 3636 /// and type traits. 3637 /// 3638 /// Completes any types necessary and validates the constraints on the operand 3639 /// expression. The logic mostly mirrors the type-based overload, but may modify 3640 /// the expression as it completes the type for that expression through template 3641 /// instantiation, etc. 3642 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3643 UnaryExprOrTypeTrait ExprKind) { 3644 QualType ExprTy = E->getType(); 3645 assert(!ExprTy->isReferenceType()); 3646 3647 if (ExprKind == UETT_VecStep) 3648 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3649 E->getSourceRange()); 3650 3651 // Whitelist some types as extensions 3652 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3653 E->getSourceRange(), ExprKind)) 3654 return false; 3655 3656 // 'alignof' applied to an expression only requires the base element type of 3657 // the expression to be complete. 'sizeof' requires the expression's type to 3658 // be complete (and will attempt to complete it if it's an array of unknown 3659 // bound). 3660 if (ExprKind == UETT_AlignOf) { 3661 if (RequireCompleteType(E->getExprLoc(), 3662 Context.getBaseElementType(E->getType()), 3663 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3664 E->getSourceRange())) 3665 return true; 3666 } else { 3667 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3668 ExprKind, E->getSourceRange())) 3669 return true; 3670 } 3671 3672 // Completing the expression's type may have changed it. 3673 ExprTy = E->getType(); 3674 assert(!ExprTy->isReferenceType()); 3675 3676 if (ExprTy->isFunctionType()) { 3677 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3678 << ExprKind << E->getSourceRange(); 3679 return true; 3680 } 3681 3682 // The operand for sizeof and alignof is in an unevaluated expression context, 3683 // so side effects could result in unintended consequences. 3684 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3685 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3686 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3687 3688 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3689 E->getSourceRange(), ExprKind)) 3690 return true; 3691 3692 if (ExprKind == UETT_SizeOf) { 3693 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3694 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3695 QualType OType = PVD->getOriginalType(); 3696 QualType Type = PVD->getType(); 3697 if (Type->isPointerType() && OType->isArrayType()) { 3698 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3699 << Type << OType; 3700 Diag(PVD->getLocation(), diag::note_declared_at); 3701 } 3702 } 3703 } 3704 3705 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3706 // decays into a pointer and returns an unintended result. This is most 3707 // likely a typo for "sizeof(array) op x". 3708 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3709 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3710 BO->getLHS()); 3711 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3712 BO->getRHS()); 3713 } 3714 } 3715 3716 return false; 3717 } 3718 3719 /// \brief Check the constraints on operands to unary expression and type 3720 /// traits. 3721 /// 3722 /// This will complete any types necessary, and validate the various constraints 3723 /// on those operands. 3724 /// 3725 /// The UsualUnaryConversions() function is *not* called by this routine. 3726 /// C99 6.3.2.1p[2-4] all state: 3727 /// Except when it is the operand of the sizeof operator ... 3728 /// 3729 /// C++ [expr.sizeof]p4 3730 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3731 /// standard conversions are not applied to the operand of sizeof. 3732 /// 3733 /// This policy is followed for all of the unary trait expressions. 3734 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3735 SourceLocation OpLoc, 3736 SourceRange ExprRange, 3737 UnaryExprOrTypeTrait ExprKind) { 3738 if (ExprType->isDependentType()) 3739 return false; 3740 3741 // C++ [expr.sizeof]p2: 3742 // When applied to a reference or a reference type, the result 3743 // is the size of the referenced type. 3744 // C++11 [expr.alignof]p3: 3745 // When alignof is applied to a reference type, the result 3746 // shall be the alignment of the referenced type. 3747 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3748 ExprType = Ref->getPointeeType(); 3749 3750 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3751 // When alignof or _Alignof is applied to an array type, the result 3752 // is the alignment of the element type. 3753 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3754 ExprType = Context.getBaseElementType(ExprType); 3755 3756 if (ExprKind == UETT_VecStep) 3757 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3758 3759 // Whitelist some types as extensions 3760 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3761 ExprKind)) 3762 return false; 3763 3764 if (RequireCompleteType(OpLoc, ExprType, 3765 diag::err_sizeof_alignof_incomplete_type, 3766 ExprKind, ExprRange)) 3767 return true; 3768 3769 if (ExprType->isFunctionType()) { 3770 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3771 << ExprKind << ExprRange; 3772 return true; 3773 } 3774 3775 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3776 ExprKind)) 3777 return true; 3778 3779 return false; 3780 } 3781 3782 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3783 E = E->IgnoreParens(); 3784 3785 // Cannot know anything else if the expression is dependent. 3786 if (E->isTypeDependent()) 3787 return false; 3788 3789 if (E->getObjectKind() == OK_BitField) { 3790 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3791 << 1 << E->getSourceRange(); 3792 return true; 3793 } 3794 3795 ValueDecl *D = nullptr; 3796 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3797 D = DRE->getDecl(); 3798 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3799 D = ME->getMemberDecl(); 3800 } 3801 3802 // If it's a field, require the containing struct to have a 3803 // complete definition so that we can compute the layout. 3804 // 3805 // This can happen in C++11 onwards, either by naming the member 3806 // in a way that is not transformed into a member access expression 3807 // (in an unevaluated operand, for instance), or by naming the member 3808 // in a trailing-return-type. 3809 // 3810 // For the record, since __alignof__ on expressions is a GCC 3811 // extension, GCC seems to permit this but always gives the 3812 // nonsensical answer 0. 3813 // 3814 // We don't really need the layout here --- we could instead just 3815 // directly check for all the appropriate alignment-lowing 3816 // attributes --- but that would require duplicating a lot of 3817 // logic that just isn't worth duplicating for such a marginal 3818 // use-case. 3819 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3820 // Fast path this check, since we at least know the record has a 3821 // definition if we can find a member of it. 3822 if (!FD->getParent()->isCompleteDefinition()) { 3823 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3824 << E->getSourceRange(); 3825 return true; 3826 } 3827 3828 // Otherwise, if it's a field, and the field doesn't have 3829 // reference type, then it must have a complete type (or be a 3830 // flexible array member, which we explicitly want to 3831 // white-list anyway), which makes the following checks trivial. 3832 if (!FD->getType()->isReferenceType()) 3833 return false; 3834 } 3835 3836 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3837 } 3838 3839 bool Sema::CheckVecStepExpr(Expr *E) { 3840 E = E->IgnoreParens(); 3841 3842 // Cannot know anything else if the expression is dependent. 3843 if (E->isTypeDependent()) 3844 return false; 3845 3846 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3847 } 3848 3849 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3850 CapturingScopeInfo *CSI) { 3851 assert(T->isVariablyModifiedType()); 3852 assert(CSI != nullptr); 3853 3854 // We're going to walk down into the type and look for VLA expressions. 3855 do { 3856 const Type *Ty = T.getTypePtr(); 3857 switch (Ty->getTypeClass()) { 3858 #define TYPE(Class, Base) 3859 #define ABSTRACT_TYPE(Class, Base) 3860 #define NON_CANONICAL_TYPE(Class, Base) 3861 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3862 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3863 #include "clang/AST/TypeNodes.def" 3864 T = QualType(); 3865 break; 3866 // These types are never variably-modified. 3867 case Type::Builtin: 3868 case Type::Complex: 3869 case Type::Vector: 3870 case Type::ExtVector: 3871 case Type::Record: 3872 case Type::Enum: 3873 case Type::Elaborated: 3874 case Type::TemplateSpecialization: 3875 case Type::ObjCObject: 3876 case Type::ObjCInterface: 3877 case Type::ObjCObjectPointer: 3878 case Type::ObjCTypeParam: 3879 case Type::Pipe: 3880 llvm_unreachable("type class is never variably-modified!"); 3881 case Type::Adjusted: 3882 T = cast<AdjustedType>(Ty)->getOriginalType(); 3883 break; 3884 case Type::Decayed: 3885 T = cast<DecayedType>(Ty)->getPointeeType(); 3886 break; 3887 case Type::Pointer: 3888 T = cast<PointerType>(Ty)->getPointeeType(); 3889 break; 3890 case Type::BlockPointer: 3891 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3892 break; 3893 case Type::LValueReference: 3894 case Type::RValueReference: 3895 T = cast<ReferenceType>(Ty)->getPointeeType(); 3896 break; 3897 case Type::MemberPointer: 3898 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3899 break; 3900 case Type::ConstantArray: 3901 case Type::IncompleteArray: 3902 // Losing element qualification here is fine. 3903 T = cast<ArrayType>(Ty)->getElementType(); 3904 break; 3905 case Type::VariableArray: { 3906 // Losing element qualification here is fine. 3907 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3908 3909 // Unknown size indication requires no size computation. 3910 // Otherwise, evaluate and record it. 3911 if (auto Size = VAT->getSizeExpr()) { 3912 if (!CSI->isVLATypeCaptured(VAT)) { 3913 RecordDecl *CapRecord = nullptr; 3914 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3915 CapRecord = LSI->Lambda; 3916 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3917 CapRecord = CRSI->TheRecordDecl; 3918 } 3919 if (CapRecord) { 3920 auto ExprLoc = Size->getExprLoc(); 3921 auto SizeType = Context.getSizeType(); 3922 // Build the non-static data member. 3923 auto Field = 3924 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3925 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3926 /*BW*/ nullptr, /*Mutable*/ false, 3927 /*InitStyle*/ ICIS_NoInit); 3928 Field->setImplicit(true); 3929 Field->setAccess(AS_private); 3930 Field->setCapturedVLAType(VAT); 3931 CapRecord->addDecl(Field); 3932 3933 CSI->addVLATypeCapture(ExprLoc, SizeType); 3934 } 3935 } 3936 } 3937 T = VAT->getElementType(); 3938 break; 3939 } 3940 case Type::FunctionProto: 3941 case Type::FunctionNoProto: 3942 T = cast<FunctionType>(Ty)->getReturnType(); 3943 break; 3944 case Type::Paren: 3945 case Type::TypeOf: 3946 case Type::UnaryTransform: 3947 case Type::Attributed: 3948 case Type::SubstTemplateTypeParm: 3949 case Type::PackExpansion: 3950 // Keep walking after single level desugaring. 3951 T = T.getSingleStepDesugaredType(Context); 3952 break; 3953 case Type::Typedef: 3954 T = cast<TypedefType>(Ty)->desugar(); 3955 break; 3956 case Type::Decltype: 3957 T = cast<DecltypeType>(Ty)->desugar(); 3958 break; 3959 case Type::Auto: 3960 T = cast<AutoType>(Ty)->getDeducedType(); 3961 break; 3962 case Type::TypeOfExpr: 3963 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3964 break; 3965 case Type::Atomic: 3966 T = cast<AtomicType>(Ty)->getValueType(); 3967 break; 3968 } 3969 } while (!T.isNull() && T->isVariablyModifiedType()); 3970 } 3971 3972 /// \brief Build a sizeof or alignof expression given a type operand. 3973 ExprResult 3974 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3975 SourceLocation OpLoc, 3976 UnaryExprOrTypeTrait ExprKind, 3977 SourceRange R) { 3978 if (!TInfo) 3979 return ExprError(); 3980 3981 QualType T = TInfo->getType(); 3982 3983 if (!T->isDependentType() && 3984 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3985 return ExprError(); 3986 3987 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3988 if (auto *TT = T->getAs<TypedefType>()) { 3989 for (auto I = FunctionScopes.rbegin(), 3990 E = std::prev(FunctionScopes.rend()); 3991 I != E; ++I) { 3992 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3993 if (CSI == nullptr) 3994 break; 3995 DeclContext *DC = nullptr; 3996 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3997 DC = LSI->CallOperator; 3998 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3999 DC = CRSI->TheCapturedDecl; 4000 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4001 DC = BSI->TheDecl; 4002 if (DC) { 4003 if (DC->containsDecl(TT->getDecl())) 4004 break; 4005 captureVariablyModifiedType(Context, T, CSI); 4006 } 4007 } 4008 } 4009 } 4010 4011 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4012 return new (Context) UnaryExprOrTypeTraitExpr( 4013 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4014 } 4015 4016 /// \brief Build a sizeof or alignof expression given an expression 4017 /// operand. 4018 ExprResult 4019 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4020 UnaryExprOrTypeTrait ExprKind) { 4021 ExprResult PE = CheckPlaceholderExpr(E); 4022 if (PE.isInvalid()) 4023 return ExprError(); 4024 4025 E = PE.get(); 4026 4027 // Verify that the operand is valid. 4028 bool isInvalid = false; 4029 if (E->isTypeDependent()) { 4030 // Delay type-checking for type-dependent expressions. 4031 } else if (ExprKind == UETT_AlignOf) { 4032 isInvalid = CheckAlignOfExpr(*this, E); 4033 } else if (ExprKind == UETT_VecStep) { 4034 isInvalid = CheckVecStepExpr(E); 4035 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4036 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4037 isInvalid = true; 4038 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4039 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4040 isInvalid = true; 4041 } else { 4042 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4043 } 4044 4045 if (isInvalid) 4046 return ExprError(); 4047 4048 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4049 PE = TransformToPotentiallyEvaluated(E); 4050 if (PE.isInvalid()) return ExprError(); 4051 E = PE.get(); 4052 } 4053 4054 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4055 return new (Context) UnaryExprOrTypeTraitExpr( 4056 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4057 } 4058 4059 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4060 /// expr and the same for @c alignof and @c __alignof 4061 /// Note that the ArgRange is invalid if isType is false. 4062 ExprResult 4063 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4064 UnaryExprOrTypeTrait ExprKind, bool IsType, 4065 void *TyOrEx, SourceRange ArgRange) { 4066 // If error parsing type, ignore. 4067 if (!TyOrEx) return ExprError(); 4068 4069 if (IsType) { 4070 TypeSourceInfo *TInfo; 4071 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4072 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4073 } 4074 4075 Expr *ArgEx = (Expr *)TyOrEx; 4076 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4077 return Result; 4078 } 4079 4080 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4081 bool IsReal) { 4082 if (V.get()->isTypeDependent()) 4083 return S.Context.DependentTy; 4084 4085 // _Real and _Imag are only l-values for normal l-values. 4086 if (V.get()->getObjectKind() != OK_Ordinary) { 4087 V = S.DefaultLvalueConversion(V.get()); 4088 if (V.isInvalid()) 4089 return QualType(); 4090 } 4091 4092 // These operators return the element type of a complex type. 4093 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4094 return CT->getElementType(); 4095 4096 // Otherwise they pass through real integer and floating point types here. 4097 if (V.get()->getType()->isArithmeticType()) 4098 return V.get()->getType(); 4099 4100 // Test for placeholders. 4101 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4102 if (PR.isInvalid()) return QualType(); 4103 if (PR.get() != V.get()) { 4104 V = PR; 4105 return CheckRealImagOperand(S, V, Loc, IsReal); 4106 } 4107 4108 // Reject anything else. 4109 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4110 << (IsReal ? "__real" : "__imag"); 4111 return QualType(); 4112 } 4113 4114 4115 4116 ExprResult 4117 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4118 tok::TokenKind Kind, Expr *Input) { 4119 UnaryOperatorKind Opc; 4120 switch (Kind) { 4121 default: llvm_unreachable("Unknown unary op!"); 4122 case tok::plusplus: Opc = UO_PostInc; break; 4123 case tok::minusminus: Opc = UO_PostDec; break; 4124 } 4125 4126 // Since this might is a postfix expression, get rid of ParenListExprs. 4127 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4128 if (Result.isInvalid()) return ExprError(); 4129 Input = Result.get(); 4130 4131 return BuildUnaryOp(S, OpLoc, Opc, Input); 4132 } 4133 4134 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4135 /// 4136 /// \return true on error 4137 static bool checkArithmeticOnObjCPointer(Sema &S, 4138 SourceLocation opLoc, 4139 Expr *op) { 4140 assert(op->getType()->isObjCObjectPointerType()); 4141 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4142 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4143 return false; 4144 4145 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4146 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4147 << op->getSourceRange(); 4148 return true; 4149 } 4150 4151 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4152 auto *BaseNoParens = Base->IgnoreParens(); 4153 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4154 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4155 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4156 } 4157 4158 ExprResult 4159 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4160 Expr *idx, SourceLocation rbLoc) { 4161 if (base && !base->getType().isNull() && 4162 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4163 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4164 /*Length=*/nullptr, rbLoc); 4165 4166 // Since this might be a postfix expression, get rid of ParenListExprs. 4167 if (isa<ParenListExpr>(base)) { 4168 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4169 if (result.isInvalid()) return ExprError(); 4170 base = result.get(); 4171 } 4172 4173 // Handle any non-overload placeholder types in the base and index 4174 // expressions. We can't handle overloads here because the other 4175 // operand might be an overloadable type, in which case the overload 4176 // resolution for the operator overload should get the first crack 4177 // at the overload. 4178 bool IsMSPropertySubscript = false; 4179 if (base->getType()->isNonOverloadPlaceholderType()) { 4180 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4181 if (!IsMSPropertySubscript) { 4182 ExprResult result = CheckPlaceholderExpr(base); 4183 if (result.isInvalid()) 4184 return ExprError(); 4185 base = result.get(); 4186 } 4187 } 4188 if (idx->getType()->isNonOverloadPlaceholderType()) { 4189 ExprResult result = CheckPlaceholderExpr(idx); 4190 if (result.isInvalid()) return ExprError(); 4191 idx = result.get(); 4192 } 4193 4194 // Build an unanalyzed expression if either operand is type-dependent. 4195 if (getLangOpts().CPlusPlus && 4196 (base->isTypeDependent() || idx->isTypeDependent())) { 4197 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4198 VK_LValue, OK_Ordinary, rbLoc); 4199 } 4200 4201 // MSDN, property (C++) 4202 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4203 // This attribute can also be used in the declaration of an empty array in a 4204 // class or structure definition. For example: 4205 // __declspec(property(get=GetX, put=PutX)) int x[]; 4206 // The above statement indicates that x[] can be used with one or more array 4207 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4208 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4209 if (IsMSPropertySubscript) { 4210 // Build MS property subscript expression if base is MS property reference 4211 // or MS property subscript. 4212 return new (Context) MSPropertySubscriptExpr( 4213 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4214 } 4215 4216 // Use C++ overloaded-operator rules if either operand has record 4217 // type. The spec says to do this if either type is *overloadable*, 4218 // but enum types can't declare subscript operators or conversion 4219 // operators, so there's nothing interesting for overload resolution 4220 // to do if there aren't any record types involved. 4221 // 4222 // ObjC pointers have their own subscripting logic that is not tied 4223 // to overload resolution and so should not take this path. 4224 if (getLangOpts().CPlusPlus && 4225 (base->getType()->isRecordType() || 4226 (!base->getType()->isObjCObjectPointerType() && 4227 idx->getType()->isRecordType()))) { 4228 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4229 } 4230 4231 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4232 } 4233 4234 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4235 Expr *LowerBound, 4236 SourceLocation ColonLoc, Expr *Length, 4237 SourceLocation RBLoc) { 4238 if (Base->getType()->isPlaceholderType() && 4239 !Base->getType()->isSpecificPlaceholderType( 4240 BuiltinType::OMPArraySection)) { 4241 ExprResult Result = CheckPlaceholderExpr(Base); 4242 if (Result.isInvalid()) 4243 return ExprError(); 4244 Base = Result.get(); 4245 } 4246 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4247 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4248 if (Result.isInvalid()) 4249 return ExprError(); 4250 Result = DefaultLvalueConversion(Result.get()); 4251 if (Result.isInvalid()) 4252 return ExprError(); 4253 LowerBound = Result.get(); 4254 } 4255 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4256 ExprResult Result = CheckPlaceholderExpr(Length); 4257 if (Result.isInvalid()) 4258 return ExprError(); 4259 Result = DefaultLvalueConversion(Result.get()); 4260 if (Result.isInvalid()) 4261 return ExprError(); 4262 Length = Result.get(); 4263 } 4264 4265 // Build an unanalyzed expression if either operand is type-dependent. 4266 if (Base->isTypeDependent() || 4267 (LowerBound && 4268 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4269 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4270 return new (Context) 4271 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4272 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4273 } 4274 4275 // Perform default conversions. 4276 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4277 QualType ResultTy; 4278 if (OriginalTy->isAnyPointerType()) { 4279 ResultTy = OriginalTy->getPointeeType(); 4280 } else if (OriginalTy->isArrayType()) { 4281 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4282 } else { 4283 return ExprError( 4284 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4285 << Base->getSourceRange()); 4286 } 4287 // C99 6.5.2.1p1 4288 if (LowerBound) { 4289 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4290 LowerBound); 4291 if (Res.isInvalid()) 4292 return ExprError(Diag(LowerBound->getExprLoc(), 4293 diag::err_omp_typecheck_section_not_integer) 4294 << 0 << LowerBound->getSourceRange()); 4295 LowerBound = Res.get(); 4296 4297 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4298 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4299 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4300 << 0 << LowerBound->getSourceRange(); 4301 } 4302 if (Length) { 4303 auto Res = 4304 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4305 if (Res.isInvalid()) 4306 return ExprError(Diag(Length->getExprLoc(), 4307 diag::err_omp_typecheck_section_not_integer) 4308 << 1 << Length->getSourceRange()); 4309 Length = Res.get(); 4310 4311 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4312 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4313 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4314 << 1 << Length->getSourceRange(); 4315 } 4316 4317 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4318 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4319 // type. Note that functions are not objects, and that (in C99 parlance) 4320 // incomplete types are not object types. 4321 if (ResultTy->isFunctionType()) { 4322 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4323 << ResultTy << Base->getSourceRange(); 4324 return ExprError(); 4325 } 4326 4327 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4328 diag::err_omp_section_incomplete_type, Base)) 4329 return ExprError(); 4330 4331 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4332 llvm::APSInt LowerBoundValue; 4333 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4334 // OpenMP 4.5, [2.4 Array Sections] 4335 // The array section must be a subset of the original array. 4336 if (LowerBoundValue.isNegative()) { 4337 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4338 << LowerBound->getSourceRange(); 4339 return ExprError(); 4340 } 4341 } 4342 } 4343 4344 if (Length) { 4345 llvm::APSInt LengthValue; 4346 if (Length->EvaluateAsInt(LengthValue, Context)) { 4347 // OpenMP 4.5, [2.4 Array Sections] 4348 // The length must evaluate to non-negative integers. 4349 if (LengthValue.isNegative()) { 4350 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4351 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4352 << Length->getSourceRange(); 4353 return ExprError(); 4354 } 4355 } 4356 } else if (ColonLoc.isValid() && 4357 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4358 !OriginalTy->isVariableArrayType()))) { 4359 // OpenMP 4.5, [2.4 Array Sections] 4360 // When the size of the array dimension is not known, the length must be 4361 // specified explicitly. 4362 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4363 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4364 return ExprError(); 4365 } 4366 4367 if (!Base->getType()->isSpecificPlaceholderType( 4368 BuiltinType::OMPArraySection)) { 4369 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4370 if (Result.isInvalid()) 4371 return ExprError(); 4372 Base = Result.get(); 4373 } 4374 return new (Context) 4375 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4376 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4377 } 4378 4379 ExprResult 4380 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4381 Expr *Idx, SourceLocation RLoc) { 4382 Expr *LHSExp = Base; 4383 Expr *RHSExp = Idx; 4384 4385 // Perform default conversions. 4386 if (!LHSExp->getType()->getAs<VectorType>()) { 4387 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4388 if (Result.isInvalid()) 4389 return ExprError(); 4390 LHSExp = Result.get(); 4391 } 4392 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4393 if (Result.isInvalid()) 4394 return ExprError(); 4395 RHSExp = Result.get(); 4396 4397 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4398 ExprValueKind VK = VK_LValue; 4399 ExprObjectKind OK = OK_Ordinary; 4400 4401 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4402 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4403 // in the subscript position. As a result, we need to derive the array base 4404 // and index from the expression types. 4405 Expr *BaseExpr, *IndexExpr; 4406 QualType ResultType; 4407 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4408 BaseExpr = LHSExp; 4409 IndexExpr = RHSExp; 4410 ResultType = Context.DependentTy; 4411 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4412 BaseExpr = LHSExp; 4413 IndexExpr = RHSExp; 4414 ResultType = PTy->getPointeeType(); 4415 } else if (const ObjCObjectPointerType *PTy = 4416 LHSTy->getAs<ObjCObjectPointerType>()) { 4417 BaseExpr = LHSExp; 4418 IndexExpr = RHSExp; 4419 4420 // Use custom logic if this should be the pseudo-object subscript 4421 // expression. 4422 if (!LangOpts.isSubscriptPointerArithmetic()) 4423 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4424 nullptr); 4425 4426 ResultType = PTy->getPointeeType(); 4427 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4428 // Handle the uncommon case of "123[Ptr]". 4429 BaseExpr = RHSExp; 4430 IndexExpr = LHSExp; 4431 ResultType = PTy->getPointeeType(); 4432 } else if (const ObjCObjectPointerType *PTy = 4433 RHSTy->getAs<ObjCObjectPointerType>()) { 4434 // Handle the uncommon case of "123[Ptr]". 4435 BaseExpr = RHSExp; 4436 IndexExpr = LHSExp; 4437 ResultType = PTy->getPointeeType(); 4438 if (!LangOpts.isSubscriptPointerArithmetic()) { 4439 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4440 << ResultType << BaseExpr->getSourceRange(); 4441 return ExprError(); 4442 } 4443 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4444 BaseExpr = LHSExp; // vectors: V[123] 4445 IndexExpr = RHSExp; 4446 VK = LHSExp->getValueKind(); 4447 if (VK != VK_RValue) 4448 OK = OK_VectorComponent; 4449 4450 // FIXME: need to deal with const... 4451 ResultType = VTy->getElementType(); 4452 } else if (LHSTy->isArrayType()) { 4453 // If we see an array that wasn't promoted by 4454 // DefaultFunctionArrayLvalueConversion, it must be an array that 4455 // wasn't promoted because of the C90 rule that doesn't 4456 // allow promoting non-lvalue arrays. Warn, then 4457 // force the promotion here. 4458 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4459 LHSExp->getSourceRange(); 4460 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4461 CK_ArrayToPointerDecay).get(); 4462 LHSTy = LHSExp->getType(); 4463 4464 BaseExpr = LHSExp; 4465 IndexExpr = RHSExp; 4466 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4467 } else if (RHSTy->isArrayType()) { 4468 // Same as previous, except for 123[f().a] case 4469 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4470 RHSExp->getSourceRange(); 4471 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4472 CK_ArrayToPointerDecay).get(); 4473 RHSTy = RHSExp->getType(); 4474 4475 BaseExpr = RHSExp; 4476 IndexExpr = LHSExp; 4477 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4478 } else { 4479 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4480 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4481 } 4482 // C99 6.5.2.1p1 4483 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4484 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4485 << IndexExpr->getSourceRange()); 4486 4487 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4488 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4489 && !IndexExpr->isTypeDependent()) 4490 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4491 4492 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4493 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4494 // type. Note that Functions are not objects, and that (in C99 parlance) 4495 // incomplete types are not object types. 4496 if (ResultType->isFunctionType()) { 4497 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4498 << ResultType << BaseExpr->getSourceRange(); 4499 return ExprError(); 4500 } 4501 4502 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4503 // GNU extension: subscripting on pointer to void 4504 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4505 << BaseExpr->getSourceRange(); 4506 4507 // C forbids expressions of unqualified void type from being l-values. 4508 // See IsCForbiddenLValueType. 4509 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4510 } else if (!ResultType->isDependentType() && 4511 RequireCompleteType(LLoc, ResultType, 4512 diag::err_subscript_incomplete_type, BaseExpr)) 4513 return ExprError(); 4514 4515 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4516 !ResultType.isCForbiddenLValueType()); 4517 4518 return new (Context) 4519 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4520 } 4521 4522 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4523 FunctionDecl *FD, 4524 ParmVarDecl *Param) { 4525 if (Param->hasUnparsedDefaultArg()) { 4526 Diag(CallLoc, 4527 diag::err_use_of_default_argument_to_function_declared_later) << 4528 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4529 Diag(UnparsedDefaultArgLocs[Param], 4530 diag::note_default_argument_declared_here); 4531 return ExprError(); 4532 } 4533 4534 if (Param->hasUninstantiatedDefaultArg()) { 4535 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4536 4537 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4538 Param); 4539 4540 // Instantiate the expression. 4541 MultiLevelTemplateArgumentList MutiLevelArgList 4542 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4543 4544 InstantiatingTemplate Inst(*this, CallLoc, Param, 4545 MutiLevelArgList.getInnermost()); 4546 if (Inst.isInvalid()) 4547 return ExprError(); 4548 if (Inst.isAlreadyInstantiating()) { 4549 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4550 Param->setInvalidDecl(); 4551 return ExprError(); 4552 } 4553 4554 ExprResult Result; 4555 { 4556 // C++ [dcl.fct.default]p5: 4557 // The names in the [default argument] expression are bound, and 4558 // the semantic constraints are checked, at the point where the 4559 // default argument expression appears. 4560 ContextRAII SavedContext(*this, FD); 4561 LocalInstantiationScope Local(*this); 4562 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4563 /*DirectInit*/false); 4564 } 4565 if (Result.isInvalid()) 4566 return ExprError(); 4567 4568 // Check the expression as an initializer for the parameter. 4569 InitializedEntity Entity 4570 = InitializedEntity::InitializeParameter(Context, Param); 4571 InitializationKind Kind 4572 = InitializationKind::CreateCopy(Param->getLocation(), 4573 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4574 Expr *ResultE = Result.getAs<Expr>(); 4575 4576 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4577 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4578 if (Result.isInvalid()) 4579 return ExprError(); 4580 4581 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4582 Param->getOuterLocStart()); 4583 if (Result.isInvalid()) 4584 return ExprError(); 4585 4586 // Remember the instantiated default argument. 4587 Param->setDefaultArg(Result.getAs<Expr>()); 4588 if (ASTMutationListener *L = getASTMutationListener()) { 4589 L->DefaultArgumentInstantiated(Param); 4590 } 4591 } 4592 4593 // If the default argument expression is not set yet, we are building it now. 4594 if (!Param->hasInit()) { 4595 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4596 Param->setInvalidDecl(); 4597 return ExprError(); 4598 } 4599 4600 // If the default expression creates temporaries, we need to 4601 // push them to the current stack of expression temporaries so they'll 4602 // be properly destroyed. 4603 // FIXME: We should really be rebuilding the default argument with new 4604 // bound temporaries; see the comment in PR5810. 4605 // We don't need to do that with block decls, though, because 4606 // blocks in default argument expression can never capture anything. 4607 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4608 // Set the "needs cleanups" bit regardless of whether there are 4609 // any explicit objects. 4610 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4611 4612 // Append all the objects to the cleanup list. Right now, this 4613 // should always be a no-op, because blocks in default argument 4614 // expressions should never be able to capture anything. 4615 assert(!Init->getNumObjects() && 4616 "default argument expression has capturing blocks?"); 4617 } 4618 4619 // We already type-checked the argument, so we know it works. 4620 // Just mark all of the declarations in this potentially-evaluated expression 4621 // as being "referenced". 4622 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4623 /*SkipLocalVariables=*/true); 4624 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4625 } 4626 4627 4628 Sema::VariadicCallType 4629 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4630 Expr *Fn) { 4631 if (Proto && Proto->isVariadic()) { 4632 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4633 return VariadicConstructor; 4634 else if (Fn && Fn->getType()->isBlockPointerType()) 4635 return VariadicBlock; 4636 else if (FDecl) { 4637 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4638 if (Method->isInstance()) 4639 return VariadicMethod; 4640 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4641 return VariadicMethod; 4642 return VariadicFunction; 4643 } 4644 return VariadicDoesNotApply; 4645 } 4646 4647 namespace { 4648 class FunctionCallCCC : public FunctionCallFilterCCC { 4649 public: 4650 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4651 unsigned NumArgs, MemberExpr *ME) 4652 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4653 FunctionName(FuncName) {} 4654 4655 bool ValidateCandidate(const TypoCorrection &candidate) override { 4656 if (!candidate.getCorrectionSpecifier() || 4657 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4658 return false; 4659 } 4660 4661 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4662 } 4663 4664 private: 4665 const IdentifierInfo *const FunctionName; 4666 }; 4667 } 4668 4669 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4670 FunctionDecl *FDecl, 4671 ArrayRef<Expr *> Args) { 4672 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4673 DeclarationName FuncName = FDecl->getDeclName(); 4674 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4675 4676 if (TypoCorrection Corrected = S.CorrectTypo( 4677 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4678 S.getScopeForContext(S.CurContext), nullptr, 4679 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4680 Args.size(), ME), 4681 Sema::CTK_ErrorRecovery)) { 4682 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4683 if (Corrected.isOverloaded()) { 4684 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4685 OverloadCandidateSet::iterator Best; 4686 for (NamedDecl *CD : Corrected) { 4687 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4688 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4689 OCS); 4690 } 4691 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4692 case OR_Success: 4693 ND = Best->FoundDecl; 4694 Corrected.setCorrectionDecl(ND); 4695 break; 4696 default: 4697 break; 4698 } 4699 } 4700 ND = ND->getUnderlyingDecl(); 4701 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4702 return Corrected; 4703 } 4704 } 4705 return TypoCorrection(); 4706 } 4707 4708 /// ConvertArgumentsForCall - Converts the arguments specified in 4709 /// Args/NumArgs to the parameter types of the function FDecl with 4710 /// function prototype Proto. Call is the call expression itself, and 4711 /// Fn is the function expression. For a C++ member function, this 4712 /// routine does not attempt to convert the object argument. Returns 4713 /// true if the call is ill-formed. 4714 bool 4715 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4716 FunctionDecl *FDecl, 4717 const FunctionProtoType *Proto, 4718 ArrayRef<Expr *> Args, 4719 SourceLocation RParenLoc, 4720 bool IsExecConfig) { 4721 // Bail out early if calling a builtin with custom typechecking. 4722 if (FDecl) 4723 if (unsigned ID = FDecl->getBuiltinID()) 4724 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4725 return false; 4726 4727 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4728 // assignment, to the types of the corresponding parameter, ... 4729 unsigned NumParams = Proto->getNumParams(); 4730 bool Invalid = false; 4731 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4732 unsigned FnKind = Fn->getType()->isBlockPointerType() 4733 ? 1 /* block */ 4734 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4735 : 0 /* function */); 4736 4737 // If too few arguments are available (and we don't have default 4738 // arguments for the remaining parameters), don't make the call. 4739 if (Args.size() < NumParams) { 4740 if (Args.size() < MinArgs) { 4741 TypoCorrection TC; 4742 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4743 unsigned diag_id = 4744 MinArgs == NumParams && !Proto->isVariadic() 4745 ? diag::err_typecheck_call_too_few_args_suggest 4746 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4747 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4748 << static_cast<unsigned>(Args.size()) 4749 << TC.getCorrectionRange()); 4750 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4751 Diag(RParenLoc, 4752 MinArgs == NumParams && !Proto->isVariadic() 4753 ? diag::err_typecheck_call_too_few_args_one 4754 : diag::err_typecheck_call_too_few_args_at_least_one) 4755 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4756 else 4757 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4758 ? diag::err_typecheck_call_too_few_args 4759 : diag::err_typecheck_call_too_few_args_at_least) 4760 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4761 << Fn->getSourceRange(); 4762 4763 // Emit the location of the prototype. 4764 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4765 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4766 << FDecl; 4767 4768 return true; 4769 } 4770 Call->setNumArgs(Context, NumParams); 4771 } 4772 4773 // If too many are passed and not variadic, error on the extras and drop 4774 // them. 4775 if (Args.size() > NumParams) { 4776 if (!Proto->isVariadic()) { 4777 TypoCorrection TC; 4778 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4779 unsigned diag_id = 4780 MinArgs == NumParams && !Proto->isVariadic() 4781 ? diag::err_typecheck_call_too_many_args_suggest 4782 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4783 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4784 << static_cast<unsigned>(Args.size()) 4785 << TC.getCorrectionRange()); 4786 } else if (NumParams == 1 && FDecl && 4787 FDecl->getParamDecl(0)->getDeclName()) 4788 Diag(Args[NumParams]->getLocStart(), 4789 MinArgs == NumParams 4790 ? diag::err_typecheck_call_too_many_args_one 4791 : diag::err_typecheck_call_too_many_args_at_most_one) 4792 << FnKind << FDecl->getParamDecl(0) 4793 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4794 << SourceRange(Args[NumParams]->getLocStart(), 4795 Args.back()->getLocEnd()); 4796 else 4797 Diag(Args[NumParams]->getLocStart(), 4798 MinArgs == NumParams 4799 ? diag::err_typecheck_call_too_many_args 4800 : diag::err_typecheck_call_too_many_args_at_most) 4801 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4802 << Fn->getSourceRange() 4803 << SourceRange(Args[NumParams]->getLocStart(), 4804 Args.back()->getLocEnd()); 4805 4806 // Emit the location of the prototype. 4807 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4808 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4809 << FDecl; 4810 4811 // This deletes the extra arguments. 4812 Call->setNumArgs(Context, NumParams); 4813 return true; 4814 } 4815 } 4816 SmallVector<Expr *, 8> AllArgs; 4817 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4818 4819 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4820 Proto, 0, Args, AllArgs, CallType); 4821 if (Invalid) 4822 return true; 4823 unsigned TotalNumArgs = AllArgs.size(); 4824 for (unsigned i = 0; i < TotalNumArgs; ++i) 4825 Call->setArg(i, AllArgs[i]); 4826 4827 return false; 4828 } 4829 4830 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4831 const FunctionProtoType *Proto, 4832 unsigned FirstParam, ArrayRef<Expr *> Args, 4833 SmallVectorImpl<Expr *> &AllArgs, 4834 VariadicCallType CallType, bool AllowExplicit, 4835 bool IsListInitialization) { 4836 unsigned NumParams = Proto->getNumParams(); 4837 bool Invalid = false; 4838 size_t ArgIx = 0; 4839 // Continue to check argument types (even if we have too few/many args). 4840 for (unsigned i = FirstParam; i < NumParams; i++) { 4841 QualType ProtoArgType = Proto->getParamType(i); 4842 4843 Expr *Arg; 4844 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4845 if (ArgIx < Args.size()) { 4846 Arg = Args[ArgIx++]; 4847 4848 if (RequireCompleteType(Arg->getLocStart(), 4849 ProtoArgType, 4850 diag::err_call_incomplete_argument, Arg)) 4851 return true; 4852 4853 // Strip the unbridged-cast placeholder expression off, if applicable. 4854 bool CFAudited = false; 4855 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4856 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4857 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4858 Arg = stripARCUnbridgedCast(Arg); 4859 else if (getLangOpts().ObjCAutoRefCount && 4860 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4861 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4862 CFAudited = true; 4863 4864 InitializedEntity Entity = 4865 Param ? InitializedEntity::InitializeParameter(Context, Param, 4866 ProtoArgType) 4867 : InitializedEntity::InitializeParameter( 4868 Context, ProtoArgType, Proto->isParamConsumed(i)); 4869 4870 // Remember that parameter belongs to a CF audited API. 4871 if (CFAudited) 4872 Entity.setParameterCFAudited(); 4873 4874 ExprResult ArgE = PerformCopyInitialization( 4875 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4876 if (ArgE.isInvalid()) 4877 return true; 4878 4879 Arg = ArgE.getAs<Expr>(); 4880 } else { 4881 assert(Param && "can't use default arguments without a known callee"); 4882 4883 ExprResult ArgExpr = 4884 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4885 if (ArgExpr.isInvalid()) 4886 return true; 4887 4888 Arg = ArgExpr.getAs<Expr>(); 4889 } 4890 4891 // Check for array bounds violations for each argument to the call. This 4892 // check only triggers warnings when the argument isn't a more complex Expr 4893 // with its own checking, such as a BinaryOperator. 4894 CheckArrayAccess(Arg); 4895 4896 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4897 CheckStaticArrayArgument(CallLoc, Param, Arg); 4898 4899 AllArgs.push_back(Arg); 4900 } 4901 4902 // If this is a variadic call, handle args passed through "...". 4903 if (CallType != VariadicDoesNotApply) { 4904 // Assume that extern "C" functions with variadic arguments that 4905 // return __unknown_anytype aren't *really* variadic. 4906 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4907 FDecl->isExternC()) { 4908 for (Expr *A : Args.slice(ArgIx)) { 4909 QualType paramType; // ignored 4910 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4911 Invalid |= arg.isInvalid(); 4912 AllArgs.push_back(arg.get()); 4913 } 4914 4915 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4916 } else { 4917 for (Expr *A : Args.slice(ArgIx)) { 4918 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4919 Invalid |= Arg.isInvalid(); 4920 AllArgs.push_back(Arg.get()); 4921 } 4922 } 4923 4924 // Check for array bounds violations. 4925 for (Expr *A : Args.slice(ArgIx)) 4926 CheckArrayAccess(A); 4927 } 4928 return Invalid; 4929 } 4930 4931 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4932 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4933 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4934 TL = DTL.getOriginalLoc(); 4935 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4936 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4937 << ATL.getLocalSourceRange(); 4938 } 4939 4940 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4941 /// array parameter, check that it is non-null, and that if it is formed by 4942 /// array-to-pointer decay, the underlying array is sufficiently large. 4943 /// 4944 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4945 /// array type derivation, then for each call to the function, the value of the 4946 /// corresponding actual argument shall provide access to the first element of 4947 /// an array with at least as many elements as specified by the size expression. 4948 void 4949 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4950 ParmVarDecl *Param, 4951 const Expr *ArgExpr) { 4952 // Static array parameters are not supported in C++. 4953 if (!Param || getLangOpts().CPlusPlus) 4954 return; 4955 4956 QualType OrigTy = Param->getOriginalType(); 4957 4958 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4959 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4960 return; 4961 4962 if (ArgExpr->isNullPointerConstant(Context, 4963 Expr::NPC_NeverValueDependent)) { 4964 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4965 DiagnoseCalleeStaticArrayParam(*this, Param); 4966 return; 4967 } 4968 4969 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4970 if (!CAT) 4971 return; 4972 4973 const ConstantArrayType *ArgCAT = 4974 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4975 if (!ArgCAT) 4976 return; 4977 4978 if (ArgCAT->getSize().ult(CAT->getSize())) { 4979 Diag(CallLoc, diag::warn_static_array_too_small) 4980 << ArgExpr->getSourceRange() 4981 << (unsigned) ArgCAT->getSize().getZExtValue() 4982 << (unsigned) CAT->getSize().getZExtValue(); 4983 DiagnoseCalleeStaticArrayParam(*this, Param); 4984 } 4985 } 4986 4987 /// Given a function expression of unknown-any type, try to rebuild it 4988 /// to have a function type. 4989 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4990 4991 /// Is the given type a placeholder that we need to lower out 4992 /// immediately during argument processing? 4993 static bool isPlaceholderToRemoveAsArg(QualType type) { 4994 // Placeholders are never sugared. 4995 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4996 if (!placeholder) return false; 4997 4998 switch (placeholder->getKind()) { 4999 // Ignore all the non-placeholder types. 5000 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5001 case BuiltinType::Id: 5002 #include "clang/Basic/OpenCLImageTypes.def" 5003 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5004 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5005 #include "clang/AST/BuiltinTypes.def" 5006 return false; 5007 5008 // We cannot lower out overload sets; they might validly be resolved 5009 // by the call machinery. 5010 case BuiltinType::Overload: 5011 return false; 5012 5013 // Unbridged casts in ARC can be handled in some call positions and 5014 // should be left in place. 5015 case BuiltinType::ARCUnbridgedCast: 5016 return false; 5017 5018 // Pseudo-objects should be converted as soon as possible. 5019 case BuiltinType::PseudoObject: 5020 return true; 5021 5022 // The debugger mode could theoretically but currently does not try 5023 // to resolve unknown-typed arguments based on known parameter types. 5024 case BuiltinType::UnknownAny: 5025 return true; 5026 5027 // These are always invalid as call arguments and should be reported. 5028 case BuiltinType::BoundMember: 5029 case BuiltinType::BuiltinFn: 5030 case BuiltinType::OMPArraySection: 5031 return true; 5032 5033 } 5034 llvm_unreachable("bad builtin type kind"); 5035 } 5036 5037 /// Check an argument list for placeholders that we won't try to 5038 /// handle later. 5039 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5040 // Apply this processing to all the arguments at once instead of 5041 // dying at the first failure. 5042 bool hasInvalid = false; 5043 for (size_t i = 0, e = args.size(); i != e; i++) { 5044 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5045 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5046 if (result.isInvalid()) hasInvalid = true; 5047 else args[i] = result.get(); 5048 } else if (hasInvalid) { 5049 (void)S.CorrectDelayedTyposInExpr(args[i]); 5050 } 5051 } 5052 return hasInvalid; 5053 } 5054 5055 /// If a builtin function has a pointer argument with no explicit address 5056 /// space, then it should be able to accept a pointer to any address 5057 /// space as input. In order to do this, we need to replace the 5058 /// standard builtin declaration with one that uses the same address space 5059 /// as the call. 5060 /// 5061 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5062 /// it does not contain any pointer arguments without 5063 /// an address space qualifer. Otherwise the rewritten 5064 /// FunctionDecl is returned. 5065 /// TODO: Handle pointer return types. 5066 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5067 const FunctionDecl *FDecl, 5068 MultiExprArg ArgExprs) { 5069 5070 QualType DeclType = FDecl->getType(); 5071 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5072 5073 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5074 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5075 return nullptr; 5076 5077 bool NeedsNewDecl = false; 5078 unsigned i = 0; 5079 SmallVector<QualType, 8> OverloadParams; 5080 5081 for (QualType ParamType : FT->param_types()) { 5082 5083 // Convert array arguments to pointer to simplify type lookup. 5084 ExprResult ArgRes = 5085 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5086 if (ArgRes.isInvalid()) 5087 return nullptr; 5088 Expr *Arg = ArgRes.get(); 5089 QualType ArgType = Arg->getType(); 5090 if (!ParamType->isPointerType() || 5091 ParamType.getQualifiers().hasAddressSpace() || 5092 !ArgType->isPointerType() || 5093 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5094 OverloadParams.push_back(ParamType); 5095 continue; 5096 } 5097 5098 NeedsNewDecl = true; 5099 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5100 5101 QualType PointeeType = ParamType->getPointeeType(); 5102 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5103 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5104 } 5105 5106 if (!NeedsNewDecl) 5107 return nullptr; 5108 5109 FunctionProtoType::ExtProtoInfo EPI; 5110 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5111 OverloadParams, EPI); 5112 DeclContext *Parent = Context.getTranslationUnitDecl(); 5113 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5114 FDecl->getLocation(), 5115 FDecl->getLocation(), 5116 FDecl->getIdentifier(), 5117 OverloadTy, 5118 /*TInfo=*/nullptr, 5119 SC_Extern, false, 5120 /*hasPrototype=*/true); 5121 SmallVector<ParmVarDecl*, 16> Params; 5122 FT = cast<FunctionProtoType>(OverloadTy); 5123 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5124 QualType ParamType = FT->getParamType(i); 5125 ParmVarDecl *Parm = 5126 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5127 SourceLocation(), nullptr, ParamType, 5128 /*TInfo=*/nullptr, SC_None, nullptr); 5129 Parm->setScopeInfo(0, i); 5130 Params.push_back(Parm); 5131 } 5132 OverloadDecl->setParams(Params); 5133 return OverloadDecl; 5134 } 5135 5136 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5137 std::size_t NumArgs) { 5138 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5139 /*PartialOverloading=*/false)) 5140 return Callee->isVariadic(); 5141 return Callee->getMinRequiredArguments() <= NumArgs; 5142 } 5143 5144 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5145 /// This provides the location of the left/right parens and a list of comma 5146 /// locations. 5147 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5148 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5149 Expr *ExecConfig, bool IsExecConfig) { 5150 // Since this might be a postfix expression, get rid of ParenListExprs. 5151 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5152 if (Result.isInvalid()) return ExprError(); 5153 Fn = Result.get(); 5154 5155 if (checkArgsForPlaceholders(*this, ArgExprs)) 5156 return ExprError(); 5157 5158 if (getLangOpts().CPlusPlus) { 5159 // If this is a pseudo-destructor expression, build the call immediately. 5160 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5161 if (!ArgExprs.empty()) { 5162 // Pseudo-destructor calls should not have any arguments. 5163 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5164 << FixItHint::CreateRemoval( 5165 SourceRange(ArgExprs.front()->getLocStart(), 5166 ArgExprs.back()->getLocEnd())); 5167 } 5168 5169 return new (Context) 5170 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5171 } 5172 if (Fn->getType() == Context.PseudoObjectTy) { 5173 ExprResult result = CheckPlaceholderExpr(Fn); 5174 if (result.isInvalid()) return ExprError(); 5175 Fn = result.get(); 5176 } 5177 5178 // Determine whether this is a dependent call inside a C++ template, 5179 // in which case we won't do any semantic analysis now. 5180 bool Dependent = false; 5181 if (Fn->isTypeDependent()) 5182 Dependent = true; 5183 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5184 Dependent = true; 5185 5186 if (Dependent) { 5187 if (ExecConfig) { 5188 return new (Context) CUDAKernelCallExpr( 5189 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5190 Context.DependentTy, VK_RValue, RParenLoc); 5191 } else { 5192 return new (Context) CallExpr( 5193 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5194 } 5195 } 5196 5197 // Determine whether this is a call to an object (C++ [over.call.object]). 5198 if (Fn->getType()->isRecordType()) 5199 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5200 RParenLoc); 5201 5202 if (Fn->getType() == Context.UnknownAnyTy) { 5203 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5204 if (result.isInvalid()) return ExprError(); 5205 Fn = result.get(); 5206 } 5207 5208 if (Fn->getType() == Context.BoundMemberTy) { 5209 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5210 RParenLoc); 5211 } 5212 } 5213 5214 // Check for overloaded calls. This can happen even in C due to extensions. 5215 if (Fn->getType() == Context.OverloadTy) { 5216 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5217 5218 // We aren't supposed to apply this logic for if there'Scope an '&' 5219 // involved. 5220 if (!find.HasFormOfMemberPointer) { 5221 OverloadExpr *ovl = find.Expression; 5222 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5223 return BuildOverloadedCallExpr( 5224 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5225 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5226 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5227 RParenLoc); 5228 } 5229 } 5230 5231 // If we're directly calling a function, get the appropriate declaration. 5232 if (Fn->getType() == Context.UnknownAnyTy) { 5233 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5234 if (result.isInvalid()) return ExprError(); 5235 Fn = result.get(); 5236 } 5237 5238 Expr *NakedFn = Fn->IgnoreParens(); 5239 5240 bool CallingNDeclIndirectly = false; 5241 NamedDecl *NDecl = nullptr; 5242 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5243 if (UnOp->getOpcode() == UO_AddrOf) { 5244 CallingNDeclIndirectly = true; 5245 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5246 } 5247 } 5248 5249 if (isa<DeclRefExpr>(NakedFn)) { 5250 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5251 5252 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5253 if (FDecl && FDecl->getBuiltinID()) { 5254 // Rewrite the function decl for this builtin by replacing parameters 5255 // with no explicit address space with the address space of the arguments 5256 // in ArgExprs. 5257 if ((FDecl = 5258 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5259 NDecl = FDecl; 5260 Fn = DeclRefExpr::Create( 5261 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5262 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5263 } 5264 } 5265 } else if (isa<MemberExpr>(NakedFn)) 5266 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5267 5268 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5269 if (CallingNDeclIndirectly && 5270 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5271 Fn->getLocStart())) 5272 return ExprError(); 5273 5274 // CheckEnableIf assumes that the we're passing in a sane number of args for 5275 // FD, but that doesn't always hold true here. This is because, in some 5276 // cases, we'll emit a diag about an ill-formed function call, but then 5277 // we'll continue on as if the function call wasn't ill-formed. So, if the 5278 // number of args looks incorrect, don't do enable_if checks; we should've 5279 // already emitted an error about the bad call. 5280 if (FD->hasAttr<EnableIfAttr>() && 5281 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5282 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5283 Diag(Fn->getLocStart(), 5284 isa<CXXMethodDecl>(FD) 5285 ? diag::err_ovl_no_viable_member_function_in_call 5286 : diag::err_ovl_no_viable_function_in_call) 5287 << FD << FD->getSourceRange(); 5288 Diag(FD->getLocation(), 5289 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5290 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5291 } 5292 } 5293 } 5294 5295 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5296 ExecConfig, IsExecConfig); 5297 } 5298 5299 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5300 /// 5301 /// __builtin_astype( value, dst type ) 5302 /// 5303 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5304 SourceLocation BuiltinLoc, 5305 SourceLocation RParenLoc) { 5306 ExprValueKind VK = VK_RValue; 5307 ExprObjectKind OK = OK_Ordinary; 5308 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5309 QualType SrcTy = E->getType(); 5310 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5311 return ExprError(Diag(BuiltinLoc, 5312 diag::err_invalid_astype_of_different_size) 5313 << DstTy 5314 << SrcTy 5315 << E->getSourceRange()); 5316 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5317 } 5318 5319 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5320 /// provided arguments. 5321 /// 5322 /// __builtin_convertvector( value, dst type ) 5323 /// 5324 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5325 SourceLocation BuiltinLoc, 5326 SourceLocation RParenLoc) { 5327 TypeSourceInfo *TInfo; 5328 GetTypeFromParser(ParsedDestTy, &TInfo); 5329 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5330 } 5331 5332 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5333 /// i.e. an expression not of \p OverloadTy. The expression should 5334 /// unary-convert to an expression of function-pointer or 5335 /// block-pointer type. 5336 /// 5337 /// \param NDecl the declaration being called, if available 5338 ExprResult 5339 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5340 SourceLocation LParenLoc, 5341 ArrayRef<Expr *> Args, 5342 SourceLocation RParenLoc, 5343 Expr *Config, bool IsExecConfig) { 5344 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5345 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5346 5347 // Functions with 'interrupt' attribute cannot be called directly. 5348 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5349 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5350 return ExprError(); 5351 } 5352 5353 // Promote the function operand. 5354 // We special-case function promotion here because we only allow promoting 5355 // builtin functions to function pointers in the callee of a call. 5356 ExprResult Result; 5357 if (BuiltinID && 5358 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5359 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5360 CK_BuiltinFnToFnPtr).get(); 5361 } else { 5362 Result = CallExprUnaryConversions(Fn); 5363 } 5364 if (Result.isInvalid()) 5365 return ExprError(); 5366 Fn = Result.get(); 5367 5368 // Make the call expr early, before semantic checks. This guarantees cleanup 5369 // of arguments and function on error. 5370 CallExpr *TheCall; 5371 if (Config) 5372 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5373 cast<CallExpr>(Config), Args, 5374 Context.BoolTy, VK_RValue, 5375 RParenLoc); 5376 else 5377 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5378 VK_RValue, RParenLoc); 5379 5380 if (!getLangOpts().CPlusPlus) { 5381 // C cannot always handle TypoExpr nodes in builtin calls and direct 5382 // function calls as their argument checking don't necessarily handle 5383 // dependent types properly, so make sure any TypoExprs have been 5384 // dealt with. 5385 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5386 if (!Result.isUsable()) return ExprError(); 5387 TheCall = dyn_cast<CallExpr>(Result.get()); 5388 if (!TheCall) return Result; 5389 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5390 } 5391 5392 // Bail out early if calling a builtin with custom typechecking. 5393 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5394 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5395 5396 retry: 5397 const FunctionType *FuncT; 5398 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5399 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5400 // have type pointer to function". 5401 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5402 if (!FuncT) 5403 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5404 << Fn->getType() << Fn->getSourceRange()); 5405 } else if (const BlockPointerType *BPT = 5406 Fn->getType()->getAs<BlockPointerType>()) { 5407 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5408 } else { 5409 // Handle calls to expressions of unknown-any type. 5410 if (Fn->getType() == Context.UnknownAnyTy) { 5411 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5412 if (rewrite.isInvalid()) return ExprError(); 5413 Fn = rewrite.get(); 5414 TheCall->setCallee(Fn); 5415 goto retry; 5416 } 5417 5418 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5419 << Fn->getType() << Fn->getSourceRange()); 5420 } 5421 5422 if (getLangOpts().CUDA) { 5423 if (Config) { 5424 // CUDA: Kernel calls must be to global functions 5425 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5426 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5427 << FDecl->getName() << Fn->getSourceRange()); 5428 5429 // CUDA: Kernel function must have 'void' return type 5430 if (!FuncT->getReturnType()->isVoidType()) 5431 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5432 << Fn->getType() << Fn->getSourceRange()); 5433 } else { 5434 // CUDA: Calls to global functions must be configured 5435 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5436 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5437 << FDecl->getName() << Fn->getSourceRange()); 5438 } 5439 } 5440 5441 // Check for a valid return type 5442 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5443 FDecl)) 5444 return ExprError(); 5445 5446 // We know the result type of the call, set it. 5447 TheCall->setType(FuncT->getCallResultType(Context)); 5448 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5449 5450 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5451 if (Proto) { 5452 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5453 IsExecConfig)) 5454 return ExprError(); 5455 } else { 5456 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5457 5458 if (FDecl) { 5459 // Check if we have too few/too many template arguments, based 5460 // on our knowledge of the function definition. 5461 const FunctionDecl *Def = nullptr; 5462 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5463 Proto = Def->getType()->getAs<FunctionProtoType>(); 5464 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5465 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5466 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5467 } 5468 5469 // If the function we're calling isn't a function prototype, but we have 5470 // a function prototype from a prior declaratiom, use that prototype. 5471 if (!FDecl->hasPrototype()) 5472 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5473 } 5474 5475 // Promote the arguments (C99 6.5.2.2p6). 5476 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5477 Expr *Arg = Args[i]; 5478 5479 if (Proto && i < Proto->getNumParams()) { 5480 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5481 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5482 ExprResult ArgE = 5483 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5484 if (ArgE.isInvalid()) 5485 return true; 5486 5487 Arg = ArgE.getAs<Expr>(); 5488 5489 } else { 5490 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5491 5492 if (ArgE.isInvalid()) 5493 return true; 5494 5495 Arg = ArgE.getAs<Expr>(); 5496 } 5497 5498 if (RequireCompleteType(Arg->getLocStart(), 5499 Arg->getType(), 5500 diag::err_call_incomplete_argument, Arg)) 5501 return ExprError(); 5502 5503 TheCall->setArg(i, Arg); 5504 } 5505 } 5506 5507 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5508 if (!Method->isStatic()) 5509 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5510 << Fn->getSourceRange()); 5511 5512 // Check for sentinels 5513 if (NDecl) 5514 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5515 5516 // Do special checking on direct calls to functions. 5517 if (FDecl) { 5518 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5519 return ExprError(); 5520 5521 if (BuiltinID) 5522 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5523 } else if (NDecl) { 5524 if (CheckPointerCall(NDecl, TheCall, Proto)) 5525 return ExprError(); 5526 } else { 5527 if (CheckOtherCall(TheCall, Proto)) 5528 return ExprError(); 5529 } 5530 5531 return MaybeBindToTemporary(TheCall); 5532 } 5533 5534 ExprResult 5535 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5536 SourceLocation RParenLoc, Expr *InitExpr) { 5537 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5538 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5539 5540 TypeSourceInfo *TInfo; 5541 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5542 if (!TInfo) 5543 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5544 5545 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5546 } 5547 5548 ExprResult 5549 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5550 SourceLocation RParenLoc, Expr *LiteralExpr) { 5551 QualType literalType = TInfo->getType(); 5552 5553 if (literalType->isArrayType()) { 5554 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5555 diag::err_illegal_decl_array_incomplete_type, 5556 SourceRange(LParenLoc, 5557 LiteralExpr->getSourceRange().getEnd()))) 5558 return ExprError(); 5559 if (literalType->isVariableArrayType()) 5560 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5561 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5562 } else if (!literalType->isDependentType() && 5563 RequireCompleteType(LParenLoc, literalType, 5564 diag::err_typecheck_decl_incomplete_type, 5565 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5566 return ExprError(); 5567 5568 InitializedEntity Entity 5569 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5570 InitializationKind Kind 5571 = InitializationKind::CreateCStyleCast(LParenLoc, 5572 SourceRange(LParenLoc, RParenLoc), 5573 /*InitList=*/true); 5574 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5575 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5576 &literalType); 5577 if (Result.isInvalid()) 5578 return ExprError(); 5579 LiteralExpr = Result.get(); 5580 5581 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5582 if (isFileScope && 5583 !LiteralExpr->isTypeDependent() && 5584 !LiteralExpr->isValueDependent() && 5585 !literalType->isDependentType()) { // 6.5.2.5p3 5586 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5587 return ExprError(); 5588 } 5589 5590 // In C, compound literals are l-values for some reason. 5591 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5592 5593 return MaybeBindToTemporary( 5594 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5595 VK, LiteralExpr, isFileScope)); 5596 } 5597 5598 ExprResult 5599 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5600 SourceLocation RBraceLoc) { 5601 // Immediately handle non-overload placeholders. Overloads can be 5602 // resolved contextually, but everything else here can't. 5603 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5604 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5605 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5606 5607 // Ignore failures; dropping the entire initializer list because 5608 // of one failure would be terrible for indexing/etc. 5609 if (result.isInvalid()) continue; 5610 5611 InitArgList[I] = result.get(); 5612 } 5613 } 5614 5615 // Semantic analysis for initializers is done by ActOnDeclarator() and 5616 // CheckInitializer() - it requires knowledge of the object being intialized. 5617 5618 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5619 RBraceLoc); 5620 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5621 return E; 5622 } 5623 5624 /// Do an explicit extend of the given block pointer if we're in ARC. 5625 void Sema::maybeExtendBlockObject(ExprResult &E) { 5626 assert(E.get()->getType()->isBlockPointerType()); 5627 assert(E.get()->isRValue()); 5628 5629 // Only do this in an r-value context. 5630 if (!getLangOpts().ObjCAutoRefCount) return; 5631 5632 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5633 CK_ARCExtendBlockObject, E.get(), 5634 /*base path*/ nullptr, VK_RValue); 5635 Cleanup.setExprNeedsCleanups(true); 5636 } 5637 5638 /// Prepare a conversion of the given expression to an ObjC object 5639 /// pointer type. 5640 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5641 QualType type = E.get()->getType(); 5642 if (type->isObjCObjectPointerType()) { 5643 return CK_BitCast; 5644 } else if (type->isBlockPointerType()) { 5645 maybeExtendBlockObject(E); 5646 return CK_BlockPointerToObjCPointerCast; 5647 } else { 5648 assert(type->isPointerType()); 5649 return CK_CPointerToObjCPointerCast; 5650 } 5651 } 5652 5653 /// Prepares for a scalar cast, performing all the necessary stages 5654 /// except the final cast and returning the kind required. 5655 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5656 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5657 // Also, callers should have filtered out the invalid cases with 5658 // pointers. Everything else should be possible. 5659 5660 QualType SrcTy = Src.get()->getType(); 5661 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5662 return CK_NoOp; 5663 5664 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5665 case Type::STK_MemberPointer: 5666 llvm_unreachable("member pointer type in C"); 5667 5668 case Type::STK_CPointer: 5669 case Type::STK_BlockPointer: 5670 case Type::STK_ObjCObjectPointer: 5671 switch (DestTy->getScalarTypeKind()) { 5672 case Type::STK_CPointer: { 5673 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5674 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5675 if (SrcAS != DestAS) 5676 return CK_AddressSpaceConversion; 5677 return CK_BitCast; 5678 } 5679 case Type::STK_BlockPointer: 5680 return (SrcKind == Type::STK_BlockPointer 5681 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5682 case Type::STK_ObjCObjectPointer: 5683 if (SrcKind == Type::STK_ObjCObjectPointer) 5684 return CK_BitCast; 5685 if (SrcKind == Type::STK_CPointer) 5686 return CK_CPointerToObjCPointerCast; 5687 maybeExtendBlockObject(Src); 5688 return CK_BlockPointerToObjCPointerCast; 5689 case Type::STK_Bool: 5690 return CK_PointerToBoolean; 5691 case Type::STK_Integral: 5692 return CK_PointerToIntegral; 5693 case Type::STK_Floating: 5694 case Type::STK_FloatingComplex: 5695 case Type::STK_IntegralComplex: 5696 case Type::STK_MemberPointer: 5697 llvm_unreachable("illegal cast from pointer"); 5698 } 5699 llvm_unreachable("Should have returned before this"); 5700 5701 case Type::STK_Bool: // casting from bool is like casting from an integer 5702 case Type::STK_Integral: 5703 switch (DestTy->getScalarTypeKind()) { 5704 case Type::STK_CPointer: 5705 case Type::STK_ObjCObjectPointer: 5706 case Type::STK_BlockPointer: 5707 if (Src.get()->isNullPointerConstant(Context, 5708 Expr::NPC_ValueDependentIsNull)) 5709 return CK_NullToPointer; 5710 return CK_IntegralToPointer; 5711 case Type::STK_Bool: 5712 return CK_IntegralToBoolean; 5713 case Type::STK_Integral: 5714 return CK_IntegralCast; 5715 case Type::STK_Floating: 5716 return CK_IntegralToFloating; 5717 case Type::STK_IntegralComplex: 5718 Src = ImpCastExprToType(Src.get(), 5719 DestTy->castAs<ComplexType>()->getElementType(), 5720 CK_IntegralCast); 5721 return CK_IntegralRealToComplex; 5722 case Type::STK_FloatingComplex: 5723 Src = ImpCastExprToType(Src.get(), 5724 DestTy->castAs<ComplexType>()->getElementType(), 5725 CK_IntegralToFloating); 5726 return CK_FloatingRealToComplex; 5727 case Type::STK_MemberPointer: 5728 llvm_unreachable("member pointer type in C"); 5729 } 5730 llvm_unreachable("Should have returned before this"); 5731 5732 case Type::STK_Floating: 5733 switch (DestTy->getScalarTypeKind()) { 5734 case Type::STK_Floating: 5735 return CK_FloatingCast; 5736 case Type::STK_Bool: 5737 return CK_FloatingToBoolean; 5738 case Type::STK_Integral: 5739 return CK_FloatingToIntegral; 5740 case Type::STK_FloatingComplex: 5741 Src = ImpCastExprToType(Src.get(), 5742 DestTy->castAs<ComplexType>()->getElementType(), 5743 CK_FloatingCast); 5744 return CK_FloatingRealToComplex; 5745 case Type::STK_IntegralComplex: 5746 Src = ImpCastExprToType(Src.get(), 5747 DestTy->castAs<ComplexType>()->getElementType(), 5748 CK_FloatingToIntegral); 5749 return CK_IntegralRealToComplex; 5750 case Type::STK_CPointer: 5751 case Type::STK_ObjCObjectPointer: 5752 case Type::STK_BlockPointer: 5753 llvm_unreachable("valid float->pointer cast?"); 5754 case Type::STK_MemberPointer: 5755 llvm_unreachable("member pointer type in C"); 5756 } 5757 llvm_unreachable("Should have returned before this"); 5758 5759 case Type::STK_FloatingComplex: 5760 switch (DestTy->getScalarTypeKind()) { 5761 case Type::STK_FloatingComplex: 5762 return CK_FloatingComplexCast; 5763 case Type::STK_IntegralComplex: 5764 return CK_FloatingComplexToIntegralComplex; 5765 case Type::STK_Floating: { 5766 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5767 if (Context.hasSameType(ET, DestTy)) 5768 return CK_FloatingComplexToReal; 5769 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5770 return CK_FloatingCast; 5771 } 5772 case Type::STK_Bool: 5773 return CK_FloatingComplexToBoolean; 5774 case Type::STK_Integral: 5775 Src = ImpCastExprToType(Src.get(), 5776 SrcTy->castAs<ComplexType>()->getElementType(), 5777 CK_FloatingComplexToReal); 5778 return CK_FloatingToIntegral; 5779 case Type::STK_CPointer: 5780 case Type::STK_ObjCObjectPointer: 5781 case Type::STK_BlockPointer: 5782 llvm_unreachable("valid complex float->pointer cast?"); 5783 case Type::STK_MemberPointer: 5784 llvm_unreachable("member pointer type in C"); 5785 } 5786 llvm_unreachable("Should have returned before this"); 5787 5788 case Type::STK_IntegralComplex: 5789 switch (DestTy->getScalarTypeKind()) { 5790 case Type::STK_FloatingComplex: 5791 return CK_IntegralComplexToFloatingComplex; 5792 case Type::STK_IntegralComplex: 5793 return CK_IntegralComplexCast; 5794 case Type::STK_Integral: { 5795 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5796 if (Context.hasSameType(ET, DestTy)) 5797 return CK_IntegralComplexToReal; 5798 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5799 return CK_IntegralCast; 5800 } 5801 case Type::STK_Bool: 5802 return CK_IntegralComplexToBoolean; 5803 case Type::STK_Floating: 5804 Src = ImpCastExprToType(Src.get(), 5805 SrcTy->castAs<ComplexType>()->getElementType(), 5806 CK_IntegralComplexToReal); 5807 return CK_IntegralToFloating; 5808 case Type::STK_CPointer: 5809 case Type::STK_ObjCObjectPointer: 5810 case Type::STK_BlockPointer: 5811 llvm_unreachable("valid complex int->pointer cast?"); 5812 case Type::STK_MemberPointer: 5813 llvm_unreachable("member pointer type in C"); 5814 } 5815 llvm_unreachable("Should have returned before this"); 5816 } 5817 5818 llvm_unreachable("Unhandled scalar cast"); 5819 } 5820 5821 static bool breakDownVectorType(QualType type, uint64_t &len, 5822 QualType &eltType) { 5823 // Vectors are simple. 5824 if (const VectorType *vecType = type->getAs<VectorType>()) { 5825 len = vecType->getNumElements(); 5826 eltType = vecType->getElementType(); 5827 assert(eltType->isScalarType()); 5828 return true; 5829 } 5830 5831 // We allow lax conversion to and from non-vector types, but only if 5832 // they're real types (i.e. non-complex, non-pointer scalar types). 5833 if (!type->isRealType()) return false; 5834 5835 len = 1; 5836 eltType = type; 5837 return true; 5838 } 5839 5840 /// Are the two types lax-compatible vector types? That is, given 5841 /// that one of them is a vector, do they have equal storage sizes, 5842 /// where the storage size is the number of elements times the element 5843 /// size? 5844 /// 5845 /// This will also return false if either of the types is neither a 5846 /// vector nor a real type. 5847 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5848 assert(destTy->isVectorType() || srcTy->isVectorType()); 5849 5850 // Disallow lax conversions between scalars and ExtVectors (these 5851 // conversions are allowed for other vector types because common headers 5852 // depend on them). Most scalar OP ExtVector cases are handled by the 5853 // splat path anyway, which does what we want (convert, not bitcast). 5854 // What this rules out for ExtVectors is crazy things like char4*float. 5855 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5856 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5857 5858 uint64_t srcLen, destLen; 5859 QualType srcEltTy, destEltTy; 5860 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5861 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5862 5863 // ASTContext::getTypeSize will return the size rounded up to a 5864 // power of 2, so instead of using that, we need to use the raw 5865 // element size multiplied by the element count. 5866 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5867 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5868 5869 return (srcLen * srcEltSize == destLen * destEltSize); 5870 } 5871 5872 /// Is this a legal conversion between two types, one of which is 5873 /// known to be a vector type? 5874 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5875 assert(destTy->isVectorType() || srcTy->isVectorType()); 5876 5877 if (!Context.getLangOpts().LaxVectorConversions) 5878 return false; 5879 return areLaxCompatibleVectorTypes(srcTy, destTy); 5880 } 5881 5882 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5883 CastKind &Kind) { 5884 assert(VectorTy->isVectorType() && "Not a vector type!"); 5885 5886 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5887 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5888 return Diag(R.getBegin(), 5889 Ty->isVectorType() ? 5890 diag::err_invalid_conversion_between_vectors : 5891 diag::err_invalid_conversion_between_vector_and_integer) 5892 << VectorTy << Ty << R; 5893 } else 5894 return Diag(R.getBegin(), 5895 diag::err_invalid_conversion_between_vector_and_scalar) 5896 << VectorTy << Ty << R; 5897 5898 Kind = CK_BitCast; 5899 return false; 5900 } 5901 5902 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5903 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5904 5905 if (DestElemTy == SplattedExpr->getType()) 5906 return SplattedExpr; 5907 5908 assert(DestElemTy->isFloatingType() || 5909 DestElemTy->isIntegralOrEnumerationType()); 5910 5911 CastKind CK; 5912 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5913 // OpenCL requires that we convert `true` boolean expressions to -1, but 5914 // only when splatting vectors. 5915 if (DestElemTy->isFloatingType()) { 5916 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5917 // in two steps: boolean to signed integral, then to floating. 5918 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5919 CK_BooleanToSignedIntegral); 5920 SplattedExpr = CastExprRes.get(); 5921 CK = CK_IntegralToFloating; 5922 } else { 5923 CK = CK_BooleanToSignedIntegral; 5924 } 5925 } else { 5926 ExprResult CastExprRes = SplattedExpr; 5927 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5928 if (CastExprRes.isInvalid()) 5929 return ExprError(); 5930 SplattedExpr = CastExprRes.get(); 5931 } 5932 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5933 } 5934 5935 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5936 Expr *CastExpr, CastKind &Kind) { 5937 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5938 5939 QualType SrcTy = CastExpr->getType(); 5940 5941 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5942 // an ExtVectorType. 5943 // In OpenCL, casts between vectors of different types are not allowed. 5944 // (See OpenCL 6.2). 5945 if (SrcTy->isVectorType()) { 5946 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5947 || (getLangOpts().OpenCL && 5948 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5949 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5950 << DestTy << SrcTy << R; 5951 return ExprError(); 5952 } 5953 Kind = CK_BitCast; 5954 return CastExpr; 5955 } 5956 5957 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5958 // conversion will take place first from scalar to elt type, and then 5959 // splat from elt type to vector. 5960 if (SrcTy->isPointerType()) 5961 return Diag(R.getBegin(), 5962 diag::err_invalid_conversion_between_vector_and_scalar) 5963 << DestTy << SrcTy << R; 5964 5965 Kind = CK_VectorSplat; 5966 return prepareVectorSplat(DestTy, CastExpr); 5967 } 5968 5969 ExprResult 5970 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5971 Declarator &D, ParsedType &Ty, 5972 SourceLocation RParenLoc, Expr *CastExpr) { 5973 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5974 "ActOnCastExpr(): missing type or expr"); 5975 5976 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5977 if (D.isInvalidType()) 5978 return ExprError(); 5979 5980 if (getLangOpts().CPlusPlus) { 5981 // Check that there are no default arguments (C++ only). 5982 CheckExtraCXXDefaultArguments(D); 5983 } else { 5984 // Make sure any TypoExprs have been dealt with. 5985 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5986 if (!Res.isUsable()) 5987 return ExprError(); 5988 CastExpr = Res.get(); 5989 } 5990 5991 checkUnusedDeclAttributes(D); 5992 5993 QualType castType = castTInfo->getType(); 5994 Ty = CreateParsedType(castType, castTInfo); 5995 5996 bool isVectorLiteral = false; 5997 5998 // Check for an altivec or OpenCL literal, 5999 // i.e. all the elements are integer constants. 6000 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6001 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6002 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6003 && castType->isVectorType() && (PE || PLE)) { 6004 if (PLE && PLE->getNumExprs() == 0) { 6005 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6006 return ExprError(); 6007 } 6008 if (PE || PLE->getNumExprs() == 1) { 6009 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6010 if (!E->getType()->isVectorType()) 6011 isVectorLiteral = true; 6012 } 6013 else 6014 isVectorLiteral = true; 6015 } 6016 6017 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6018 // then handle it as such. 6019 if (isVectorLiteral) 6020 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6021 6022 // If the Expr being casted is a ParenListExpr, handle it specially. 6023 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6024 // sequence of BinOp comma operators. 6025 if (isa<ParenListExpr>(CastExpr)) { 6026 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6027 if (Result.isInvalid()) return ExprError(); 6028 CastExpr = Result.get(); 6029 } 6030 6031 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6032 !getSourceManager().isInSystemMacro(LParenLoc)) 6033 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6034 6035 CheckTollFreeBridgeCast(castType, CastExpr); 6036 6037 CheckObjCBridgeRelatedCast(castType, CastExpr); 6038 6039 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6040 6041 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6042 } 6043 6044 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6045 SourceLocation RParenLoc, Expr *E, 6046 TypeSourceInfo *TInfo) { 6047 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6048 "Expected paren or paren list expression"); 6049 6050 Expr **exprs; 6051 unsigned numExprs; 6052 Expr *subExpr; 6053 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6054 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6055 LiteralLParenLoc = PE->getLParenLoc(); 6056 LiteralRParenLoc = PE->getRParenLoc(); 6057 exprs = PE->getExprs(); 6058 numExprs = PE->getNumExprs(); 6059 } else { // isa<ParenExpr> by assertion at function entrance 6060 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6061 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6062 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6063 exprs = &subExpr; 6064 numExprs = 1; 6065 } 6066 6067 QualType Ty = TInfo->getType(); 6068 assert(Ty->isVectorType() && "Expected vector type"); 6069 6070 SmallVector<Expr *, 8> initExprs; 6071 const VectorType *VTy = Ty->getAs<VectorType>(); 6072 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6073 6074 // '(...)' form of vector initialization in AltiVec: the number of 6075 // initializers must be one or must match the size of the vector. 6076 // If a single value is specified in the initializer then it will be 6077 // replicated to all the components of the vector 6078 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6079 // The number of initializers must be one or must match the size of the 6080 // vector. If a single value is specified in the initializer then it will 6081 // be replicated to all the components of the vector 6082 if (numExprs == 1) { 6083 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6084 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6085 if (Literal.isInvalid()) 6086 return ExprError(); 6087 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6088 PrepareScalarCast(Literal, ElemTy)); 6089 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6090 } 6091 else if (numExprs < numElems) { 6092 Diag(E->getExprLoc(), 6093 diag::err_incorrect_number_of_vector_initializers); 6094 return ExprError(); 6095 } 6096 else 6097 initExprs.append(exprs, exprs + numExprs); 6098 } 6099 else { 6100 // For OpenCL, when the number of initializers is a single value, 6101 // it will be replicated to all components of the vector. 6102 if (getLangOpts().OpenCL && 6103 VTy->getVectorKind() == VectorType::GenericVector && 6104 numExprs == 1) { 6105 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6106 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6107 if (Literal.isInvalid()) 6108 return ExprError(); 6109 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6110 PrepareScalarCast(Literal, ElemTy)); 6111 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6112 } 6113 6114 initExprs.append(exprs, exprs + numExprs); 6115 } 6116 // FIXME: This means that pretty-printing the final AST will produce curly 6117 // braces instead of the original commas. 6118 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6119 initExprs, LiteralRParenLoc); 6120 initE->setType(Ty); 6121 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6122 } 6123 6124 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6125 /// the ParenListExpr into a sequence of comma binary operators. 6126 ExprResult 6127 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6128 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6129 if (!E) 6130 return OrigExpr; 6131 6132 ExprResult Result(E->getExpr(0)); 6133 6134 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6135 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6136 E->getExpr(i)); 6137 6138 if (Result.isInvalid()) return ExprError(); 6139 6140 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6141 } 6142 6143 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6144 SourceLocation R, 6145 MultiExprArg Val) { 6146 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6147 return expr; 6148 } 6149 6150 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6151 /// constant and the other is not a pointer. Returns true if a diagnostic is 6152 /// emitted. 6153 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6154 SourceLocation QuestionLoc) { 6155 Expr *NullExpr = LHSExpr; 6156 Expr *NonPointerExpr = RHSExpr; 6157 Expr::NullPointerConstantKind NullKind = 6158 NullExpr->isNullPointerConstant(Context, 6159 Expr::NPC_ValueDependentIsNotNull); 6160 6161 if (NullKind == Expr::NPCK_NotNull) { 6162 NullExpr = RHSExpr; 6163 NonPointerExpr = LHSExpr; 6164 NullKind = 6165 NullExpr->isNullPointerConstant(Context, 6166 Expr::NPC_ValueDependentIsNotNull); 6167 } 6168 6169 if (NullKind == Expr::NPCK_NotNull) 6170 return false; 6171 6172 if (NullKind == Expr::NPCK_ZeroExpression) 6173 return false; 6174 6175 if (NullKind == Expr::NPCK_ZeroLiteral) { 6176 // In this case, check to make sure that we got here from a "NULL" 6177 // string in the source code. 6178 NullExpr = NullExpr->IgnoreParenImpCasts(); 6179 SourceLocation loc = NullExpr->getExprLoc(); 6180 if (!findMacroSpelling(loc, "NULL")) 6181 return false; 6182 } 6183 6184 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6185 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6186 << NonPointerExpr->getType() << DiagType 6187 << NonPointerExpr->getSourceRange(); 6188 return true; 6189 } 6190 6191 /// \brief Return false if the condition expression is valid, true otherwise. 6192 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6193 QualType CondTy = Cond->getType(); 6194 6195 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6196 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6197 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6198 << CondTy << Cond->getSourceRange(); 6199 return true; 6200 } 6201 6202 // C99 6.5.15p2 6203 if (CondTy->isScalarType()) return false; 6204 6205 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6206 << CondTy << Cond->getSourceRange(); 6207 return true; 6208 } 6209 6210 /// \brief Handle when one or both operands are void type. 6211 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6212 ExprResult &RHS) { 6213 Expr *LHSExpr = LHS.get(); 6214 Expr *RHSExpr = RHS.get(); 6215 6216 if (!LHSExpr->getType()->isVoidType()) 6217 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6218 << RHSExpr->getSourceRange(); 6219 if (!RHSExpr->getType()->isVoidType()) 6220 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6221 << LHSExpr->getSourceRange(); 6222 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6223 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6224 return S.Context.VoidTy; 6225 } 6226 6227 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6228 /// true otherwise. 6229 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6230 QualType PointerTy) { 6231 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6232 !NullExpr.get()->isNullPointerConstant(S.Context, 6233 Expr::NPC_ValueDependentIsNull)) 6234 return true; 6235 6236 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6237 return false; 6238 } 6239 6240 /// \brief Checks compatibility between two pointers and return the resulting 6241 /// type. 6242 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6243 ExprResult &RHS, 6244 SourceLocation Loc) { 6245 QualType LHSTy = LHS.get()->getType(); 6246 QualType RHSTy = RHS.get()->getType(); 6247 6248 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6249 // Two identical pointers types are always compatible. 6250 return LHSTy; 6251 } 6252 6253 QualType lhptee, rhptee; 6254 6255 // Get the pointee types. 6256 bool IsBlockPointer = false; 6257 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6258 lhptee = LHSBTy->getPointeeType(); 6259 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6260 IsBlockPointer = true; 6261 } else { 6262 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6263 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6264 } 6265 6266 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6267 // differently qualified versions of compatible types, the result type is 6268 // a pointer to an appropriately qualified version of the composite 6269 // type. 6270 6271 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6272 // clause doesn't make sense for our extensions. E.g. address space 2 should 6273 // be incompatible with address space 3: they may live on different devices or 6274 // anything. 6275 Qualifiers lhQual = lhptee.getQualifiers(); 6276 Qualifiers rhQual = rhptee.getQualifiers(); 6277 6278 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6279 lhQual.removeCVRQualifiers(); 6280 rhQual.removeCVRQualifiers(); 6281 6282 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6283 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6284 6285 // For OpenCL: 6286 // 1. If LHS and RHS types match exactly and: 6287 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6288 // (b) AS overlap => generate addrspacecast 6289 // (c) AS don't overlap => give an error 6290 // 2. if LHS and RHS types don't match: 6291 // (a) AS match => use standard C rules, generate bitcast 6292 // (b) AS overlap => generate addrspacecast instead of bitcast 6293 // (c) AS don't overlap => give an error 6294 6295 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6296 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6297 6298 // OpenCL cases 1c, 2a, 2b, and 2c. 6299 if (CompositeTy.isNull()) { 6300 // In this situation, we assume void* type. No especially good 6301 // reason, but this is what gcc does, and we do have to pick 6302 // to get a consistent AST. 6303 QualType incompatTy; 6304 if (S.getLangOpts().OpenCL) { 6305 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6306 // spaces is disallowed. 6307 unsigned ResultAddrSpace; 6308 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6309 // Cases 2a and 2b. 6310 ResultAddrSpace = lhQual.getAddressSpace(); 6311 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6312 // Cases 2a and 2b. 6313 ResultAddrSpace = rhQual.getAddressSpace(); 6314 } else { 6315 // Cases 1c and 2c. 6316 S.Diag(Loc, 6317 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6318 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6319 << RHS.get()->getSourceRange(); 6320 return QualType(); 6321 } 6322 6323 // Continue handling cases 2a and 2b. 6324 incompatTy = S.Context.getPointerType( 6325 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6326 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6327 (lhQual.getAddressSpace() != ResultAddrSpace) 6328 ? CK_AddressSpaceConversion /* 2b */ 6329 : CK_BitCast /* 2a */); 6330 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6331 (rhQual.getAddressSpace() != ResultAddrSpace) 6332 ? CK_AddressSpaceConversion /* 2b */ 6333 : CK_BitCast /* 2a */); 6334 } else { 6335 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6336 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6337 << RHS.get()->getSourceRange(); 6338 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6339 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6340 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6341 } 6342 return incompatTy; 6343 } 6344 6345 // The pointer types are compatible. 6346 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6347 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6348 if (IsBlockPointer) 6349 ResultTy = S.Context.getBlockPointerType(ResultTy); 6350 else { 6351 // Cases 1a and 1b for OpenCL. 6352 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6353 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6354 ? CK_BitCast /* 1a */ 6355 : CK_AddressSpaceConversion /* 1b */; 6356 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6357 ? CK_BitCast /* 1a */ 6358 : CK_AddressSpaceConversion /* 1b */; 6359 ResultTy = S.Context.getPointerType(ResultTy); 6360 } 6361 6362 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6363 // if the target type does not change. 6364 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6365 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6366 return ResultTy; 6367 } 6368 6369 /// \brief Return the resulting type when the operands are both block pointers. 6370 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6371 ExprResult &LHS, 6372 ExprResult &RHS, 6373 SourceLocation Loc) { 6374 QualType LHSTy = LHS.get()->getType(); 6375 QualType RHSTy = RHS.get()->getType(); 6376 6377 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6378 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6379 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6380 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6381 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6382 return destType; 6383 } 6384 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6385 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6386 << RHS.get()->getSourceRange(); 6387 return QualType(); 6388 } 6389 6390 // We have 2 block pointer types. 6391 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6392 } 6393 6394 /// \brief Return the resulting type when the operands are both pointers. 6395 static QualType 6396 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6397 ExprResult &RHS, 6398 SourceLocation Loc) { 6399 // get the pointer types 6400 QualType LHSTy = LHS.get()->getType(); 6401 QualType RHSTy = RHS.get()->getType(); 6402 6403 // get the "pointed to" types 6404 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6405 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6406 6407 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6408 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6409 // Figure out necessary qualifiers (C99 6.5.15p6) 6410 QualType destPointee 6411 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6412 QualType destType = S.Context.getPointerType(destPointee); 6413 // Add qualifiers if necessary. 6414 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6415 // Promote to void*. 6416 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6417 return destType; 6418 } 6419 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6420 QualType destPointee 6421 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6422 QualType destType = S.Context.getPointerType(destPointee); 6423 // Add qualifiers if necessary. 6424 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6425 // Promote to void*. 6426 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6427 return destType; 6428 } 6429 6430 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6431 } 6432 6433 /// \brief Return false if the first expression is not an integer and the second 6434 /// expression is not a pointer, true otherwise. 6435 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6436 Expr* PointerExpr, SourceLocation Loc, 6437 bool IsIntFirstExpr) { 6438 if (!PointerExpr->getType()->isPointerType() || 6439 !Int.get()->getType()->isIntegerType()) 6440 return false; 6441 6442 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6443 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6444 6445 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6446 << Expr1->getType() << Expr2->getType() 6447 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6448 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6449 CK_IntegralToPointer); 6450 return true; 6451 } 6452 6453 /// \brief Simple conversion between integer and floating point types. 6454 /// 6455 /// Used when handling the OpenCL conditional operator where the 6456 /// condition is a vector while the other operands are scalar. 6457 /// 6458 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6459 /// types are either integer or floating type. Between the two 6460 /// operands, the type with the higher rank is defined as the "result 6461 /// type". The other operand needs to be promoted to the same type. No 6462 /// other type promotion is allowed. We cannot use 6463 /// UsualArithmeticConversions() for this purpose, since it always 6464 /// promotes promotable types. 6465 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6466 ExprResult &RHS, 6467 SourceLocation QuestionLoc) { 6468 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6469 if (LHS.isInvalid()) 6470 return QualType(); 6471 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6472 if (RHS.isInvalid()) 6473 return QualType(); 6474 6475 // For conversion purposes, we ignore any qualifiers. 6476 // For example, "const float" and "float" are equivalent. 6477 QualType LHSType = 6478 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6479 QualType RHSType = 6480 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6481 6482 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6483 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6484 << LHSType << LHS.get()->getSourceRange(); 6485 return QualType(); 6486 } 6487 6488 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6489 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6490 << RHSType << RHS.get()->getSourceRange(); 6491 return QualType(); 6492 } 6493 6494 // If both types are identical, no conversion is needed. 6495 if (LHSType == RHSType) 6496 return LHSType; 6497 6498 // Now handle "real" floating types (i.e. float, double, long double). 6499 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6500 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6501 /*IsCompAssign = */ false); 6502 6503 // Finally, we have two differing integer types. 6504 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6505 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6506 } 6507 6508 /// \brief Convert scalar operands to a vector that matches the 6509 /// condition in length. 6510 /// 6511 /// Used when handling the OpenCL conditional operator where the 6512 /// condition is a vector while the other operands are scalar. 6513 /// 6514 /// We first compute the "result type" for the scalar operands 6515 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6516 /// into a vector of that type where the length matches the condition 6517 /// vector type. s6.11.6 requires that the element types of the result 6518 /// and the condition must have the same number of bits. 6519 static QualType 6520 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6521 QualType CondTy, SourceLocation QuestionLoc) { 6522 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6523 if (ResTy.isNull()) return QualType(); 6524 6525 const VectorType *CV = CondTy->getAs<VectorType>(); 6526 assert(CV); 6527 6528 // Determine the vector result type 6529 unsigned NumElements = CV->getNumElements(); 6530 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6531 6532 // Ensure that all types have the same number of bits 6533 if (S.Context.getTypeSize(CV->getElementType()) 6534 != S.Context.getTypeSize(ResTy)) { 6535 // Since VectorTy is created internally, it does not pretty print 6536 // with an OpenCL name. Instead, we just print a description. 6537 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6538 SmallString<64> Str; 6539 llvm::raw_svector_ostream OS(Str); 6540 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6541 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6542 << CondTy << OS.str(); 6543 return QualType(); 6544 } 6545 6546 // Convert operands to the vector result type 6547 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6548 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6549 6550 return VectorTy; 6551 } 6552 6553 /// \brief Return false if this is a valid OpenCL condition vector 6554 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6555 SourceLocation QuestionLoc) { 6556 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6557 // integral type. 6558 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6559 assert(CondTy); 6560 QualType EleTy = CondTy->getElementType(); 6561 if (EleTy->isIntegerType()) return false; 6562 6563 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6564 << Cond->getType() << Cond->getSourceRange(); 6565 return true; 6566 } 6567 6568 /// \brief Return false if the vector condition type and the vector 6569 /// result type are compatible. 6570 /// 6571 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6572 /// number of elements, and their element types have the same number 6573 /// of bits. 6574 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6575 SourceLocation QuestionLoc) { 6576 const VectorType *CV = CondTy->getAs<VectorType>(); 6577 const VectorType *RV = VecResTy->getAs<VectorType>(); 6578 assert(CV && RV); 6579 6580 if (CV->getNumElements() != RV->getNumElements()) { 6581 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6582 << CondTy << VecResTy; 6583 return true; 6584 } 6585 6586 QualType CVE = CV->getElementType(); 6587 QualType RVE = RV->getElementType(); 6588 6589 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6590 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6591 << CondTy << VecResTy; 6592 return true; 6593 } 6594 6595 return false; 6596 } 6597 6598 /// \brief Return the resulting type for the conditional operator in 6599 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6600 /// s6.3.i) when the condition is a vector type. 6601 static QualType 6602 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6603 ExprResult &LHS, ExprResult &RHS, 6604 SourceLocation QuestionLoc) { 6605 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6606 if (Cond.isInvalid()) 6607 return QualType(); 6608 QualType CondTy = Cond.get()->getType(); 6609 6610 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6611 return QualType(); 6612 6613 // If either operand is a vector then find the vector type of the 6614 // result as specified in OpenCL v1.1 s6.3.i. 6615 if (LHS.get()->getType()->isVectorType() || 6616 RHS.get()->getType()->isVectorType()) { 6617 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6618 /*isCompAssign*/false, 6619 /*AllowBothBool*/true, 6620 /*AllowBoolConversions*/false); 6621 if (VecResTy.isNull()) return QualType(); 6622 // The result type must match the condition type as specified in 6623 // OpenCL v1.1 s6.11.6. 6624 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6625 return QualType(); 6626 return VecResTy; 6627 } 6628 6629 // Both operands are scalar. 6630 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6631 } 6632 6633 /// \brief Return true if the Expr is block type 6634 static bool checkBlockType(Sema &S, const Expr *E) { 6635 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6636 QualType Ty = CE->getCallee()->getType(); 6637 if (Ty->isBlockPointerType()) { 6638 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6639 return true; 6640 } 6641 } 6642 return false; 6643 } 6644 6645 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6646 /// In that case, LHS = cond. 6647 /// C99 6.5.15 6648 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6649 ExprResult &RHS, ExprValueKind &VK, 6650 ExprObjectKind &OK, 6651 SourceLocation QuestionLoc) { 6652 6653 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6654 if (!LHSResult.isUsable()) return QualType(); 6655 LHS = LHSResult; 6656 6657 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6658 if (!RHSResult.isUsable()) return QualType(); 6659 RHS = RHSResult; 6660 6661 // C++ is sufficiently different to merit its own checker. 6662 if (getLangOpts().CPlusPlus) 6663 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6664 6665 VK = VK_RValue; 6666 OK = OK_Ordinary; 6667 6668 // The OpenCL operator with a vector condition is sufficiently 6669 // different to merit its own checker. 6670 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6671 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6672 6673 // First, check the condition. 6674 Cond = UsualUnaryConversions(Cond.get()); 6675 if (Cond.isInvalid()) 6676 return QualType(); 6677 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6678 return QualType(); 6679 6680 // Now check the two expressions. 6681 if (LHS.get()->getType()->isVectorType() || 6682 RHS.get()->getType()->isVectorType()) 6683 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6684 /*AllowBothBool*/true, 6685 /*AllowBoolConversions*/false); 6686 6687 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6688 if (LHS.isInvalid() || RHS.isInvalid()) 6689 return QualType(); 6690 6691 QualType LHSTy = LHS.get()->getType(); 6692 QualType RHSTy = RHS.get()->getType(); 6693 6694 // Diagnose attempts to convert between __float128 and long double where 6695 // such conversions currently can't be handled. 6696 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6697 Diag(QuestionLoc, 6698 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6699 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6700 return QualType(); 6701 } 6702 6703 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6704 // selection operator (?:). 6705 if (getLangOpts().OpenCL && 6706 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6707 return QualType(); 6708 } 6709 6710 // If both operands have arithmetic type, do the usual arithmetic conversions 6711 // to find a common type: C99 6.5.15p3,5. 6712 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6713 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6714 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6715 6716 return ResTy; 6717 } 6718 6719 // If both operands are the same structure or union type, the result is that 6720 // type. 6721 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6722 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6723 if (LHSRT->getDecl() == RHSRT->getDecl()) 6724 // "If both the operands have structure or union type, the result has 6725 // that type." This implies that CV qualifiers are dropped. 6726 return LHSTy.getUnqualifiedType(); 6727 // FIXME: Type of conditional expression must be complete in C mode. 6728 } 6729 6730 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6731 // The following || allows only one side to be void (a GCC-ism). 6732 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6733 return checkConditionalVoidType(*this, LHS, RHS); 6734 } 6735 6736 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6737 // the type of the other operand." 6738 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6739 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6740 6741 // All objective-c pointer type analysis is done here. 6742 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6743 QuestionLoc); 6744 if (LHS.isInvalid() || RHS.isInvalid()) 6745 return QualType(); 6746 if (!compositeType.isNull()) 6747 return compositeType; 6748 6749 6750 // Handle block pointer types. 6751 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6752 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6753 QuestionLoc); 6754 6755 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6756 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6757 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6758 QuestionLoc); 6759 6760 // GCC compatibility: soften pointer/integer mismatch. Note that 6761 // null pointers have been filtered out by this point. 6762 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6763 /*isIntFirstExpr=*/true)) 6764 return RHSTy; 6765 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6766 /*isIntFirstExpr=*/false)) 6767 return LHSTy; 6768 6769 // Emit a better diagnostic if one of the expressions is a null pointer 6770 // constant and the other is not a pointer type. In this case, the user most 6771 // likely forgot to take the address of the other expression. 6772 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6773 return QualType(); 6774 6775 // Otherwise, the operands are not compatible. 6776 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6777 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6778 << RHS.get()->getSourceRange(); 6779 return QualType(); 6780 } 6781 6782 /// FindCompositeObjCPointerType - Helper method to find composite type of 6783 /// two objective-c pointer types of the two input expressions. 6784 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6785 SourceLocation QuestionLoc) { 6786 QualType LHSTy = LHS.get()->getType(); 6787 QualType RHSTy = RHS.get()->getType(); 6788 6789 // Handle things like Class and struct objc_class*. Here we case the result 6790 // to the pseudo-builtin, because that will be implicitly cast back to the 6791 // redefinition type if an attempt is made to access its fields. 6792 if (LHSTy->isObjCClassType() && 6793 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6794 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6795 return LHSTy; 6796 } 6797 if (RHSTy->isObjCClassType() && 6798 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6799 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6800 return RHSTy; 6801 } 6802 // And the same for struct objc_object* / id 6803 if (LHSTy->isObjCIdType() && 6804 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6805 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6806 return LHSTy; 6807 } 6808 if (RHSTy->isObjCIdType() && 6809 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6810 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6811 return RHSTy; 6812 } 6813 // And the same for struct objc_selector* / SEL 6814 if (Context.isObjCSelType(LHSTy) && 6815 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6816 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6817 return LHSTy; 6818 } 6819 if (Context.isObjCSelType(RHSTy) && 6820 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6821 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6822 return RHSTy; 6823 } 6824 // Check constraints for Objective-C object pointers types. 6825 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6826 6827 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6828 // Two identical object pointer types are always compatible. 6829 return LHSTy; 6830 } 6831 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6832 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6833 QualType compositeType = LHSTy; 6834 6835 // If both operands are interfaces and either operand can be 6836 // assigned to the other, use that type as the composite 6837 // type. This allows 6838 // xxx ? (A*) a : (B*) b 6839 // where B is a subclass of A. 6840 // 6841 // Additionally, as for assignment, if either type is 'id' 6842 // allow silent coercion. Finally, if the types are 6843 // incompatible then make sure to use 'id' as the composite 6844 // type so the result is acceptable for sending messages to. 6845 6846 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6847 // It could return the composite type. 6848 if (!(compositeType = 6849 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6850 // Nothing more to do. 6851 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6852 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6853 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6854 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6855 } else if ((LHSTy->isObjCQualifiedIdType() || 6856 RHSTy->isObjCQualifiedIdType()) && 6857 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6858 // Need to handle "id<xx>" explicitly. 6859 // GCC allows qualified id and any Objective-C type to devolve to 6860 // id. Currently localizing to here until clear this should be 6861 // part of ObjCQualifiedIdTypesAreCompatible. 6862 compositeType = Context.getObjCIdType(); 6863 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6864 compositeType = Context.getObjCIdType(); 6865 } else { 6866 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6867 << LHSTy << RHSTy 6868 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6869 QualType incompatTy = Context.getObjCIdType(); 6870 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6871 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6872 return incompatTy; 6873 } 6874 // The object pointer types are compatible. 6875 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6876 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6877 return compositeType; 6878 } 6879 // Check Objective-C object pointer types and 'void *' 6880 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6881 if (getLangOpts().ObjCAutoRefCount) { 6882 // ARC forbids the implicit conversion of object pointers to 'void *', 6883 // so these types are not compatible. 6884 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6885 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6886 LHS = RHS = true; 6887 return QualType(); 6888 } 6889 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6890 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6891 QualType destPointee 6892 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6893 QualType destType = Context.getPointerType(destPointee); 6894 // Add qualifiers if necessary. 6895 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6896 // Promote to void*. 6897 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6898 return destType; 6899 } 6900 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6901 if (getLangOpts().ObjCAutoRefCount) { 6902 // ARC forbids the implicit conversion of object pointers to 'void *', 6903 // so these types are not compatible. 6904 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6905 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6906 LHS = RHS = true; 6907 return QualType(); 6908 } 6909 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6910 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6911 QualType destPointee 6912 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6913 QualType destType = Context.getPointerType(destPointee); 6914 // Add qualifiers if necessary. 6915 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6916 // Promote to void*. 6917 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6918 return destType; 6919 } 6920 return QualType(); 6921 } 6922 6923 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6924 /// ParenRange in parentheses. 6925 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6926 const PartialDiagnostic &Note, 6927 SourceRange ParenRange) { 6928 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6929 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6930 EndLoc.isValid()) { 6931 Self.Diag(Loc, Note) 6932 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6933 << FixItHint::CreateInsertion(EndLoc, ")"); 6934 } else { 6935 // We can't display the parentheses, so just show the bare note. 6936 Self.Diag(Loc, Note) << ParenRange; 6937 } 6938 } 6939 6940 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6941 return BinaryOperator::isAdditiveOp(Opc) || 6942 BinaryOperator::isMultiplicativeOp(Opc) || 6943 BinaryOperator::isShiftOp(Opc); 6944 } 6945 6946 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6947 /// expression, either using a built-in or overloaded operator, 6948 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6949 /// expression. 6950 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6951 Expr **RHSExprs) { 6952 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6953 E = E->IgnoreImpCasts(); 6954 E = E->IgnoreConversionOperator(); 6955 E = E->IgnoreImpCasts(); 6956 6957 // Built-in binary operator. 6958 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6959 if (IsArithmeticOp(OP->getOpcode())) { 6960 *Opcode = OP->getOpcode(); 6961 *RHSExprs = OP->getRHS(); 6962 return true; 6963 } 6964 } 6965 6966 // Overloaded operator. 6967 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6968 if (Call->getNumArgs() != 2) 6969 return false; 6970 6971 // Make sure this is really a binary operator that is safe to pass into 6972 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6973 OverloadedOperatorKind OO = Call->getOperator(); 6974 if (OO < OO_Plus || OO > OO_Arrow || 6975 OO == OO_PlusPlus || OO == OO_MinusMinus) 6976 return false; 6977 6978 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6979 if (IsArithmeticOp(OpKind)) { 6980 *Opcode = OpKind; 6981 *RHSExprs = Call->getArg(1); 6982 return true; 6983 } 6984 } 6985 6986 return false; 6987 } 6988 6989 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6990 /// or is a logical expression such as (x==y) which has int type, but is 6991 /// commonly interpreted as boolean. 6992 static bool ExprLooksBoolean(Expr *E) { 6993 E = E->IgnoreParenImpCasts(); 6994 6995 if (E->getType()->isBooleanType()) 6996 return true; 6997 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6998 return OP->isComparisonOp() || OP->isLogicalOp(); 6999 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7000 return OP->getOpcode() == UO_LNot; 7001 if (E->getType()->isPointerType()) 7002 return true; 7003 7004 return false; 7005 } 7006 7007 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7008 /// and binary operator are mixed in a way that suggests the programmer assumed 7009 /// the conditional operator has higher precedence, for example: 7010 /// "int x = a + someBinaryCondition ? 1 : 2". 7011 static void DiagnoseConditionalPrecedence(Sema &Self, 7012 SourceLocation OpLoc, 7013 Expr *Condition, 7014 Expr *LHSExpr, 7015 Expr *RHSExpr) { 7016 BinaryOperatorKind CondOpcode; 7017 Expr *CondRHS; 7018 7019 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7020 return; 7021 if (!ExprLooksBoolean(CondRHS)) 7022 return; 7023 7024 // The condition is an arithmetic binary expression, with a right- 7025 // hand side that looks boolean, so warn. 7026 7027 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7028 << Condition->getSourceRange() 7029 << BinaryOperator::getOpcodeStr(CondOpcode); 7030 7031 SuggestParentheses(Self, OpLoc, 7032 Self.PDiag(diag::note_precedence_silence) 7033 << BinaryOperator::getOpcodeStr(CondOpcode), 7034 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7035 7036 SuggestParentheses(Self, OpLoc, 7037 Self.PDiag(diag::note_precedence_conditional_first), 7038 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7039 } 7040 7041 /// Compute the nullability of a conditional expression. 7042 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7043 QualType LHSTy, QualType RHSTy, 7044 ASTContext &Ctx) { 7045 if (!ResTy->isAnyPointerType()) 7046 return ResTy; 7047 7048 auto GetNullability = [&Ctx](QualType Ty) { 7049 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7050 if (Kind) 7051 return *Kind; 7052 return NullabilityKind::Unspecified; 7053 }; 7054 7055 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7056 NullabilityKind MergedKind; 7057 7058 // Compute nullability of a binary conditional expression. 7059 if (IsBin) { 7060 if (LHSKind == NullabilityKind::NonNull) 7061 MergedKind = NullabilityKind::NonNull; 7062 else 7063 MergedKind = RHSKind; 7064 // Compute nullability of a normal conditional expression. 7065 } else { 7066 if (LHSKind == NullabilityKind::Nullable || 7067 RHSKind == NullabilityKind::Nullable) 7068 MergedKind = NullabilityKind::Nullable; 7069 else if (LHSKind == NullabilityKind::NonNull) 7070 MergedKind = RHSKind; 7071 else if (RHSKind == NullabilityKind::NonNull) 7072 MergedKind = LHSKind; 7073 else 7074 MergedKind = NullabilityKind::Unspecified; 7075 } 7076 7077 // Return if ResTy already has the correct nullability. 7078 if (GetNullability(ResTy) == MergedKind) 7079 return ResTy; 7080 7081 // Strip all nullability from ResTy. 7082 while (ResTy->getNullability(Ctx)) 7083 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7084 7085 // Create a new AttributedType with the new nullability kind. 7086 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7087 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7088 } 7089 7090 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7091 /// in the case of a the GNU conditional expr extension. 7092 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7093 SourceLocation ColonLoc, 7094 Expr *CondExpr, Expr *LHSExpr, 7095 Expr *RHSExpr) { 7096 if (!getLangOpts().CPlusPlus) { 7097 // C cannot handle TypoExpr nodes in the condition because it 7098 // doesn't handle dependent types properly, so make sure any TypoExprs have 7099 // been dealt with before checking the operands. 7100 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7101 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7102 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7103 7104 if (!CondResult.isUsable()) 7105 return ExprError(); 7106 7107 if (LHSExpr) { 7108 if (!LHSResult.isUsable()) 7109 return ExprError(); 7110 } 7111 7112 if (!RHSResult.isUsable()) 7113 return ExprError(); 7114 7115 CondExpr = CondResult.get(); 7116 LHSExpr = LHSResult.get(); 7117 RHSExpr = RHSResult.get(); 7118 } 7119 7120 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7121 // was the condition. 7122 OpaqueValueExpr *opaqueValue = nullptr; 7123 Expr *commonExpr = nullptr; 7124 if (!LHSExpr) { 7125 commonExpr = CondExpr; 7126 // Lower out placeholder types first. This is important so that we don't 7127 // try to capture a placeholder. This happens in few cases in C++; such 7128 // as Objective-C++'s dictionary subscripting syntax. 7129 if (commonExpr->hasPlaceholderType()) { 7130 ExprResult result = CheckPlaceholderExpr(commonExpr); 7131 if (!result.isUsable()) return ExprError(); 7132 commonExpr = result.get(); 7133 } 7134 // We usually want to apply unary conversions *before* saving, except 7135 // in the special case of a C++ l-value conditional. 7136 if (!(getLangOpts().CPlusPlus 7137 && !commonExpr->isTypeDependent() 7138 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7139 && commonExpr->isGLValue() 7140 && commonExpr->isOrdinaryOrBitFieldObject() 7141 && RHSExpr->isOrdinaryOrBitFieldObject() 7142 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7143 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7144 if (commonRes.isInvalid()) 7145 return ExprError(); 7146 commonExpr = commonRes.get(); 7147 } 7148 7149 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7150 commonExpr->getType(), 7151 commonExpr->getValueKind(), 7152 commonExpr->getObjectKind(), 7153 commonExpr); 7154 LHSExpr = CondExpr = opaqueValue; 7155 } 7156 7157 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7158 ExprValueKind VK = VK_RValue; 7159 ExprObjectKind OK = OK_Ordinary; 7160 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7161 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7162 VK, OK, QuestionLoc); 7163 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7164 RHS.isInvalid()) 7165 return ExprError(); 7166 7167 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7168 RHS.get()); 7169 7170 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7171 7172 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7173 Context); 7174 7175 if (!commonExpr) 7176 return new (Context) 7177 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7178 RHS.get(), result, VK, OK); 7179 7180 return new (Context) BinaryConditionalOperator( 7181 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7182 ColonLoc, result, VK, OK); 7183 } 7184 7185 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7186 // being closely modeled after the C99 spec:-). The odd characteristic of this 7187 // routine is it effectively iqnores the qualifiers on the top level pointee. 7188 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7189 // FIXME: add a couple examples in this comment. 7190 static Sema::AssignConvertType 7191 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7192 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7193 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7194 7195 // get the "pointed to" type (ignoring qualifiers at the top level) 7196 const Type *lhptee, *rhptee; 7197 Qualifiers lhq, rhq; 7198 std::tie(lhptee, lhq) = 7199 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7200 std::tie(rhptee, rhq) = 7201 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7202 7203 Sema::AssignConvertType ConvTy = Sema::Compatible; 7204 7205 // C99 6.5.16.1p1: This following citation is common to constraints 7206 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7207 // qualifiers of the type *pointed to* by the right; 7208 7209 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7210 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7211 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7212 // Ignore lifetime for further calculation. 7213 lhq.removeObjCLifetime(); 7214 rhq.removeObjCLifetime(); 7215 } 7216 7217 if (!lhq.compatiblyIncludes(rhq)) { 7218 // Treat address-space mismatches as fatal. TODO: address subspaces 7219 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7220 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7221 7222 // It's okay to add or remove GC or lifetime qualifiers when converting to 7223 // and from void*. 7224 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7225 .compatiblyIncludes( 7226 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7227 && (lhptee->isVoidType() || rhptee->isVoidType())) 7228 ; // keep old 7229 7230 // Treat lifetime mismatches as fatal. 7231 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7232 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7233 7234 // For GCC/MS compatibility, other qualifier mismatches are treated 7235 // as still compatible in C. 7236 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7237 } 7238 7239 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7240 // incomplete type and the other is a pointer to a qualified or unqualified 7241 // version of void... 7242 if (lhptee->isVoidType()) { 7243 if (rhptee->isIncompleteOrObjectType()) 7244 return ConvTy; 7245 7246 // As an extension, we allow cast to/from void* to function pointer. 7247 assert(rhptee->isFunctionType()); 7248 return Sema::FunctionVoidPointer; 7249 } 7250 7251 if (rhptee->isVoidType()) { 7252 if (lhptee->isIncompleteOrObjectType()) 7253 return ConvTy; 7254 7255 // As an extension, we allow cast to/from void* to function pointer. 7256 assert(lhptee->isFunctionType()); 7257 return Sema::FunctionVoidPointer; 7258 } 7259 7260 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7261 // unqualified versions of compatible types, ... 7262 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7263 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7264 // Check if the pointee types are compatible ignoring the sign. 7265 // We explicitly check for char so that we catch "char" vs 7266 // "unsigned char" on systems where "char" is unsigned. 7267 if (lhptee->isCharType()) 7268 ltrans = S.Context.UnsignedCharTy; 7269 else if (lhptee->hasSignedIntegerRepresentation()) 7270 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7271 7272 if (rhptee->isCharType()) 7273 rtrans = S.Context.UnsignedCharTy; 7274 else if (rhptee->hasSignedIntegerRepresentation()) 7275 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7276 7277 if (ltrans == rtrans) { 7278 // Types are compatible ignoring the sign. Qualifier incompatibility 7279 // takes priority over sign incompatibility because the sign 7280 // warning can be disabled. 7281 if (ConvTy != Sema::Compatible) 7282 return ConvTy; 7283 7284 return Sema::IncompatiblePointerSign; 7285 } 7286 7287 // If we are a multi-level pointer, it's possible that our issue is simply 7288 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7289 // the eventual target type is the same and the pointers have the same 7290 // level of indirection, this must be the issue. 7291 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7292 do { 7293 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7294 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7295 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7296 7297 if (lhptee == rhptee) 7298 return Sema::IncompatibleNestedPointerQualifiers; 7299 } 7300 7301 // General pointer incompatibility takes priority over qualifiers. 7302 return Sema::IncompatiblePointer; 7303 } 7304 if (!S.getLangOpts().CPlusPlus && 7305 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7306 return Sema::IncompatiblePointer; 7307 return ConvTy; 7308 } 7309 7310 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7311 /// block pointer types are compatible or whether a block and normal pointer 7312 /// are compatible. It is more restrict than comparing two function pointer 7313 // types. 7314 static Sema::AssignConvertType 7315 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7316 QualType RHSType) { 7317 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7318 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7319 7320 QualType lhptee, rhptee; 7321 7322 // get the "pointed to" type (ignoring qualifiers at the top level) 7323 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7324 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7325 7326 // In C++, the types have to match exactly. 7327 if (S.getLangOpts().CPlusPlus) 7328 return Sema::IncompatibleBlockPointer; 7329 7330 Sema::AssignConvertType ConvTy = Sema::Compatible; 7331 7332 // For blocks we enforce that qualifiers are identical. 7333 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7334 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7335 7336 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7337 return Sema::IncompatibleBlockPointer; 7338 7339 return ConvTy; 7340 } 7341 7342 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7343 /// for assignment compatibility. 7344 static Sema::AssignConvertType 7345 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7346 QualType RHSType) { 7347 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7348 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7349 7350 if (LHSType->isObjCBuiltinType()) { 7351 // Class is not compatible with ObjC object pointers. 7352 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7353 !RHSType->isObjCQualifiedClassType()) 7354 return Sema::IncompatiblePointer; 7355 return Sema::Compatible; 7356 } 7357 if (RHSType->isObjCBuiltinType()) { 7358 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7359 !LHSType->isObjCQualifiedClassType()) 7360 return Sema::IncompatiblePointer; 7361 return Sema::Compatible; 7362 } 7363 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7364 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7365 7366 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7367 // make an exception for id<P> 7368 !LHSType->isObjCQualifiedIdType()) 7369 return Sema::CompatiblePointerDiscardsQualifiers; 7370 7371 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7372 return Sema::Compatible; 7373 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7374 return Sema::IncompatibleObjCQualifiedId; 7375 return Sema::IncompatiblePointer; 7376 } 7377 7378 Sema::AssignConvertType 7379 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7380 QualType LHSType, QualType RHSType) { 7381 // Fake up an opaque expression. We don't actually care about what 7382 // cast operations are required, so if CheckAssignmentConstraints 7383 // adds casts to this they'll be wasted, but fortunately that doesn't 7384 // usually happen on valid code. 7385 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7386 ExprResult RHSPtr = &RHSExpr; 7387 CastKind K = CK_Invalid; 7388 7389 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7390 } 7391 7392 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7393 /// has code to accommodate several GCC extensions when type checking 7394 /// pointers. Here are some objectionable examples that GCC considers warnings: 7395 /// 7396 /// int a, *pint; 7397 /// short *pshort; 7398 /// struct foo *pfoo; 7399 /// 7400 /// pint = pshort; // warning: assignment from incompatible pointer type 7401 /// a = pint; // warning: assignment makes integer from pointer without a cast 7402 /// pint = a; // warning: assignment makes pointer from integer without a cast 7403 /// pint = pfoo; // warning: assignment from incompatible pointer type 7404 /// 7405 /// As a result, the code for dealing with pointers is more complex than the 7406 /// C99 spec dictates. 7407 /// 7408 /// Sets 'Kind' for any result kind except Incompatible. 7409 Sema::AssignConvertType 7410 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7411 CastKind &Kind, bool ConvertRHS) { 7412 QualType RHSType = RHS.get()->getType(); 7413 QualType OrigLHSType = LHSType; 7414 7415 // Get canonical types. We're not formatting these types, just comparing 7416 // them. 7417 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7418 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7419 7420 // Common case: no conversion required. 7421 if (LHSType == RHSType) { 7422 Kind = CK_NoOp; 7423 return Compatible; 7424 } 7425 7426 // If we have an atomic type, try a non-atomic assignment, then just add an 7427 // atomic qualification step. 7428 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7429 Sema::AssignConvertType result = 7430 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7431 if (result != Compatible) 7432 return result; 7433 if (Kind != CK_NoOp && ConvertRHS) 7434 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7435 Kind = CK_NonAtomicToAtomic; 7436 return Compatible; 7437 } 7438 7439 // If the left-hand side is a reference type, then we are in a 7440 // (rare!) case where we've allowed the use of references in C, 7441 // e.g., as a parameter type in a built-in function. In this case, 7442 // just make sure that the type referenced is compatible with the 7443 // right-hand side type. The caller is responsible for adjusting 7444 // LHSType so that the resulting expression does not have reference 7445 // type. 7446 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7447 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7448 Kind = CK_LValueBitCast; 7449 return Compatible; 7450 } 7451 return Incompatible; 7452 } 7453 7454 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7455 // to the same ExtVector type. 7456 if (LHSType->isExtVectorType()) { 7457 if (RHSType->isExtVectorType()) 7458 return Incompatible; 7459 if (RHSType->isArithmeticType()) { 7460 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7461 if (ConvertRHS) 7462 RHS = prepareVectorSplat(LHSType, RHS.get()); 7463 Kind = CK_VectorSplat; 7464 return Compatible; 7465 } 7466 } 7467 7468 // Conversions to or from vector type. 7469 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7470 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7471 // Allow assignments of an AltiVec vector type to an equivalent GCC 7472 // vector type and vice versa 7473 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7474 Kind = CK_BitCast; 7475 return Compatible; 7476 } 7477 7478 // If we are allowing lax vector conversions, and LHS and RHS are both 7479 // vectors, the total size only needs to be the same. This is a bitcast; 7480 // no bits are changed but the result type is different. 7481 if (isLaxVectorConversion(RHSType, LHSType)) { 7482 Kind = CK_BitCast; 7483 return IncompatibleVectors; 7484 } 7485 } 7486 7487 // When the RHS comes from another lax conversion (e.g. binops between 7488 // scalars and vectors) the result is canonicalized as a vector. When the 7489 // LHS is also a vector, the lax is allowed by the condition above. Handle 7490 // the case where LHS is a scalar. 7491 if (LHSType->isScalarType()) { 7492 const VectorType *VecType = RHSType->getAs<VectorType>(); 7493 if (VecType && VecType->getNumElements() == 1 && 7494 isLaxVectorConversion(RHSType, LHSType)) { 7495 ExprResult *VecExpr = &RHS; 7496 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7497 Kind = CK_BitCast; 7498 return Compatible; 7499 } 7500 } 7501 7502 return Incompatible; 7503 } 7504 7505 // Diagnose attempts to convert between __float128 and long double where 7506 // such conversions currently can't be handled. 7507 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7508 return Incompatible; 7509 7510 // Arithmetic conversions. 7511 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7512 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7513 if (ConvertRHS) 7514 Kind = PrepareScalarCast(RHS, LHSType); 7515 return Compatible; 7516 } 7517 7518 // Conversions to normal pointers. 7519 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7520 // U* -> T* 7521 if (isa<PointerType>(RHSType)) { 7522 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7523 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7524 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7525 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7526 } 7527 7528 // int -> T* 7529 if (RHSType->isIntegerType()) { 7530 Kind = CK_IntegralToPointer; // FIXME: null? 7531 return IntToPointer; 7532 } 7533 7534 // C pointers are not compatible with ObjC object pointers, 7535 // with two exceptions: 7536 if (isa<ObjCObjectPointerType>(RHSType)) { 7537 // - conversions to void* 7538 if (LHSPointer->getPointeeType()->isVoidType()) { 7539 Kind = CK_BitCast; 7540 return Compatible; 7541 } 7542 7543 // - conversions from 'Class' to the redefinition type 7544 if (RHSType->isObjCClassType() && 7545 Context.hasSameType(LHSType, 7546 Context.getObjCClassRedefinitionType())) { 7547 Kind = CK_BitCast; 7548 return Compatible; 7549 } 7550 7551 Kind = CK_BitCast; 7552 return IncompatiblePointer; 7553 } 7554 7555 // U^ -> void* 7556 if (RHSType->getAs<BlockPointerType>()) { 7557 if (LHSPointer->getPointeeType()->isVoidType()) { 7558 Kind = CK_BitCast; 7559 return Compatible; 7560 } 7561 } 7562 7563 return Incompatible; 7564 } 7565 7566 // Conversions to block pointers. 7567 if (isa<BlockPointerType>(LHSType)) { 7568 // U^ -> T^ 7569 if (RHSType->isBlockPointerType()) { 7570 Kind = CK_BitCast; 7571 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7572 } 7573 7574 // int or null -> T^ 7575 if (RHSType->isIntegerType()) { 7576 Kind = CK_IntegralToPointer; // FIXME: null 7577 return IntToBlockPointer; 7578 } 7579 7580 // id -> T^ 7581 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7582 Kind = CK_AnyPointerToBlockPointerCast; 7583 return Compatible; 7584 } 7585 7586 // void* -> T^ 7587 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7588 if (RHSPT->getPointeeType()->isVoidType()) { 7589 Kind = CK_AnyPointerToBlockPointerCast; 7590 return Compatible; 7591 } 7592 7593 return Incompatible; 7594 } 7595 7596 // Conversions to Objective-C pointers. 7597 if (isa<ObjCObjectPointerType>(LHSType)) { 7598 // A* -> B* 7599 if (RHSType->isObjCObjectPointerType()) { 7600 Kind = CK_BitCast; 7601 Sema::AssignConvertType result = 7602 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7603 if (getLangOpts().ObjCAutoRefCount && 7604 result == Compatible && 7605 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7606 result = IncompatibleObjCWeakRef; 7607 return result; 7608 } 7609 7610 // int or null -> A* 7611 if (RHSType->isIntegerType()) { 7612 Kind = CK_IntegralToPointer; // FIXME: null 7613 return IntToPointer; 7614 } 7615 7616 // In general, C pointers are not compatible with ObjC object pointers, 7617 // with two exceptions: 7618 if (isa<PointerType>(RHSType)) { 7619 Kind = CK_CPointerToObjCPointerCast; 7620 7621 // - conversions from 'void*' 7622 if (RHSType->isVoidPointerType()) { 7623 return Compatible; 7624 } 7625 7626 // - conversions to 'Class' from its redefinition type 7627 if (LHSType->isObjCClassType() && 7628 Context.hasSameType(RHSType, 7629 Context.getObjCClassRedefinitionType())) { 7630 return Compatible; 7631 } 7632 7633 return IncompatiblePointer; 7634 } 7635 7636 // Only under strict condition T^ is compatible with an Objective-C pointer. 7637 if (RHSType->isBlockPointerType() && 7638 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7639 if (ConvertRHS) 7640 maybeExtendBlockObject(RHS); 7641 Kind = CK_BlockPointerToObjCPointerCast; 7642 return Compatible; 7643 } 7644 7645 return Incompatible; 7646 } 7647 7648 // Conversions from pointers that are not covered by the above. 7649 if (isa<PointerType>(RHSType)) { 7650 // T* -> _Bool 7651 if (LHSType == Context.BoolTy) { 7652 Kind = CK_PointerToBoolean; 7653 return Compatible; 7654 } 7655 7656 // T* -> int 7657 if (LHSType->isIntegerType()) { 7658 Kind = CK_PointerToIntegral; 7659 return PointerToInt; 7660 } 7661 7662 return Incompatible; 7663 } 7664 7665 // Conversions from Objective-C pointers that are not covered by the above. 7666 if (isa<ObjCObjectPointerType>(RHSType)) { 7667 // T* -> _Bool 7668 if (LHSType == Context.BoolTy) { 7669 Kind = CK_PointerToBoolean; 7670 return Compatible; 7671 } 7672 7673 // T* -> int 7674 if (LHSType->isIntegerType()) { 7675 Kind = CK_PointerToIntegral; 7676 return PointerToInt; 7677 } 7678 7679 return Incompatible; 7680 } 7681 7682 // struct A -> struct B 7683 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7684 if (Context.typesAreCompatible(LHSType, RHSType)) { 7685 Kind = CK_NoOp; 7686 return Compatible; 7687 } 7688 } 7689 7690 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7691 Kind = CK_IntToOCLSampler; 7692 return Compatible; 7693 } 7694 7695 return Incompatible; 7696 } 7697 7698 /// \brief Constructs a transparent union from an expression that is 7699 /// used to initialize the transparent union. 7700 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7701 ExprResult &EResult, QualType UnionType, 7702 FieldDecl *Field) { 7703 // Build an initializer list that designates the appropriate member 7704 // of the transparent union. 7705 Expr *E = EResult.get(); 7706 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7707 E, SourceLocation()); 7708 Initializer->setType(UnionType); 7709 Initializer->setInitializedFieldInUnion(Field); 7710 7711 // Build a compound literal constructing a value of the transparent 7712 // union type from this initializer list. 7713 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7714 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7715 VK_RValue, Initializer, false); 7716 } 7717 7718 Sema::AssignConvertType 7719 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7720 ExprResult &RHS) { 7721 QualType RHSType = RHS.get()->getType(); 7722 7723 // If the ArgType is a Union type, we want to handle a potential 7724 // transparent_union GCC extension. 7725 const RecordType *UT = ArgType->getAsUnionType(); 7726 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7727 return Incompatible; 7728 7729 // The field to initialize within the transparent union. 7730 RecordDecl *UD = UT->getDecl(); 7731 FieldDecl *InitField = nullptr; 7732 // It's compatible if the expression matches any of the fields. 7733 for (auto *it : UD->fields()) { 7734 if (it->getType()->isPointerType()) { 7735 // If the transparent union contains a pointer type, we allow: 7736 // 1) void pointer 7737 // 2) null pointer constant 7738 if (RHSType->isPointerType()) 7739 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7740 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7741 InitField = it; 7742 break; 7743 } 7744 7745 if (RHS.get()->isNullPointerConstant(Context, 7746 Expr::NPC_ValueDependentIsNull)) { 7747 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7748 CK_NullToPointer); 7749 InitField = it; 7750 break; 7751 } 7752 } 7753 7754 CastKind Kind = CK_Invalid; 7755 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7756 == Compatible) { 7757 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7758 InitField = it; 7759 break; 7760 } 7761 } 7762 7763 if (!InitField) 7764 return Incompatible; 7765 7766 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7767 return Compatible; 7768 } 7769 7770 Sema::AssignConvertType 7771 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7772 bool Diagnose, 7773 bool DiagnoseCFAudited, 7774 bool ConvertRHS) { 7775 // We need to be able to tell the caller whether we diagnosed a problem, if 7776 // they ask us to issue diagnostics. 7777 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7778 7779 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7780 // we can't avoid *all* modifications at the moment, so we need some somewhere 7781 // to put the updated value. 7782 ExprResult LocalRHS = CallerRHS; 7783 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7784 7785 if (getLangOpts().CPlusPlus) { 7786 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7787 // C++ 5.17p3: If the left operand is not of class type, the 7788 // expression is implicitly converted (C++ 4) to the 7789 // cv-unqualified type of the left operand. 7790 QualType RHSType = RHS.get()->getType(); 7791 if (Diagnose) { 7792 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7793 AA_Assigning); 7794 } else { 7795 ImplicitConversionSequence ICS = 7796 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7797 /*SuppressUserConversions=*/false, 7798 /*AllowExplicit=*/false, 7799 /*InOverloadResolution=*/false, 7800 /*CStyle=*/false, 7801 /*AllowObjCWritebackConversion=*/false); 7802 if (ICS.isFailure()) 7803 return Incompatible; 7804 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7805 ICS, AA_Assigning); 7806 } 7807 if (RHS.isInvalid()) 7808 return Incompatible; 7809 Sema::AssignConvertType result = Compatible; 7810 if (getLangOpts().ObjCAutoRefCount && 7811 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7812 result = IncompatibleObjCWeakRef; 7813 return result; 7814 } 7815 7816 // FIXME: Currently, we fall through and treat C++ classes like C 7817 // structures. 7818 // FIXME: We also fall through for atomics; not sure what should 7819 // happen there, though. 7820 } else if (RHS.get()->getType() == Context.OverloadTy) { 7821 // As a set of extensions to C, we support overloading on functions. These 7822 // functions need to be resolved here. 7823 DeclAccessPair DAP; 7824 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7825 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7826 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7827 else 7828 return Incompatible; 7829 } 7830 7831 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7832 // a null pointer constant. 7833 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7834 LHSType->isBlockPointerType()) && 7835 RHS.get()->isNullPointerConstant(Context, 7836 Expr::NPC_ValueDependentIsNull)) { 7837 if (Diagnose || ConvertRHS) { 7838 CastKind Kind; 7839 CXXCastPath Path; 7840 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7841 /*IgnoreBaseAccess=*/false, Diagnose); 7842 if (ConvertRHS) 7843 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7844 } 7845 return Compatible; 7846 } 7847 7848 // This check seems unnatural, however it is necessary to ensure the proper 7849 // conversion of functions/arrays. If the conversion were done for all 7850 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7851 // expressions that suppress this implicit conversion (&, sizeof). 7852 // 7853 // Suppress this for references: C++ 8.5.3p5. 7854 if (!LHSType->isReferenceType()) { 7855 // FIXME: We potentially allocate here even if ConvertRHS is false. 7856 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7857 if (RHS.isInvalid()) 7858 return Incompatible; 7859 } 7860 7861 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7862 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7863 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7864 if (PDecl && !PDecl->hasDefinition()) { 7865 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7866 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7867 } 7868 } 7869 7870 CastKind Kind = CK_Invalid; 7871 Sema::AssignConvertType result = 7872 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7873 7874 // C99 6.5.16.1p2: The value of the right operand is converted to the 7875 // type of the assignment expression. 7876 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7877 // so that we can use references in built-in functions even in C. 7878 // The getNonReferenceType() call makes sure that the resulting expression 7879 // does not have reference type. 7880 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7881 QualType Ty = LHSType.getNonLValueExprType(Context); 7882 Expr *E = RHS.get(); 7883 7884 // Check for various Objective-C errors. If we are not reporting 7885 // diagnostics and just checking for errors, e.g., during overload 7886 // resolution, return Incompatible to indicate the failure. 7887 if (getLangOpts().ObjCAutoRefCount && 7888 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7889 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7890 if (!Diagnose) 7891 return Incompatible; 7892 } 7893 if (getLangOpts().ObjC1 && 7894 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7895 E->getType(), E, Diagnose) || 7896 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7897 if (!Diagnose) 7898 return Incompatible; 7899 // Replace the expression with a corrected version and continue so we 7900 // can find further errors. 7901 RHS = E; 7902 return Compatible; 7903 } 7904 7905 if (ConvertRHS) 7906 RHS = ImpCastExprToType(E, Ty, Kind); 7907 } 7908 return result; 7909 } 7910 7911 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7912 ExprResult &RHS) { 7913 Diag(Loc, diag::err_typecheck_invalid_operands) 7914 << LHS.get()->getType() << RHS.get()->getType() 7915 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7916 return QualType(); 7917 } 7918 7919 /// Try to convert a value of non-vector type to a vector type by converting 7920 /// the type to the element type of the vector and then performing a splat. 7921 /// If the language is OpenCL, we only use conversions that promote scalar 7922 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7923 /// for float->int. 7924 /// 7925 /// \param scalar - if non-null, actually perform the conversions 7926 /// \return true if the operation fails (but without diagnosing the failure) 7927 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7928 QualType scalarTy, 7929 QualType vectorEltTy, 7930 QualType vectorTy) { 7931 // The conversion to apply to the scalar before splatting it, 7932 // if necessary. 7933 CastKind scalarCast = CK_Invalid; 7934 7935 if (vectorEltTy->isIntegralType(S.Context)) { 7936 if (!scalarTy->isIntegralType(S.Context)) 7937 return true; 7938 if (S.getLangOpts().OpenCL && 7939 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7940 return true; 7941 scalarCast = CK_IntegralCast; 7942 } else if (vectorEltTy->isRealFloatingType()) { 7943 if (scalarTy->isRealFloatingType()) { 7944 if (S.getLangOpts().OpenCL && 7945 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7946 return true; 7947 scalarCast = CK_FloatingCast; 7948 } 7949 else if (scalarTy->isIntegralType(S.Context)) 7950 scalarCast = CK_IntegralToFloating; 7951 else 7952 return true; 7953 } else { 7954 return true; 7955 } 7956 7957 // Adjust scalar if desired. 7958 if (scalar) { 7959 if (scalarCast != CK_Invalid) 7960 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7961 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7962 } 7963 return false; 7964 } 7965 7966 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7967 SourceLocation Loc, bool IsCompAssign, 7968 bool AllowBothBool, 7969 bool AllowBoolConversions) { 7970 if (!IsCompAssign) { 7971 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7972 if (LHS.isInvalid()) 7973 return QualType(); 7974 } 7975 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7976 if (RHS.isInvalid()) 7977 return QualType(); 7978 7979 // For conversion purposes, we ignore any qualifiers. 7980 // For example, "const float" and "float" are equivalent. 7981 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7982 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7983 7984 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7985 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7986 assert(LHSVecType || RHSVecType); 7987 7988 // AltiVec-style "vector bool op vector bool" combinations are allowed 7989 // for some operators but not others. 7990 if (!AllowBothBool && 7991 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7992 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7993 return InvalidOperands(Loc, LHS, RHS); 7994 7995 // If the vector types are identical, return. 7996 if (Context.hasSameType(LHSType, RHSType)) 7997 return LHSType; 7998 7999 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8000 if (LHSVecType && RHSVecType && 8001 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8002 if (isa<ExtVectorType>(LHSVecType)) { 8003 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8004 return LHSType; 8005 } 8006 8007 if (!IsCompAssign) 8008 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8009 return RHSType; 8010 } 8011 8012 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8013 // can be mixed, with the result being the non-bool type. The non-bool 8014 // operand must have integer element type. 8015 if (AllowBoolConversions && LHSVecType && RHSVecType && 8016 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8017 (Context.getTypeSize(LHSVecType->getElementType()) == 8018 Context.getTypeSize(RHSVecType->getElementType()))) { 8019 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8020 LHSVecType->getElementType()->isIntegerType() && 8021 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8022 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8023 return LHSType; 8024 } 8025 if (!IsCompAssign && 8026 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8027 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8028 RHSVecType->getElementType()->isIntegerType()) { 8029 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8030 return RHSType; 8031 } 8032 } 8033 8034 // If there's an ext-vector type and a scalar, try to convert the scalar to 8035 // the vector element type and splat. 8036 // FIXME: this should also work for regular vector types as supported in GCC. 8037 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8038 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8039 LHSVecType->getElementType(), LHSType)) 8040 return LHSType; 8041 } 8042 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8043 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8044 LHSType, RHSVecType->getElementType(), 8045 RHSType)) 8046 return RHSType; 8047 } 8048 8049 // FIXME: The code below also handles convertion between vectors and 8050 // non-scalars, we should break this down into fine grained specific checks 8051 // and emit proper diagnostics. 8052 QualType VecType = LHSVecType ? LHSType : RHSType; 8053 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8054 QualType OtherType = LHSVecType ? RHSType : LHSType; 8055 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8056 if (isLaxVectorConversion(OtherType, VecType)) { 8057 // If we're allowing lax vector conversions, only the total (data) size 8058 // needs to be the same. For non compound assignment, if one of the types is 8059 // scalar, the result is always the vector type. 8060 if (!IsCompAssign) { 8061 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8062 return VecType; 8063 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8064 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8065 // type. Note that this is already done by non-compound assignments in 8066 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8067 // <1 x T> -> T. The result is also a vector type. 8068 } else if (OtherType->isExtVectorType() || 8069 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8070 ExprResult *RHSExpr = &RHS; 8071 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8072 return VecType; 8073 } 8074 } 8075 8076 // Okay, the expression is invalid. 8077 8078 // If there's a non-vector, non-real operand, diagnose that. 8079 if ((!RHSVecType && !RHSType->isRealType()) || 8080 (!LHSVecType && !LHSType->isRealType())) { 8081 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8082 << LHSType << RHSType 8083 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8084 return QualType(); 8085 } 8086 8087 // OpenCL V1.1 6.2.6.p1: 8088 // If the operands are of more than one vector type, then an error shall 8089 // occur. Implicit conversions between vector types are not permitted, per 8090 // section 6.2.1. 8091 if (getLangOpts().OpenCL && 8092 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8093 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8094 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8095 << RHSType; 8096 return QualType(); 8097 } 8098 8099 // Otherwise, use the generic diagnostic. 8100 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8101 << LHSType << RHSType 8102 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8103 return QualType(); 8104 } 8105 8106 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8107 // expression. These are mainly cases where the null pointer is used as an 8108 // integer instead of a pointer. 8109 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8110 SourceLocation Loc, bool IsCompare) { 8111 // The canonical way to check for a GNU null is with isNullPointerConstant, 8112 // but we use a bit of a hack here for speed; this is a relatively 8113 // hot path, and isNullPointerConstant is slow. 8114 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8115 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8116 8117 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8118 8119 // Avoid analyzing cases where the result will either be invalid (and 8120 // diagnosed as such) or entirely valid and not something to warn about. 8121 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8122 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8123 return; 8124 8125 // Comparison operations would not make sense with a null pointer no matter 8126 // what the other expression is. 8127 if (!IsCompare) { 8128 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8129 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8130 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8131 return; 8132 } 8133 8134 // The rest of the operations only make sense with a null pointer 8135 // if the other expression is a pointer. 8136 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8137 NonNullType->canDecayToPointerType()) 8138 return; 8139 8140 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8141 << LHSNull /* LHS is NULL */ << NonNullType 8142 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8143 } 8144 8145 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8146 ExprResult &RHS, 8147 SourceLocation Loc, bool IsDiv) { 8148 // Check for division/remainder by zero. 8149 llvm::APSInt RHSValue; 8150 if (!RHS.get()->isValueDependent() && 8151 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8152 S.DiagRuntimeBehavior(Loc, RHS.get(), 8153 S.PDiag(diag::warn_remainder_division_by_zero) 8154 << IsDiv << RHS.get()->getSourceRange()); 8155 } 8156 8157 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8158 SourceLocation Loc, 8159 bool IsCompAssign, bool IsDiv) { 8160 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8161 8162 if (LHS.get()->getType()->isVectorType() || 8163 RHS.get()->getType()->isVectorType()) 8164 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8165 /*AllowBothBool*/getLangOpts().AltiVec, 8166 /*AllowBoolConversions*/false); 8167 8168 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8169 if (LHS.isInvalid() || RHS.isInvalid()) 8170 return QualType(); 8171 8172 8173 if (compType.isNull() || !compType->isArithmeticType()) 8174 return InvalidOperands(Loc, LHS, RHS); 8175 if (IsDiv) 8176 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8177 return compType; 8178 } 8179 8180 QualType Sema::CheckRemainderOperands( 8181 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8182 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8183 8184 if (LHS.get()->getType()->isVectorType() || 8185 RHS.get()->getType()->isVectorType()) { 8186 if (LHS.get()->getType()->hasIntegerRepresentation() && 8187 RHS.get()->getType()->hasIntegerRepresentation()) 8188 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8189 /*AllowBothBool*/getLangOpts().AltiVec, 8190 /*AllowBoolConversions*/false); 8191 return InvalidOperands(Loc, LHS, RHS); 8192 } 8193 8194 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8195 if (LHS.isInvalid() || RHS.isInvalid()) 8196 return QualType(); 8197 8198 if (compType.isNull() || !compType->isIntegerType()) 8199 return InvalidOperands(Loc, LHS, RHS); 8200 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8201 return compType; 8202 } 8203 8204 /// \brief Diagnose invalid arithmetic on two void pointers. 8205 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8206 Expr *LHSExpr, Expr *RHSExpr) { 8207 S.Diag(Loc, S.getLangOpts().CPlusPlus 8208 ? diag::err_typecheck_pointer_arith_void_type 8209 : diag::ext_gnu_void_ptr) 8210 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8211 << RHSExpr->getSourceRange(); 8212 } 8213 8214 /// \brief Diagnose invalid arithmetic on a void pointer. 8215 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8216 Expr *Pointer) { 8217 S.Diag(Loc, S.getLangOpts().CPlusPlus 8218 ? diag::err_typecheck_pointer_arith_void_type 8219 : diag::ext_gnu_void_ptr) 8220 << 0 /* one pointer */ << Pointer->getSourceRange(); 8221 } 8222 8223 /// \brief Diagnose invalid arithmetic on two function pointers. 8224 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8225 Expr *LHS, Expr *RHS) { 8226 assert(LHS->getType()->isAnyPointerType()); 8227 assert(RHS->getType()->isAnyPointerType()); 8228 S.Diag(Loc, S.getLangOpts().CPlusPlus 8229 ? diag::err_typecheck_pointer_arith_function_type 8230 : diag::ext_gnu_ptr_func_arith) 8231 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8232 // We only show the second type if it differs from the first. 8233 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8234 RHS->getType()) 8235 << RHS->getType()->getPointeeType() 8236 << LHS->getSourceRange() << RHS->getSourceRange(); 8237 } 8238 8239 /// \brief Diagnose invalid arithmetic on a function pointer. 8240 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8241 Expr *Pointer) { 8242 assert(Pointer->getType()->isAnyPointerType()); 8243 S.Diag(Loc, S.getLangOpts().CPlusPlus 8244 ? diag::err_typecheck_pointer_arith_function_type 8245 : diag::ext_gnu_ptr_func_arith) 8246 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8247 << 0 /* one pointer, so only one type */ 8248 << Pointer->getSourceRange(); 8249 } 8250 8251 /// \brief Emit error if Operand is incomplete pointer type 8252 /// 8253 /// \returns True if pointer has incomplete type 8254 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8255 Expr *Operand) { 8256 QualType ResType = Operand->getType(); 8257 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8258 ResType = ResAtomicType->getValueType(); 8259 8260 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8261 QualType PointeeTy = ResType->getPointeeType(); 8262 return S.RequireCompleteType(Loc, PointeeTy, 8263 diag::err_typecheck_arithmetic_incomplete_type, 8264 PointeeTy, Operand->getSourceRange()); 8265 } 8266 8267 /// \brief Check the validity of an arithmetic pointer operand. 8268 /// 8269 /// If the operand has pointer type, this code will check for pointer types 8270 /// which are invalid in arithmetic operations. These will be diagnosed 8271 /// appropriately, including whether or not the use is supported as an 8272 /// extension. 8273 /// 8274 /// \returns True when the operand is valid to use (even if as an extension). 8275 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8276 Expr *Operand) { 8277 QualType ResType = Operand->getType(); 8278 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8279 ResType = ResAtomicType->getValueType(); 8280 8281 if (!ResType->isAnyPointerType()) return true; 8282 8283 QualType PointeeTy = ResType->getPointeeType(); 8284 if (PointeeTy->isVoidType()) { 8285 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8286 return !S.getLangOpts().CPlusPlus; 8287 } 8288 if (PointeeTy->isFunctionType()) { 8289 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8290 return !S.getLangOpts().CPlusPlus; 8291 } 8292 8293 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8294 8295 return true; 8296 } 8297 8298 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8299 /// operands. 8300 /// 8301 /// This routine will diagnose any invalid arithmetic on pointer operands much 8302 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8303 /// for emitting a single diagnostic even for operations where both LHS and RHS 8304 /// are (potentially problematic) pointers. 8305 /// 8306 /// \returns True when the operand is valid to use (even if as an extension). 8307 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8308 Expr *LHSExpr, Expr *RHSExpr) { 8309 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8310 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8311 if (!isLHSPointer && !isRHSPointer) return true; 8312 8313 QualType LHSPointeeTy, RHSPointeeTy; 8314 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8315 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8316 8317 // if both are pointers check if operation is valid wrt address spaces 8318 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8319 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8320 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8321 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8322 S.Diag(Loc, 8323 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8324 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8325 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8326 return false; 8327 } 8328 } 8329 8330 // Check for arithmetic on pointers to incomplete types. 8331 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8332 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8333 if (isLHSVoidPtr || isRHSVoidPtr) { 8334 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8335 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8336 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8337 8338 return !S.getLangOpts().CPlusPlus; 8339 } 8340 8341 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8342 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8343 if (isLHSFuncPtr || isRHSFuncPtr) { 8344 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8345 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8346 RHSExpr); 8347 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8348 8349 return !S.getLangOpts().CPlusPlus; 8350 } 8351 8352 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8353 return false; 8354 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8355 return false; 8356 8357 return true; 8358 } 8359 8360 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8361 /// literal. 8362 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8363 Expr *LHSExpr, Expr *RHSExpr) { 8364 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8365 Expr* IndexExpr = RHSExpr; 8366 if (!StrExpr) { 8367 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8368 IndexExpr = LHSExpr; 8369 } 8370 8371 bool IsStringPlusInt = StrExpr && 8372 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8373 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8374 return; 8375 8376 llvm::APSInt index; 8377 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8378 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8379 if (index.isNonNegative() && 8380 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8381 index.isUnsigned())) 8382 return; 8383 } 8384 8385 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8386 Self.Diag(OpLoc, diag::warn_string_plus_int) 8387 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8388 8389 // Only print a fixit for "str" + int, not for int + "str". 8390 if (IndexExpr == RHSExpr) { 8391 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8392 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8393 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8394 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8395 << FixItHint::CreateInsertion(EndLoc, "]"); 8396 } else 8397 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8398 } 8399 8400 /// \brief Emit a warning when adding a char literal to a string. 8401 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8402 Expr *LHSExpr, Expr *RHSExpr) { 8403 const Expr *StringRefExpr = LHSExpr; 8404 const CharacterLiteral *CharExpr = 8405 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8406 8407 if (!CharExpr) { 8408 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8409 StringRefExpr = RHSExpr; 8410 } 8411 8412 if (!CharExpr || !StringRefExpr) 8413 return; 8414 8415 const QualType StringType = StringRefExpr->getType(); 8416 8417 // Return if not a PointerType. 8418 if (!StringType->isAnyPointerType()) 8419 return; 8420 8421 // Return if not a CharacterType. 8422 if (!StringType->getPointeeType()->isAnyCharacterType()) 8423 return; 8424 8425 ASTContext &Ctx = Self.getASTContext(); 8426 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8427 8428 const QualType CharType = CharExpr->getType(); 8429 if (!CharType->isAnyCharacterType() && 8430 CharType->isIntegerType() && 8431 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8432 Self.Diag(OpLoc, diag::warn_string_plus_char) 8433 << DiagRange << Ctx.CharTy; 8434 } else { 8435 Self.Diag(OpLoc, diag::warn_string_plus_char) 8436 << DiagRange << CharExpr->getType(); 8437 } 8438 8439 // Only print a fixit for str + char, not for char + str. 8440 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8441 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8442 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8443 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8444 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8445 << FixItHint::CreateInsertion(EndLoc, "]"); 8446 } else { 8447 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8448 } 8449 } 8450 8451 /// \brief Emit error when two pointers are incompatible. 8452 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8453 Expr *LHSExpr, Expr *RHSExpr) { 8454 assert(LHSExpr->getType()->isAnyPointerType()); 8455 assert(RHSExpr->getType()->isAnyPointerType()); 8456 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8457 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8458 << RHSExpr->getSourceRange(); 8459 } 8460 8461 // C99 6.5.6 8462 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8463 SourceLocation Loc, BinaryOperatorKind Opc, 8464 QualType* CompLHSTy) { 8465 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8466 8467 if (LHS.get()->getType()->isVectorType() || 8468 RHS.get()->getType()->isVectorType()) { 8469 QualType compType = CheckVectorOperands( 8470 LHS, RHS, Loc, CompLHSTy, 8471 /*AllowBothBool*/getLangOpts().AltiVec, 8472 /*AllowBoolConversions*/getLangOpts().ZVector); 8473 if (CompLHSTy) *CompLHSTy = compType; 8474 return compType; 8475 } 8476 8477 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8478 if (LHS.isInvalid() || RHS.isInvalid()) 8479 return QualType(); 8480 8481 // Diagnose "string literal" '+' int and string '+' "char literal". 8482 if (Opc == BO_Add) { 8483 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8484 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8485 } 8486 8487 // handle the common case first (both operands are arithmetic). 8488 if (!compType.isNull() && compType->isArithmeticType()) { 8489 if (CompLHSTy) *CompLHSTy = compType; 8490 return compType; 8491 } 8492 8493 // Type-checking. Ultimately the pointer's going to be in PExp; 8494 // note that we bias towards the LHS being the pointer. 8495 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8496 8497 bool isObjCPointer; 8498 if (PExp->getType()->isPointerType()) { 8499 isObjCPointer = false; 8500 } else if (PExp->getType()->isObjCObjectPointerType()) { 8501 isObjCPointer = true; 8502 } else { 8503 std::swap(PExp, IExp); 8504 if (PExp->getType()->isPointerType()) { 8505 isObjCPointer = false; 8506 } else if (PExp->getType()->isObjCObjectPointerType()) { 8507 isObjCPointer = true; 8508 } else { 8509 return InvalidOperands(Loc, LHS, RHS); 8510 } 8511 } 8512 assert(PExp->getType()->isAnyPointerType()); 8513 8514 if (!IExp->getType()->isIntegerType()) 8515 return InvalidOperands(Loc, LHS, RHS); 8516 8517 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8518 return QualType(); 8519 8520 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8521 return QualType(); 8522 8523 // Check array bounds for pointer arithemtic 8524 CheckArrayAccess(PExp, IExp); 8525 8526 if (CompLHSTy) { 8527 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8528 if (LHSTy.isNull()) { 8529 LHSTy = LHS.get()->getType(); 8530 if (LHSTy->isPromotableIntegerType()) 8531 LHSTy = Context.getPromotedIntegerType(LHSTy); 8532 } 8533 *CompLHSTy = LHSTy; 8534 } 8535 8536 return PExp->getType(); 8537 } 8538 8539 // C99 6.5.6 8540 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8541 SourceLocation Loc, 8542 QualType* CompLHSTy) { 8543 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8544 8545 if (LHS.get()->getType()->isVectorType() || 8546 RHS.get()->getType()->isVectorType()) { 8547 QualType compType = CheckVectorOperands( 8548 LHS, RHS, Loc, CompLHSTy, 8549 /*AllowBothBool*/getLangOpts().AltiVec, 8550 /*AllowBoolConversions*/getLangOpts().ZVector); 8551 if (CompLHSTy) *CompLHSTy = compType; 8552 return compType; 8553 } 8554 8555 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8556 if (LHS.isInvalid() || RHS.isInvalid()) 8557 return QualType(); 8558 8559 // Enforce type constraints: C99 6.5.6p3. 8560 8561 // Handle the common case first (both operands are arithmetic). 8562 if (!compType.isNull() && compType->isArithmeticType()) { 8563 if (CompLHSTy) *CompLHSTy = compType; 8564 return compType; 8565 } 8566 8567 // Either ptr - int or ptr - ptr. 8568 if (LHS.get()->getType()->isAnyPointerType()) { 8569 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8570 8571 // Diagnose bad cases where we step over interface counts. 8572 if (LHS.get()->getType()->isObjCObjectPointerType() && 8573 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8574 return QualType(); 8575 8576 // The result type of a pointer-int computation is the pointer type. 8577 if (RHS.get()->getType()->isIntegerType()) { 8578 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8579 return QualType(); 8580 8581 // Check array bounds for pointer arithemtic 8582 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8583 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8584 8585 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8586 return LHS.get()->getType(); 8587 } 8588 8589 // Handle pointer-pointer subtractions. 8590 if (const PointerType *RHSPTy 8591 = RHS.get()->getType()->getAs<PointerType>()) { 8592 QualType rpointee = RHSPTy->getPointeeType(); 8593 8594 if (getLangOpts().CPlusPlus) { 8595 // Pointee types must be the same: C++ [expr.add] 8596 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8597 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8598 } 8599 } else { 8600 // Pointee types must be compatible C99 6.5.6p3 8601 if (!Context.typesAreCompatible( 8602 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8603 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8604 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8605 return QualType(); 8606 } 8607 } 8608 8609 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8610 LHS.get(), RHS.get())) 8611 return QualType(); 8612 8613 // The pointee type may have zero size. As an extension, a structure or 8614 // union may have zero size or an array may have zero length. In this 8615 // case subtraction does not make sense. 8616 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8617 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8618 if (ElementSize.isZero()) { 8619 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8620 << rpointee.getUnqualifiedType() 8621 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8622 } 8623 } 8624 8625 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8626 return Context.getPointerDiffType(); 8627 } 8628 } 8629 8630 return InvalidOperands(Loc, LHS, RHS); 8631 } 8632 8633 static bool isScopedEnumerationType(QualType T) { 8634 if (const EnumType *ET = T->getAs<EnumType>()) 8635 return ET->getDecl()->isScoped(); 8636 return false; 8637 } 8638 8639 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8640 SourceLocation Loc, BinaryOperatorKind Opc, 8641 QualType LHSType) { 8642 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8643 // so skip remaining warnings as we don't want to modify values within Sema. 8644 if (S.getLangOpts().OpenCL) 8645 return; 8646 8647 llvm::APSInt Right; 8648 // Check right/shifter operand 8649 if (RHS.get()->isValueDependent() || 8650 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8651 return; 8652 8653 if (Right.isNegative()) { 8654 S.DiagRuntimeBehavior(Loc, RHS.get(), 8655 S.PDiag(diag::warn_shift_negative) 8656 << RHS.get()->getSourceRange()); 8657 return; 8658 } 8659 llvm::APInt LeftBits(Right.getBitWidth(), 8660 S.Context.getTypeSize(LHS.get()->getType())); 8661 if (Right.uge(LeftBits)) { 8662 S.DiagRuntimeBehavior(Loc, RHS.get(), 8663 S.PDiag(diag::warn_shift_gt_typewidth) 8664 << RHS.get()->getSourceRange()); 8665 return; 8666 } 8667 if (Opc != BO_Shl) 8668 return; 8669 8670 // When left shifting an ICE which is signed, we can check for overflow which 8671 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8672 // integers have defined behavior modulo one more than the maximum value 8673 // representable in the result type, so never warn for those. 8674 llvm::APSInt Left; 8675 if (LHS.get()->isValueDependent() || 8676 LHSType->hasUnsignedIntegerRepresentation() || 8677 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8678 return; 8679 8680 // If LHS does not have a signed type and non-negative value 8681 // then, the behavior is undefined. Warn about it. 8682 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8683 S.DiagRuntimeBehavior(Loc, LHS.get(), 8684 S.PDiag(diag::warn_shift_lhs_negative) 8685 << LHS.get()->getSourceRange()); 8686 return; 8687 } 8688 8689 llvm::APInt ResultBits = 8690 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8691 if (LeftBits.uge(ResultBits)) 8692 return; 8693 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8694 Result = Result.shl(Right); 8695 8696 // Print the bit representation of the signed integer as an unsigned 8697 // hexadecimal number. 8698 SmallString<40> HexResult; 8699 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8700 8701 // If we are only missing a sign bit, this is less likely to result in actual 8702 // bugs -- if the result is cast back to an unsigned type, it will have the 8703 // expected value. Thus we place this behind a different warning that can be 8704 // turned off separately if needed. 8705 if (LeftBits == ResultBits - 1) { 8706 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8707 << HexResult << LHSType 8708 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8709 return; 8710 } 8711 8712 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8713 << HexResult.str() << Result.getMinSignedBits() << LHSType 8714 << Left.getBitWidth() << LHS.get()->getSourceRange() 8715 << RHS.get()->getSourceRange(); 8716 } 8717 8718 /// \brief Return the resulting type when a vector is shifted 8719 /// by a scalar or vector shift amount. 8720 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8721 SourceLocation Loc, bool IsCompAssign) { 8722 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8723 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8724 !LHS.get()->getType()->isVectorType()) { 8725 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8726 << RHS.get()->getType() << LHS.get()->getType() 8727 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8728 return QualType(); 8729 } 8730 8731 if (!IsCompAssign) { 8732 LHS = S.UsualUnaryConversions(LHS.get()); 8733 if (LHS.isInvalid()) return QualType(); 8734 } 8735 8736 RHS = S.UsualUnaryConversions(RHS.get()); 8737 if (RHS.isInvalid()) return QualType(); 8738 8739 QualType LHSType = LHS.get()->getType(); 8740 // Note that LHS might be a scalar because the routine calls not only in 8741 // OpenCL case. 8742 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8743 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8744 8745 // Note that RHS might not be a vector. 8746 QualType RHSType = RHS.get()->getType(); 8747 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8748 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8749 8750 // The operands need to be integers. 8751 if (!LHSEleType->isIntegerType()) { 8752 S.Diag(Loc, diag::err_typecheck_expect_int) 8753 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8754 return QualType(); 8755 } 8756 8757 if (!RHSEleType->isIntegerType()) { 8758 S.Diag(Loc, diag::err_typecheck_expect_int) 8759 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8760 return QualType(); 8761 } 8762 8763 if (!LHSVecTy) { 8764 assert(RHSVecTy); 8765 if (IsCompAssign) 8766 return RHSType; 8767 if (LHSEleType != RHSEleType) { 8768 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8769 LHSEleType = RHSEleType; 8770 } 8771 QualType VecTy = 8772 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8773 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8774 LHSType = VecTy; 8775 } else if (RHSVecTy) { 8776 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8777 // are applied component-wise. So if RHS is a vector, then ensure 8778 // that the number of elements is the same as LHS... 8779 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8780 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8781 << LHS.get()->getType() << RHS.get()->getType() 8782 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8783 return QualType(); 8784 } 8785 } else { 8786 // ...else expand RHS to match the number of elements in LHS. 8787 QualType VecTy = 8788 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8789 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8790 } 8791 8792 return LHSType; 8793 } 8794 8795 // C99 6.5.7 8796 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8797 SourceLocation Loc, BinaryOperatorKind Opc, 8798 bool IsCompAssign) { 8799 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8800 8801 // Vector shifts promote their scalar inputs to vector type. 8802 if (LHS.get()->getType()->isVectorType() || 8803 RHS.get()->getType()->isVectorType()) { 8804 if (LangOpts.ZVector) { 8805 // The shift operators for the z vector extensions work basically 8806 // like general shifts, except that neither the LHS nor the RHS is 8807 // allowed to be a "vector bool". 8808 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8809 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8810 return InvalidOperands(Loc, LHS, RHS); 8811 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8812 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8813 return InvalidOperands(Loc, LHS, RHS); 8814 } 8815 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8816 } 8817 8818 // Shifts don't perform usual arithmetic conversions, they just do integer 8819 // promotions on each operand. C99 6.5.7p3 8820 8821 // For the LHS, do usual unary conversions, but then reset them away 8822 // if this is a compound assignment. 8823 ExprResult OldLHS = LHS; 8824 LHS = UsualUnaryConversions(LHS.get()); 8825 if (LHS.isInvalid()) 8826 return QualType(); 8827 QualType LHSType = LHS.get()->getType(); 8828 if (IsCompAssign) LHS = OldLHS; 8829 8830 // The RHS is simpler. 8831 RHS = UsualUnaryConversions(RHS.get()); 8832 if (RHS.isInvalid()) 8833 return QualType(); 8834 QualType RHSType = RHS.get()->getType(); 8835 8836 // C99 6.5.7p2: Each of the operands shall have integer type. 8837 if (!LHSType->hasIntegerRepresentation() || 8838 !RHSType->hasIntegerRepresentation()) 8839 return InvalidOperands(Loc, LHS, RHS); 8840 8841 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8842 // hasIntegerRepresentation() above instead of this. 8843 if (isScopedEnumerationType(LHSType) || 8844 isScopedEnumerationType(RHSType)) { 8845 return InvalidOperands(Loc, LHS, RHS); 8846 } 8847 // Sanity-check shift operands 8848 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8849 8850 // "The type of the result is that of the promoted left operand." 8851 return LHSType; 8852 } 8853 8854 static bool IsWithinTemplateSpecialization(Decl *D) { 8855 if (DeclContext *DC = D->getDeclContext()) { 8856 if (isa<ClassTemplateSpecializationDecl>(DC)) 8857 return true; 8858 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8859 return FD->isFunctionTemplateSpecialization(); 8860 } 8861 return false; 8862 } 8863 8864 /// If two different enums are compared, raise a warning. 8865 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8866 Expr *RHS) { 8867 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8868 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8869 8870 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8871 if (!LHSEnumType) 8872 return; 8873 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8874 if (!RHSEnumType) 8875 return; 8876 8877 // Ignore anonymous enums. 8878 if (!LHSEnumType->getDecl()->getIdentifier()) 8879 return; 8880 if (!RHSEnumType->getDecl()->getIdentifier()) 8881 return; 8882 8883 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8884 return; 8885 8886 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8887 << LHSStrippedType << RHSStrippedType 8888 << LHS->getSourceRange() << RHS->getSourceRange(); 8889 } 8890 8891 /// \brief Diagnose bad pointer comparisons. 8892 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8893 ExprResult &LHS, ExprResult &RHS, 8894 bool IsError) { 8895 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8896 : diag::ext_typecheck_comparison_of_distinct_pointers) 8897 << LHS.get()->getType() << RHS.get()->getType() 8898 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8899 } 8900 8901 /// \brief Returns false if the pointers are converted to a composite type, 8902 /// true otherwise. 8903 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8904 ExprResult &LHS, ExprResult &RHS) { 8905 // C++ [expr.rel]p2: 8906 // [...] Pointer conversions (4.10) and qualification 8907 // conversions (4.4) are performed on pointer operands (or on 8908 // a pointer operand and a null pointer constant) to bring 8909 // them to their composite pointer type. [...] 8910 // 8911 // C++ [expr.eq]p1 uses the same notion for (in)equality 8912 // comparisons of pointers. 8913 8914 // C++ [expr.eq]p2: 8915 // In addition, pointers to members can be compared, or a pointer to 8916 // member and a null pointer constant. Pointer to member conversions 8917 // (4.11) and qualification conversions (4.4) are performed to bring 8918 // them to a common type. If one operand is a null pointer constant, 8919 // the common type is the type of the other operand. Otherwise, the 8920 // common type is a pointer to member type similar (4.4) to the type 8921 // of one of the operands, with a cv-qualification signature (4.4) 8922 // that is the union of the cv-qualification signatures of the operand 8923 // types. 8924 8925 QualType LHSType = LHS.get()->getType(); 8926 QualType RHSType = RHS.get()->getType(); 8927 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8928 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8929 8930 bool NonStandardCompositeType = false; 8931 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8932 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8933 if (T.isNull()) { 8934 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8935 return true; 8936 } 8937 8938 if (NonStandardCompositeType) 8939 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8940 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8941 << RHS.get()->getSourceRange(); 8942 8943 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8944 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8945 return false; 8946 } 8947 8948 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8949 ExprResult &LHS, 8950 ExprResult &RHS, 8951 bool IsError) { 8952 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8953 : diag::ext_typecheck_comparison_of_fptr_to_void) 8954 << LHS.get()->getType() << RHS.get()->getType() 8955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8956 } 8957 8958 static bool isObjCObjectLiteral(ExprResult &E) { 8959 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8960 case Stmt::ObjCArrayLiteralClass: 8961 case Stmt::ObjCDictionaryLiteralClass: 8962 case Stmt::ObjCStringLiteralClass: 8963 case Stmt::ObjCBoxedExprClass: 8964 return true; 8965 default: 8966 // Note that ObjCBoolLiteral is NOT an object literal! 8967 return false; 8968 } 8969 } 8970 8971 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8972 const ObjCObjectPointerType *Type = 8973 LHS->getType()->getAs<ObjCObjectPointerType>(); 8974 8975 // If this is not actually an Objective-C object, bail out. 8976 if (!Type) 8977 return false; 8978 8979 // Get the LHS object's interface type. 8980 QualType InterfaceType = Type->getPointeeType(); 8981 8982 // If the RHS isn't an Objective-C object, bail out. 8983 if (!RHS->getType()->isObjCObjectPointerType()) 8984 return false; 8985 8986 // Try to find the -isEqual: method. 8987 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8988 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8989 InterfaceType, 8990 /*instance=*/true); 8991 if (!Method) { 8992 if (Type->isObjCIdType()) { 8993 // For 'id', just check the global pool. 8994 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8995 /*receiverId=*/true); 8996 } else { 8997 // Check protocols. 8998 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8999 /*instance=*/true); 9000 } 9001 } 9002 9003 if (!Method) 9004 return false; 9005 9006 QualType T = Method->parameters()[0]->getType(); 9007 if (!T->isObjCObjectPointerType()) 9008 return false; 9009 9010 QualType R = Method->getReturnType(); 9011 if (!R->isScalarType()) 9012 return false; 9013 9014 return true; 9015 } 9016 9017 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9018 FromE = FromE->IgnoreParenImpCasts(); 9019 switch (FromE->getStmtClass()) { 9020 default: 9021 break; 9022 case Stmt::ObjCStringLiteralClass: 9023 // "string literal" 9024 return LK_String; 9025 case Stmt::ObjCArrayLiteralClass: 9026 // "array literal" 9027 return LK_Array; 9028 case Stmt::ObjCDictionaryLiteralClass: 9029 // "dictionary literal" 9030 return LK_Dictionary; 9031 case Stmt::BlockExprClass: 9032 return LK_Block; 9033 case Stmt::ObjCBoxedExprClass: { 9034 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9035 switch (Inner->getStmtClass()) { 9036 case Stmt::IntegerLiteralClass: 9037 case Stmt::FloatingLiteralClass: 9038 case Stmt::CharacterLiteralClass: 9039 case Stmt::ObjCBoolLiteralExprClass: 9040 case Stmt::CXXBoolLiteralExprClass: 9041 // "numeric literal" 9042 return LK_Numeric; 9043 case Stmt::ImplicitCastExprClass: { 9044 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9045 // Boolean literals can be represented by implicit casts. 9046 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9047 return LK_Numeric; 9048 break; 9049 } 9050 default: 9051 break; 9052 } 9053 return LK_Boxed; 9054 } 9055 } 9056 return LK_None; 9057 } 9058 9059 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9060 ExprResult &LHS, ExprResult &RHS, 9061 BinaryOperator::Opcode Opc){ 9062 Expr *Literal; 9063 Expr *Other; 9064 if (isObjCObjectLiteral(LHS)) { 9065 Literal = LHS.get(); 9066 Other = RHS.get(); 9067 } else { 9068 Literal = RHS.get(); 9069 Other = LHS.get(); 9070 } 9071 9072 // Don't warn on comparisons against nil. 9073 Other = Other->IgnoreParenCasts(); 9074 if (Other->isNullPointerConstant(S.getASTContext(), 9075 Expr::NPC_ValueDependentIsNotNull)) 9076 return; 9077 9078 // This should be kept in sync with warn_objc_literal_comparison. 9079 // LK_String should always be after the other literals, since it has its own 9080 // warning flag. 9081 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9082 assert(LiteralKind != Sema::LK_Block); 9083 if (LiteralKind == Sema::LK_None) { 9084 llvm_unreachable("Unknown Objective-C object literal kind"); 9085 } 9086 9087 if (LiteralKind == Sema::LK_String) 9088 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9089 << Literal->getSourceRange(); 9090 else 9091 S.Diag(Loc, diag::warn_objc_literal_comparison) 9092 << LiteralKind << Literal->getSourceRange(); 9093 9094 if (BinaryOperator::isEqualityOp(Opc) && 9095 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9096 SourceLocation Start = LHS.get()->getLocStart(); 9097 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9098 CharSourceRange OpRange = 9099 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9100 9101 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9102 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9103 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9104 << FixItHint::CreateInsertion(End, "]"); 9105 } 9106 } 9107 9108 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 9109 ExprResult &RHS, 9110 SourceLocation Loc, 9111 BinaryOperatorKind Opc) { 9112 // Check that left hand side is !something. 9113 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9114 if (!UO || UO->getOpcode() != UO_LNot) return; 9115 9116 // Only check if the right hand side is non-bool arithmetic type. 9117 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9118 9119 // Make sure that the something in !something is not bool. 9120 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9121 if (SubExpr->isKnownToHaveBooleanValue()) return; 9122 9123 // Emit warning. 9124 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 9125 << Loc; 9126 9127 // First note suggest !(x < y) 9128 SourceLocation FirstOpen = SubExpr->getLocStart(); 9129 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9130 FirstClose = S.getLocForEndOfToken(FirstClose); 9131 if (FirstClose.isInvalid()) 9132 FirstOpen = SourceLocation(); 9133 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9134 << FixItHint::CreateInsertion(FirstOpen, "(") 9135 << FixItHint::CreateInsertion(FirstClose, ")"); 9136 9137 // Second note suggests (!x) < y 9138 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9139 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9140 SecondClose = S.getLocForEndOfToken(SecondClose); 9141 if (SecondClose.isInvalid()) 9142 SecondOpen = SourceLocation(); 9143 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9144 << FixItHint::CreateInsertion(SecondOpen, "(") 9145 << FixItHint::CreateInsertion(SecondClose, ")"); 9146 } 9147 9148 // Get the decl for a simple expression: a reference to a variable, 9149 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9150 static ValueDecl *getCompareDecl(Expr *E) { 9151 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9152 return DR->getDecl(); 9153 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9154 if (Ivar->isFreeIvar()) 9155 return Ivar->getDecl(); 9156 } 9157 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9158 if (Mem->isImplicitAccess()) 9159 return Mem->getMemberDecl(); 9160 } 9161 return nullptr; 9162 } 9163 9164 // C99 6.5.8, C++ [expr.rel] 9165 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9166 SourceLocation Loc, BinaryOperatorKind Opc, 9167 bool IsRelational) { 9168 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9169 9170 // Handle vector comparisons separately. 9171 if (LHS.get()->getType()->isVectorType() || 9172 RHS.get()->getType()->isVectorType()) 9173 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9174 9175 QualType LHSType = LHS.get()->getType(); 9176 QualType RHSType = RHS.get()->getType(); 9177 9178 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9179 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9180 9181 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9182 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9183 9184 if (!LHSType->hasFloatingRepresentation() && 9185 !(LHSType->isBlockPointerType() && IsRelational) && 9186 !LHS.get()->getLocStart().isMacroID() && 9187 !RHS.get()->getLocStart().isMacroID() && 9188 ActiveTemplateInstantiations.empty()) { 9189 // For non-floating point types, check for self-comparisons of the form 9190 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9191 // often indicate logic errors in the program. 9192 // 9193 // NOTE: Don't warn about comparison expressions resulting from macro 9194 // expansion. Also don't warn about comparisons which are only self 9195 // comparisons within a template specialization. The warnings should catch 9196 // obvious cases in the definition of the template anyways. The idea is to 9197 // warn when the typed comparison operator will always evaluate to the same 9198 // result. 9199 ValueDecl *DL = getCompareDecl(LHSStripped); 9200 ValueDecl *DR = getCompareDecl(RHSStripped); 9201 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9202 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9203 << 0 // self- 9204 << (Opc == BO_EQ 9205 || Opc == BO_LE 9206 || Opc == BO_GE)); 9207 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9208 !DL->getType()->isReferenceType() && 9209 !DR->getType()->isReferenceType()) { 9210 // what is it always going to eval to? 9211 char always_evals_to; 9212 switch(Opc) { 9213 case BO_EQ: // e.g. array1 == array2 9214 always_evals_to = 0; // false 9215 break; 9216 case BO_NE: // e.g. array1 != array2 9217 always_evals_to = 1; // true 9218 break; 9219 default: 9220 // best we can say is 'a constant' 9221 always_evals_to = 2; // e.g. array1 <= array2 9222 break; 9223 } 9224 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9225 << 1 // array 9226 << always_evals_to); 9227 } 9228 9229 if (isa<CastExpr>(LHSStripped)) 9230 LHSStripped = LHSStripped->IgnoreParenCasts(); 9231 if (isa<CastExpr>(RHSStripped)) 9232 RHSStripped = RHSStripped->IgnoreParenCasts(); 9233 9234 // Warn about comparisons against a string constant (unless the other 9235 // operand is null), the user probably wants strcmp. 9236 Expr *literalString = nullptr; 9237 Expr *literalStringStripped = nullptr; 9238 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9239 !RHSStripped->isNullPointerConstant(Context, 9240 Expr::NPC_ValueDependentIsNull)) { 9241 literalString = LHS.get(); 9242 literalStringStripped = LHSStripped; 9243 } else if ((isa<StringLiteral>(RHSStripped) || 9244 isa<ObjCEncodeExpr>(RHSStripped)) && 9245 !LHSStripped->isNullPointerConstant(Context, 9246 Expr::NPC_ValueDependentIsNull)) { 9247 literalString = RHS.get(); 9248 literalStringStripped = RHSStripped; 9249 } 9250 9251 if (literalString) { 9252 DiagRuntimeBehavior(Loc, nullptr, 9253 PDiag(diag::warn_stringcompare) 9254 << isa<ObjCEncodeExpr>(literalStringStripped) 9255 << literalString->getSourceRange()); 9256 } 9257 } 9258 9259 // C99 6.5.8p3 / C99 6.5.9p4 9260 UsualArithmeticConversions(LHS, RHS); 9261 if (LHS.isInvalid() || RHS.isInvalid()) 9262 return QualType(); 9263 9264 LHSType = LHS.get()->getType(); 9265 RHSType = RHS.get()->getType(); 9266 9267 // The result of comparisons is 'bool' in C++, 'int' in C. 9268 QualType ResultTy = Context.getLogicalOperationType(); 9269 9270 if (IsRelational) { 9271 if (LHSType->isRealType() && RHSType->isRealType()) 9272 return ResultTy; 9273 } else { 9274 // Check for comparisons of floating point operands using != and ==. 9275 if (LHSType->hasFloatingRepresentation()) 9276 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9277 9278 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9279 return ResultTy; 9280 } 9281 9282 const Expr::NullPointerConstantKind LHSNullKind = 9283 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9284 const Expr::NullPointerConstantKind RHSNullKind = 9285 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9286 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9287 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9288 9289 if (!IsRelational && LHSIsNull != RHSIsNull) { 9290 bool IsEquality = Opc == BO_EQ; 9291 if (RHSIsNull) 9292 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9293 RHS.get()->getSourceRange()); 9294 else 9295 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9296 LHS.get()->getSourceRange()); 9297 } 9298 9299 // All of the following pointer-related warnings are GCC extensions, except 9300 // when handling null pointer constants. 9301 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9302 QualType LCanPointeeTy = 9303 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9304 QualType RCanPointeeTy = 9305 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9306 9307 if (getLangOpts().CPlusPlus) { 9308 if (LCanPointeeTy == RCanPointeeTy) 9309 return ResultTy; 9310 if (!IsRelational && 9311 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9312 // Valid unless comparison between non-null pointer and function pointer 9313 // This is a gcc extension compatibility comparison. 9314 // In a SFINAE context, we treat this as a hard error to maintain 9315 // conformance with the C++ standard. 9316 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9317 && !LHSIsNull && !RHSIsNull) { 9318 diagnoseFunctionPointerToVoidComparison( 9319 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9320 9321 if (isSFINAEContext()) 9322 return QualType(); 9323 9324 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9325 return ResultTy; 9326 } 9327 } 9328 9329 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9330 return QualType(); 9331 else 9332 return ResultTy; 9333 } 9334 // C99 6.5.9p2 and C99 6.5.8p2 9335 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9336 RCanPointeeTy.getUnqualifiedType())) { 9337 // Valid unless a relational comparison of function pointers 9338 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9339 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9340 << LHSType << RHSType << LHS.get()->getSourceRange() 9341 << RHS.get()->getSourceRange(); 9342 } 9343 } else if (!IsRelational && 9344 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9345 // Valid unless comparison between non-null pointer and function pointer 9346 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9347 && !LHSIsNull && !RHSIsNull) 9348 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9349 /*isError*/false); 9350 } else { 9351 // Invalid 9352 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9353 } 9354 if (LCanPointeeTy != RCanPointeeTy) { 9355 // Treat NULL constant as a special case in OpenCL. 9356 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9357 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9358 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9359 Diag(Loc, 9360 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9361 << LHSType << RHSType << 0 /* comparison */ 9362 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9363 } 9364 } 9365 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9366 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9367 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9368 : CK_BitCast; 9369 if (LHSIsNull && !RHSIsNull) 9370 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9371 else 9372 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9373 } 9374 return ResultTy; 9375 } 9376 9377 if (getLangOpts().CPlusPlus) { 9378 // Comparison of nullptr_t with itself. 9379 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9380 return ResultTy; 9381 9382 // Comparison of pointers with null pointer constants and equality 9383 // comparisons of member pointers to null pointer constants. 9384 if (RHSIsNull && 9385 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9386 (!IsRelational && 9387 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9388 RHS = ImpCastExprToType(RHS.get(), LHSType, 9389 LHSType->isMemberPointerType() 9390 ? CK_NullToMemberPointer 9391 : CK_NullToPointer); 9392 return ResultTy; 9393 } 9394 if (LHSIsNull && 9395 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9396 (!IsRelational && 9397 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9398 LHS = ImpCastExprToType(LHS.get(), RHSType, 9399 RHSType->isMemberPointerType() 9400 ? CK_NullToMemberPointer 9401 : CK_NullToPointer); 9402 return ResultTy; 9403 } 9404 9405 // Comparison of member pointers. 9406 if (!IsRelational && 9407 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9408 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9409 return QualType(); 9410 else 9411 return ResultTy; 9412 } 9413 9414 // Handle scoped enumeration types specifically, since they don't promote 9415 // to integers. 9416 if (LHS.get()->getType()->isEnumeralType() && 9417 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9418 RHS.get()->getType())) 9419 return ResultTy; 9420 } 9421 9422 // Handle block pointer types. 9423 if (!IsRelational && LHSType->isBlockPointerType() && 9424 RHSType->isBlockPointerType()) { 9425 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9426 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9427 9428 if (!LHSIsNull && !RHSIsNull && 9429 !Context.typesAreCompatible(lpointee, rpointee)) { 9430 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9431 << LHSType << RHSType << LHS.get()->getSourceRange() 9432 << RHS.get()->getSourceRange(); 9433 } 9434 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9435 return ResultTy; 9436 } 9437 9438 // Allow block pointers to be compared with null pointer constants. 9439 if (!IsRelational 9440 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9441 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9442 if (!LHSIsNull && !RHSIsNull) { 9443 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9444 ->getPointeeType()->isVoidType()) 9445 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9446 ->getPointeeType()->isVoidType()))) 9447 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9448 << LHSType << RHSType << LHS.get()->getSourceRange() 9449 << RHS.get()->getSourceRange(); 9450 } 9451 if (LHSIsNull && !RHSIsNull) 9452 LHS = ImpCastExprToType(LHS.get(), RHSType, 9453 RHSType->isPointerType() ? CK_BitCast 9454 : CK_AnyPointerToBlockPointerCast); 9455 else 9456 RHS = ImpCastExprToType(RHS.get(), LHSType, 9457 LHSType->isPointerType() ? CK_BitCast 9458 : CK_AnyPointerToBlockPointerCast); 9459 return ResultTy; 9460 } 9461 9462 if (LHSType->isObjCObjectPointerType() || 9463 RHSType->isObjCObjectPointerType()) { 9464 const PointerType *LPT = LHSType->getAs<PointerType>(); 9465 const PointerType *RPT = RHSType->getAs<PointerType>(); 9466 if (LPT || RPT) { 9467 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9468 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9469 9470 if (!LPtrToVoid && !RPtrToVoid && 9471 !Context.typesAreCompatible(LHSType, RHSType)) { 9472 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9473 /*isError*/false); 9474 } 9475 if (LHSIsNull && !RHSIsNull) { 9476 Expr *E = LHS.get(); 9477 if (getLangOpts().ObjCAutoRefCount) 9478 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9479 LHS = ImpCastExprToType(E, RHSType, 9480 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9481 } 9482 else { 9483 Expr *E = RHS.get(); 9484 if (getLangOpts().ObjCAutoRefCount) 9485 CheckObjCARCConversion(SourceRange(), LHSType, E, 9486 CCK_ImplicitConversion, /*Diagnose=*/true, 9487 /*DiagnoseCFAudited=*/false, Opc); 9488 RHS = ImpCastExprToType(E, LHSType, 9489 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9490 } 9491 return ResultTy; 9492 } 9493 if (LHSType->isObjCObjectPointerType() && 9494 RHSType->isObjCObjectPointerType()) { 9495 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9496 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9497 /*isError*/false); 9498 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9499 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9500 9501 if (LHSIsNull && !RHSIsNull) 9502 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9503 else 9504 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9505 return ResultTy; 9506 } 9507 } 9508 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9509 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9510 unsigned DiagID = 0; 9511 bool isError = false; 9512 if (LangOpts.DebuggerSupport) { 9513 // Under a debugger, allow the comparison of pointers to integers, 9514 // since users tend to want to compare addresses. 9515 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9516 (RHSIsNull && RHSType->isIntegerType())) { 9517 if (IsRelational && !getLangOpts().CPlusPlus) 9518 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9519 } else if (IsRelational && !getLangOpts().CPlusPlus) 9520 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9521 else if (getLangOpts().CPlusPlus) { 9522 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9523 isError = true; 9524 } else 9525 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9526 9527 if (DiagID) { 9528 Diag(Loc, DiagID) 9529 << LHSType << RHSType << LHS.get()->getSourceRange() 9530 << RHS.get()->getSourceRange(); 9531 if (isError) 9532 return QualType(); 9533 } 9534 9535 if (LHSType->isIntegerType()) 9536 LHS = ImpCastExprToType(LHS.get(), RHSType, 9537 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9538 else 9539 RHS = ImpCastExprToType(RHS.get(), LHSType, 9540 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9541 return ResultTy; 9542 } 9543 9544 // Handle block pointers. 9545 if (!IsRelational && RHSIsNull 9546 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9547 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9548 return ResultTy; 9549 } 9550 if (!IsRelational && LHSIsNull 9551 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9552 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9553 return ResultTy; 9554 } 9555 9556 return InvalidOperands(Loc, LHS, RHS); 9557 } 9558 9559 9560 // Return a signed type that is of identical size and number of elements. 9561 // For floating point vectors, return an integer type of identical size 9562 // and number of elements. 9563 QualType Sema::GetSignedVectorType(QualType V) { 9564 const VectorType *VTy = V->getAs<VectorType>(); 9565 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9566 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9567 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9568 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9569 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9570 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9571 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9572 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9573 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9574 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9575 "Unhandled vector element size in vector compare"); 9576 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9577 } 9578 9579 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9580 /// operates on extended vector types. Instead of producing an IntTy result, 9581 /// like a scalar comparison, a vector comparison produces a vector of integer 9582 /// types. 9583 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9584 SourceLocation Loc, 9585 bool IsRelational) { 9586 // Check to make sure we're operating on vectors of the same type and width, 9587 // Allowing one side to be a scalar of element type. 9588 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9589 /*AllowBothBool*/true, 9590 /*AllowBoolConversions*/getLangOpts().ZVector); 9591 if (vType.isNull()) 9592 return vType; 9593 9594 QualType LHSType = LHS.get()->getType(); 9595 9596 // If AltiVec, the comparison results in a numeric type, i.e. 9597 // bool for C++, int for C 9598 if (getLangOpts().AltiVec && 9599 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9600 return Context.getLogicalOperationType(); 9601 9602 // For non-floating point types, check for self-comparisons of the form 9603 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9604 // often indicate logic errors in the program. 9605 if (!LHSType->hasFloatingRepresentation() && 9606 ActiveTemplateInstantiations.empty()) { 9607 if (DeclRefExpr* DRL 9608 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9609 if (DeclRefExpr* DRR 9610 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9611 if (DRL->getDecl() == DRR->getDecl()) 9612 DiagRuntimeBehavior(Loc, nullptr, 9613 PDiag(diag::warn_comparison_always) 9614 << 0 // self- 9615 << 2 // "a constant" 9616 ); 9617 } 9618 9619 // Check for comparisons of floating point operands using != and ==. 9620 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9621 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9622 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9623 } 9624 9625 // Return a signed type for the vector. 9626 return GetSignedVectorType(vType); 9627 } 9628 9629 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9630 SourceLocation Loc) { 9631 // Ensure that either both operands are of the same vector type, or 9632 // one operand is of a vector type and the other is of its element type. 9633 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9634 /*AllowBothBool*/true, 9635 /*AllowBoolConversions*/false); 9636 if (vType.isNull()) 9637 return InvalidOperands(Loc, LHS, RHS); 9638 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9639 vType->hasFloatingRepresentation()) 9640 return InvalidOperands(Loc, LHS, RHS); 9641 9642 return GetSignedVectorType(LHS.get()->getType()); 9643 } 9644 9645 inline QualType Sema::CheckBitwiseOperands( 9646 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9647 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9648 9649 if (LHS.get()->getType()->isVectorType() || 9650 RHS.get()->getType()->isVectorType()) { 9651 if (LHS.get()->getType()->hasIntegerRepresentation() && 9652 RHS.get()->getType()->hasIntegerRepresentation()) 9653 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9654 /*AllowBothBool*/true, 9655 /*AllowBoolConversions*/getLangOpts().ZVector); 9656 return InvalidOperands(Loc, LHS, RHS); 9657 } 9658 9659 ExprResult LHSResult = LHS, RHSResult = RHS; 9660 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9661 IsCompAssign); 9662 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9663 return QualType(); 9664 LHS = LHSResult.get(); 9665 RHS = RHSResult.get(); 9666 9667 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9668 return compType; 9669 return InvalidOperands(Loc, LHS, RHS); 9670 } 9671 9672 // C99 6.5.[13,14] 9673 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9674 SourceLocation Loc, 9675 BinaryOperatorKind Opc) { 9676 // Check vector operands differently. 9677 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9678 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9679 9680 // Diagnose cases where the user write a logical and/or but probably meant a 9681 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9682 // is a constant. 9683 if (LHS.get()->getType()->isIntegerType() && 9684 !LHS.get()->getType()->isBooleanType() && 9685 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9686 // Don't warn in macros or template instantiations. 9687 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9688 // If the RHS can be constant folded, and if it constant folds to something 9689 // that isn't 0 or 1 (which indicate a potential logical operation that 9690 // happened to fold to true/false) then warn. 9691 // Parens on the RHS are ignored. 9692 llvm::APSInt Result; 9693 if (RHS.get()->EvaluateAsInt(Result, Context)) 9694 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9695 !RHS.get()->getExprLoc().isMacroID()) || 9696 (Result != 0 && Result != 1)) { 9697 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9698 << RHS.get()->getSourceRange() 9699 << (Opc == BO_LAnd ? "&&" : "||"); 9700 // Suggest replacing the logical operator with the bitwise version 9701 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9702 << (Opc == BO_LAnd ? "&" : "|") 9703 << FixItHint::CreateReplacement(SourceRange( 9704 Loc, getLocForEndOfToken(Loc)), 9705 Opc == BO_LAnd ? "&" : "|"); 9706 if (Opc == BO_LAnd) 9707 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9708 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9709 << FixItHint::CreateRemoval( 9710 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9711 RHS.get()->getLocEnd())); 9712 } 9713 } 9714 9715 if (!Context.getLangOpts().CPlusPlus) { 9716 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9717 // not operate on the built-in scalar and vector float types. 9718 if (Context.getLangOpts().OpenCL && 9719 Context.getLangOpts().OpenCLVersion < 120) { 9720 if (LHS.get()->getType()->isFloatingType() || 9721 RHS.get()->getType()->isFloatingType()) 9722 return InvalidOperands(Loc, LHS, RHS); 9723 } 9724 9725 LHS = UsualUnaryConversions(LHS.get()); 9726 if (LHS.isInvalid()) 9727 return QualType(); 9728 9729 RHS = UsualUnaryConversions(RHS.get()); 9730 if (RHS.isInvalid()) 9731 return QualType(); 9732 9733 if (!LHS.get()->getType()->isScalarType() || 9734 !RHS.get()->getType()->isScalarType()) 9735 return InvalidOperands(Loc, LHS, RHS); 9736 9737 return Context.IntTy; 9738 } 9739 9740 // The following is safe because we only use this method for 9741 // non-overloadable operands. 9742 9743 // C++ [expr.log.and]p1 9744 // C++ [expr.log.or]p1 9745 // The operands are both contextually converted to type bool. 9746 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9747 if (LHSRes.isInvalid()) 9748 return InvalidOperands(Loc, LHS, RHS); 9749 LHS = LHSRes; 9750 9751 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9752 if (RHSRes.isInvalid()) 9753 return InvalidOperands(Loc, LHS, RHS); 9754 RHS = RHSRes; 9755 9756 // C++ [expr.log.and]p2 9757 // C++ [expr.log.or]p2 9758 // The result is a bool. 9759 return Context.BoolTy; 9760 } 9761 9762 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9763 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9764 if (!ME) return false; 9765 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9766 ObjCMessageExpr *Base = 9767 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9768 if (!Base) return false; 9769 return Base->getMethodDecl() != nullptr; 9770 } 9771 9772 /// Is the given expression (which must be 'const') a reference to a 9773 /// variable which was originally non-const, but which has become 9774 /// 'const' due to being captured within a block? 9775 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9776 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9777 assert(E->isLValue() && E->getType().isConstQualified()); 9778 E = E->IgnoreParens(); 9779 9780 // Must be a reference to a declaration from an enclosing scope. 9781 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9782 if (!DRE) return NCCK_None; 9783 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9784 9785 // The declaration must be a variable which is not declared 'const'. 9786 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9787 if (!var) return NCCK_None; 9788 if (var->getType().isConstQualified()) return NCCK_None; 9789 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9790 9791 // Decide whether the first capture was for a block or a lambda. 9792 DeclContext *DC = S.CurContext, *Prev = nullptr; 9793 // Decide whether the first capture was for a block or a lambda. 9794 while (DC) { 9795 // For init-capture, it is possible that the variable belongs to the 9796 // template pattern of the current context. 9797 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9798 if (var->isInitCapture() && 9799 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9800 break; 9801 if (DC == var->getDeclContext()) 9802 break; 9803 Prev = DC; 9804 DC = DC->getParent(); 9805 } 9806 // Unless we have an init-capture, we've gone one step too far. 9807 if (!var->isInitCapture()) 9808 DC = Prev; 9809 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9810 } 9811 9812 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9813 Ty = Ty.getNonReferenceType(); 9814 if (IsDereference && Ty->isPointerType()) 9815 Ty = Ty->getPointeeType(); 9816 return !Ty.isConstQualified(); 9817 } 9818 9819 /// Emit the "read-only variable not assignable" error and print notes to give 9820 /// more information about why the variable is not assignable, such as pointing 9821 /// to the declaration of a const variable, showing that a method is const, or 9822 /// that the function is returning a const reference. 9823 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9824 SourceLocation Loc) { 9825 // Update err_typecheck_assign_const and note_typecheck_assign_const 9826 // when this enum is changed. 9827 enum { 9828 ConstFunction, 9829 ConstVariable, 9830 ConstMember, 9831 ConstMethod, 9832 ConstUnknown, // Keep as last element 9833 }; 9834 9835 SourceRange ExprRange = E->getSourceRange(); 9836 9837 // Only emit one error on the first const found. All other consts will emit 9838 // a note to the error. 9839 bool DiagnosticEmitted = false; 9840 9841 // Track if the current expression is the result of a derefence, and if the 9842 // next checked expression is the result of a derefence. 9843 bool IsDereference = false; 9844 bool NextIsDereference = false; 9845 9846 // Loop to process MemberExpr chains. 9847 while (true) { 9848 IsDereference = NextIsDereference; 9849 NextIsDereference = false; 9850 9851 E = E->IgnoreParenImpCasts(); 9852 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9853 NextIsDereference = ME->isArrow(); 9854 const ValueDecl *VD = ME->getMemberDecl(); 9855 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9856 // Mutable fields can be modified even if the class is const. 9857 if (Field->isMutable()) { 9858 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9859 break; 9860 } 9861 9862 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9863 if (!DiagnosticEmitted) { 9864 S.Diag(Loc, diag::err_typecheck_assign_const) 9865 << ExprRange << ConstMember << false /*static*/ << Field 9866 << Field->getType(); 9867 DiagnosticEmitted = true; 9868 } 9869 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9870 << ConstMember << false /*static*/ << Field << Field->getType() 9871 << Field->getSourceRange(); 9872 } 9873 E = ME->getBase(); 9874 continue; 9875 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9876 if (VDecl->getType().isConstQualified()) { 9877 if (!DiagnosticEmitted) { 9878 S.Diag(Loc, diag::err_typecheck_assign_const) 9879 << ExprRange << ConstMember << true /*static*/ << VDecl 9880 << VDecl->getType(); 9881 DiagnosticEmitted = true; 9882 } 9883 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9884 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9885 << VDecl->getSourceRange(); 9886 } 9887 // Static fields do not inherit constness from parents. 9888 break; 9889 } 9890 break; 9891 } // End MemberExpr 9892 break; 9893 } 9894 9895 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9896 // Function calls 9897 const FunctionDecl *FD = CE->getDirectCallee(); 9898 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9899 if (!DiagnosticEmitted) { 9900 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9901 << ConstFunction << FD; 9902 DiagnosticEmitted = true; 9903 } 9904 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9905 diag::note_typecheck_assign_const) 9906 << ConstFunction << FD << FD->getReturnType() 9907 << FD->getReturnTypeSourceRange(); 9908 } 9909 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9910 // Point to variable declaration. 9911 if (const ValueDecl *VD = DRE->getDecl()) { 9912 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9913 if (!DiagnosticEmitted) { 9914 S.Diag(Loc, diag::err_typecheck_assign_const) 9915 << ExprRange << ConstVariable << VD << VD->getType(); 9916 DiagnosticEmitted = true; 9917 } 9918 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9919 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9920 } 9921 } 9922 } else if (isa<CXXThisExpr>(E)) { 9923 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9924 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9925 if (MD->isConst()) { 9926 if (!DiagnosticEmitted) { 9927 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9928 << ConstMethod << MD; 9929 DiagnosticEmitted = true; 9930 } 9931 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9932 << ConstMethod << MD << MD->getSourceRange(); 9933 } 9934 } 9935 } 9936 } 9937 9938 if (DiagnosticEmitted) 9939 return; 9940 9941 // Can't determine a more specific message, so display the generic error. 9942 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9943 } 9944 9945 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9946 /// emit an error and return true. If so, return false. 9947 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9948 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9949 9950 S.CheckShadowingDeclModification(E, Loc); 9951 9952 SourceLocation OrigLoc = Loc; 9953 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9954 &Loc); 9955 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9956 IsLV = Expr::MLV_InvalidMessageExpression; 9957 if (IsLV == Expr::MLV_Valid) 9958 return false; 9959 9960 unsigned DiagID = 0; 9961 bool NeedType = false; 9962 switch (IsLV) { // C99 6.5.16p2 9963 case Expr::MLV_ConstQualified: 9964 // Use a specialized diagnostic when we're assigning to an object 9965 // from an enclosing function or block. 9966 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9967 if (NCCK == NCCK_Block) 9968 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9969 else 9970 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9971 break; 9972 } 9973 9974 // In ARC, use some specialized diagnostics for occasions where we 9975 // infer 'const'. These are always pseudo-strong variables. 9976 if (S.getLangOpts().ObjCAutoRefCount) { 9977 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9978 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9979 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9980 9981 // Use the normal diagnostic if it's pseudo-__strong but the 9982 // user actually wrote 'const'. 9983 if (var->isARCPseudoStrong() && 9984 (!var->getTypeSourceInfo() || 9985 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9986 // There are two pseudo-strong cases: 9987 // - self 9988 ObjCMethodDecl *method = S.getCurMethodDecl(); 9989 if (method && var == method->getSelfDecl()) 9990 DiagID = method->isClassMethod() 9991 ? diag::err_typecheck_arc_assign_self_class_method 9992 : diag::err_typecheck_arc_assign_self; 9993 9994 // - fast enumeration variables 9995 else 9996 DiagID = diag::err_typecheck_arr_assign_enumeration; 9997 9998 SourceRange Assign; 9999 if (Loc != OrigLoc) 10000 Assign = SourceRange(OrigLoc, OrigLoc); 10001 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10002 // We need to preserve the AST regardless, so migration tool 10003 // can do its job. 10004 return false; 10005 } 10006 } 10007 } 10008 10009 // If none of the special cases above are triggered, then this is a 10010 // simple const assignment. 10011 if (DiagID == 0) { 10012 DiagnoseConstAssignment(S, E, Loc); 10013 return true; 10014 } 10015 10016 break; 10017 case Expr::MLV_ConstAddrSpace: 10018 DiagnoseConstAssignment(S, E, Loc); 10019 return true; 10020 case Expr::MLV_ArrayType: 10021 case Expr::MLV_ArrayTemporary: 10022 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10023 NeedType = true; 10024 break; 10025 case Expr::MLV_NotObjectType: 10026 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10027 NeedType = true; 10028 break; 10029 case Expr::MLV_LValueCast: 10030 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10031 break; 10032 case Expr::MLV_Valid: 10033 llvm_unreachable("did not take early return for MLV_Valid"); 10034 case Expr::MLV_InvalidExpression: 10035 case Expr::MLV_MemberFunction: 10036 case Expr::MLV_ClassTemporary: 10037 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10038 break; 10039 case Expr::MLV_IncompleteType: 10040 case Expr::MLV_IncompleteVoidType: 10041 return S.RequireCompleteType(Loc, E->getType(), 10042 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10043 case Expr::MLV_DuplicateVectorComponents: 10044 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10045 break; 10046 case Expr::MLV_NoSetterProperty: 10047 llvm_unreachable("readonly properties should be processed differently"); 10048 case Expr::MLV_InvalidMessageExpression: 10049 DiagID = diag::error_readonly_message_assignment; 10050 break; 10051 case Expr::MLV_SubObjCPropertySetting: 10052 DiagID = diag::error_no_subobject_property_setting; 10053 break; 10054 } 10055 10056 SourceRange Assign; 10057 if (Loc != OrigLoc) 10058 Assign = SourceRange(OrigLoc, OrigLoc); 10059 if (NeedType) 10060 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10061 else 10062 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10063 return true; 10064 } 10065 10066 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10067 SourceLocation Loc, 10068 Sema &Sema) { 10069 // C / C++ fields 10070 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10071 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10072 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10073 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10074 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10075 } 10076 10077 // Objective-C instance variables 10078 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10079 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10080 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10081 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10082 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10083 if (RL && RR && RL->getDecl() == RR->getDecl()) 10084 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10085 } 10086 } 10087 10088 // C99 6.5.16.1 10089 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10090 SourceLocation Loc, 10091 QualType CompoundType) { 10092 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10093 10094 // Verify that LHS is a modifiable lvalue, and emit error if not. 10095 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10096 return QualType(); 10097 10098 QualType LHSType = LHSExpr->getType(); 10099 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10100 CompoundType; 10101 // OpenCL v1.2 s6.1.1.1 p2: 10102 // The half data type can only be used to declare a pointer to a buffer that 10103 // contains half values 10104 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 10105 LHSType->isHalfType()) { 10106 Diag(Loc, diag::err_opencl_half_load_store) << 1 10107 << LHSType.getUnqualifiedType(); 10108 return QualType(); 10109 } 10110 10111 AssignConvertType ConvTy; 10112 if (CompoundType.isNull()) { 10113 Expr *RHSCheck = RHS.get(); 10114 10115 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10116 10117 QualType LHSTy(LHSType); 10118 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10119 if (RHS.isInvalid()) 10120 return QualType(); 10121 // Special case of NSObject attributes on c-style pointer types. 10122 if (ConvTy == IncompatiblePointer && 10123 ((Context.isObjCNSObjectType(LHSType) && 10124 RHSType->isObjCObjectPointerType()) || 10125 (Context.isObjCNSObjectType(RHSType) && 10126 LHSType->isObjCObjectPointerType()))) 10127 ConvTy = Compatible; 10128 10129 if (ConvTy == Compatible && 10130 LHSType->isObjCObjectType()) 10131 Diag(Loc, diag::err_objc_object_assignment) 10132 << LHSType; 10133 10134 // If the RHS is a unary plus or minus, check to see if they = and + are 10135 // right next to each other. If so, the user may have typo'd "x =+ 4" 10136 // instead of "x += 4". 10137 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10138 RHSCheck = ICE->getSubExpr(); 10139 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10140 if ((UO->getOpcode() == UO_Plus || 10141 UO->getOpcode() == UO_Minus) && 10142 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10143 // Only if the two operators are exactly adjacent. 10144 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10145 // And there is a space or other character before the subexpr of the 10146 // unary +/-. We don't want to warn on "x=-1". 10147 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10148 UO->getSubExpr()->getLocStart().isFileID()) { 10149 Diag(Loc, diag::warn_not_compound_assign) 10150 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10151 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10152 } 10153 } 10154 10155 if (ConvTy == Compatible) { 10156 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10157 // Warn about retain cycles where a block captures the LHS, but 10158 // not if the LHS is a simple variable into which the block is 10159 // being stored...unless that variable can be captured by reference! 10160 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10161 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10162 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10163 checkRetainCycles(LHSExpr, RHS.get()); 10164 10165 // It is safe to assign a weak reference into a strong variable. 10166 // Although this code can still have problems: 10167 // id x = self.weakProp; 10168 // id y = self.weakProp; 10169 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10170 // paths through the function. This should be revisited if 10171 // -Wrepeated-use-of-weak is made flow-sensitive. 10172 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10173 RHS.get()->getLocStart())) 10174 getCurFunction()->markSafeWeakUse(RHS.get()); 10175 10176 } else if (getLangOpts().ObjCAutoRefCount) { 10177 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10178 } 10179 } 10180 } else { 10181 // Compound assignment "x += y" 10182 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10183 } 10184 10185 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10186 RHS.get(), AA_Assigning)) 10187 return QualType(); 10188 10189 CheckForNullPointerDereference(*this, LHSExpr); 10190 10191 // C99 6.5.16p3: The type of an assignment expression is the type of the 10192 // left operand unless the left operand has qualified type, in which case 10193 // it is the unqualified version of the type of the left operand. 10194 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10195 // is converted to the type of the assignment expression (above). 10196 // C++ 5.17p1: the type of the assignment expression is that of its left 10197 // operand. 10198 return (getLangOpts().CPlusPlus 10199 ? LHSType : LHSType.getUnqualifiedType()); 10200 } 10201 10202 // Only ignore explicit casts to void. 10203 static bool IgnoreCommaOperand(const Expr *E) { 10204 E = E->IgnoreParens(); 10205 10206 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10207 if (CE->getCastKind() == CK_ToVoid) { 10208 return true; 10209 } 10210 } 10211 10212 return false; 10213 } 10214 10215 // Look for instances where it is likely the comma operator is confused with 10216 // another operator. There is a whitelist of acceptable expressions for the 10217 // left hand side of the comma operator, otherwise emit a warning. 10218 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10219 // No warnings in macros 10220 if (Loc.isMacroID()) 10221 return; 10222 10223 // Don't warn in template instantiations. 10224 if (!ActiveTemplateInstantiations.empty()) 10225 return; 10226 10227 // Scope isn't fine-grained enough to whitelist the specific cases, so 10228 // instead, skip more than needed, then call back into here with the 10229 // CommaVisitor in SemaStmt.cpp. 10230 // The whitelisted locations are the initialization and increment portions 10231 // of a for loop. The additional checks are on the condition of 10232 // if statements, do/while loops, and for loops. 10233 const unsigned ForIncrementFlags = 10234 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10235 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10236 const unsigned ScopeFlags = getCurScope()->getFlags(); 10237 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10238 (ScopeFlags & ForInitFlags) == ForInitFlags) 10239 return; 10240 10241 // If there are multiple comma operators used together, get the RHS of the 10242 // of the comma operator as the LHS. 10243 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10244 if (BO->getOpcode() != BO_Comma) 10245 break; 10246 LHS = BO->getRHS(); 10247 } 10248 10249 // Only allow some expressions on LHS to not warn. 10250 if (IgnoreCommaOperand(LHS)) 10251 return; 10252 10253 Diag(Loc, diag::warn_comma_operator); 10254 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10255 << LHS->getSourceRange() 10256 << FixItHint::CreateInsertion(LHS->getLocStart(), 10257 LangOpts.CPlusPlus ? "static_cast<void>(" 10258 : "(void)(") 10259 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10260 ")"); 10261 } 10262 10263 // C99 6.5.17 10264 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10265 SourceLocation Loc) { 10266 LHS = S.CheckPlaceholderExpr(LHS.get()); 10267 RHS = S.CheckPlaceholderExpr(RHS.get()); 10268 if (LHS.isInvalid() || RHS.isInvalid()) 10269 return QualType(); 10270 10271 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10272 // operands, but not unary promotions. 10273 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10274 10275 // So we treat the LHS as a ignored value, and in C++ we allow the 10276 // containing site to determine what should be done with the RHS. 10277 LHS = S.IgnoredValueConversions(LHS.get()); 10278 if (LHS.isInvalid()) 10279 return QualType(); 10280 10281 S.DiagnoseUnusedExprResult(LHS.get()); 10282 10283 if (!S.getLangOpts().CPlusPlus) { 10284 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10285 if (RHS.isInvalid()) 10286 return QualType(); 10287 if (!RHS.get()->getType()->isVoidType()) 10288 S.RequireCompleteType(Loc, RHS.get()->getType(), 10289 diag::err_incomplete_type); 10290 } 10291 10292 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10293 S.DiagnoseCommaOperator(LHS.get(), Loc); 10294 10295 return RHS.get()->getType(); 10296 } 10297 10298 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10299 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10300 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10301 ExprValueKind &VK, 10302 ExprObjectKind &OK, 10303 SourceLocation OpLoc, 10304 bool IsInc, bool IsPrefix) { 10305 if (Op->isTypeDependent()) 10306 return S.Context.DependentTy; 10307 10308 QualType ResType = Op->getType(); 10309 // Atomic types can be used for increment / decrement where the non-atomic 10310 // versions can, so ignore the _Atomic() specifier for the purpose of 10311 // checking. 10312 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10313 ResType = ResAtomicType->getValueType(); 10314 10315 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10316 10317 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10318 // Decrement of bool is not allowed. 10319 if (!IsInc) { 10320 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10321 return QualType(); 10322 } 10323 // Increment of bool sets it to true, but is deprecated. 10324 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10325 : diag::warn_increment_bool) 10326 << Op->getSourceRange(); 10327 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10328 // Error on enum increments and decrements in C++ mode 10329 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10330 return QualType(); 10331 } else if (ResType->isRealType()) { 10332 // OK! 10333 } else if (ResType->isPointerType()) { 10334 // C99 6.5.2.4p2, 6.5.6p2 10335 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10336 return QualType(); 10337 } else if (ResType->isObjCObjectPointerType()) { 10338 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10339 // Otherwise, we just need a complete type. 10340 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10341 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10342 return QualType(); 10343 } else if (ResType->isAnyComplexType()) { 10344 // C99 does not support ++/-- on complex types, we allow as an extension. 10345 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10346 << ResType << Op->getSourceRange(); 10347 } else if (ResType->isPlaceholderType()) { 10348 ExprResult PR = S.CheckPlaceholderExpr(Op); 10349 if (PR.isInvalid()) return QualType(); 10350 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10351 IsInc, IsPrefix); 10352 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10353 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10354 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10355 (ResType->getAs<VectorType>()->getVectorKind() != 10356 VectorType::AltiVecBool)) { 10357 // The z vector extensions allow ++ and -- for non-bool vectors. 10358 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10359 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10360 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10361 } else { 10362 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10363 << ResType << int(IsInc) << Op->getSourceRange(); 10364 return QualType(); 10365 } 10366 // At this point, we know we have a real, complex or pointer type. 10367 // Now make sure the operand is a modifiable lvalue. 10368 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10369 return QualType(); 10370 // In C++, a prefix increment is the same type as the operand. Otherwise 10371 // (in C or with postfix), the increment is the unqualified type of the 10372 // operand. 10373 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10374 VK = VK_LValue; 10375 OK = Op->getObjectKind(); 10376 return ResType; 10377 } else { 10378 VK = VK_RValue; 10379 return ResType.getUnqualifiedType(); 10380 } 10381 } 10382 10383 10384 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10385 /// This routine allows us to typecheck complex/recursive expressions 10386 /// where the declaration is needed for type checking. We only need to 10387 /// handle cases when the expression references a function designator 10388 /// or is an lvalue. Here are some examples: 10389 /// - &(x) => x 10390 /// - &*****f => f for f a function designator. 10391 /// - &s.xx => s 10392 /// - &s.zz[1].yy -> s, if zz is an array 10393 /// - *(x + 1) -> x, if x is an array 10394 /// - &"123"[2] -> 0 10395 /// - & __real__ x -> x 10396 static ValueDecl *getPrimaryDecl(Expr *E) { 10397 switch (E->getStmtClass()) { 10398 case Stmt::DeclRefExprClass: 10399 return cast<DeclRefExpr>(E)->getDecl(); 10400 case Stmt::MemberExprClass: 10401 // If this is an arrow operator, the address is an offset from 10402 // the base's value, so the object the base refers to is 10403 // irrelevant. 10404 if (cast<MemberExpr>(E)->isArrow()) 10405 return nullptr; 10406 // Otherwise, the expression refers to a part of the base 10407 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10408 case Stmt::ArraySubscriptExprClass: { 10409 // FIXME: This code shouldn't be necessary! We should catch the implicit 10410 // promotion of register arrays earlier. 10411 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10412 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10413 if (ICE->getSubExpr()->getType()->isArrayType()) 10414 return getPrimaryDecl(ICE->getSubExpr()); 10415 } 10416 return nullptr; 10417 } 10418 case Stmt::UnaryOperatorClass: { 10419 UnaryOperator *UO = cast<UnaryOperator>(E); 10420 10421 switch(UO->getOpcode()) { 10422 case UO_Real: 10423 case UO_Imag: 10424 case UO_Extension: 10425 return getPrimaryDecl(UO->getSubExpr()); 10426 default: 10427 return nullptr; 10428 } 10429 } 10430 case Stmt::ParenExprClass: 10431 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10432 case Stmt::ImplicitCastExprClass: 10433 // If the result of an implicit cast is an l-value, we care about 10434 // the sub-expression; otherwise, the result here doesn't matter. 10435 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10436 default: 10437 return nullptr; 10438 } 10439 } 10440 10441 namespace { 10442 enum { 10443 AO_Bit_Field = 0, 10444 AO_Vector_Element = 1, 10445 AO_Property_Expansion = 2, 10446 AO_Register_Variable = 3, 10447 AO_No_Error = 4 10448 }; 10449 } 10450 /// \brief Diagnose invalid operand for address of operations. 10451 /// 10452 /// \param Type The type of operand which cannot have its address taken. 10453 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10454 Expr *E, unsigned Type) { 10455 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10456 } 10457 10458 /// CheckAddressOfOperand - The operand of & must be either a function 10459 /// designator or an lvalue designating an object. If it is an lvalue, the 10460 /// object cannot be declared with storage class register or be a bit field. 10461 /// Note: The usual conversions are *not* applied to the operand of the & 10462 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10463 /// In C++, the operand might be an overloaded function name, in which case 10464 /// we allow the '&' but retain the overloaded-function type. 10465 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10466 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10467 if (PTy->getKind() == BuiltinType::Overload) { 10468 Expr *E = OrigOp.get()->IgnoreParens(); 10469 if (!isa<OverloadExpr>(E)) { 10470 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10471 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10472 << OrigOp.get()->getSourceRange(); 10473 return QualType(); 10474 } 10475 10476 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10477 if (isa<UnresolvedMemberExpr>(Ovl)) 10478 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10479 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10480 << OrigOp.get()->getSourceRange(); 10481 return QualType(); 10482 } 10483 10484 return Context.OverloadTy; 10485 } 10486 10487 if (PTy->getKind() == BuiltinType::UnknownAny) 10488 return Context.UnknownAnyTy; 10489 10490 if (PTy->getKind() == BuiltinType::BoundMember) { 10491 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10492 << OrigOp.get()->getSourceRange(); 10493 return QualType(); 10494 } 10495 10496 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10497 if (OrigOp.isInvalid()) return QualType(); 10498 } 10499 10500 if (OrigOp.get()->isTypeDependent()) 10501 return Context.DependentTy; 10502 10503 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10504 10505 // Make sure to ignore parentheses in subsequent checks 10506 Expr *op = OrigOp.get()->IgnoreParens(); 10507 10508 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10509 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10510 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10511 return QualType(); 10512 } 10513 10514 if (getLangOpts().C99) { 10515 // Implement C99-only parts of addressof rules. 10516 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10517 if (uOp->getOpcode() == UO_Deref) 10518 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10519 // (assuming the deref expression is valid). 10520 return uOp->getSubExpr()->getType(); 10521 } 10522 // Technically, there should be a check for array subscript 10523 // expressions here, but the result of one is always an lvalue anyway. 10524 } 10525 ValueDecl *dcl = getPrimaryDecl(op); 10526 10527 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10528 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10529 op->getLocStart())) 10530 return QualType(); 10531 10532 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10533 unsigned AddressOfError = AO_No_Error; 10534 10535 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10536 bool sfinae = (bool)isSFINAEContext(); 10537 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10538 : diag::ext_typecheck_addrof_temporary) 10539 << op->getType() << op->getSourceRange(); 10540 if (sfinae) 10541 return QualType(); 10542 // Materialize the temporary as an lvalue so that we can take its address. 10543 OrigOp = op = 10544 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10545 } else if (isa<ObjCSelectorExpr>(op)) { 10546 return Context.getPointerType(op->getType()); 10547 } else if (lval == Expr::LV_MemberFunction) { 10548 // If it's an instance method, make a member pointer. 10549 // The expression must have exactly the form &A::foo. 10550 10551 // If the underlying expression isn't a decl ref, give up. 10552 if (!isa<DeclRefExpr>(op)) { 10553 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10554 << OrigOp.get()->getSourceRange(); 10555 return QualType(); 10556 } 10557 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10558 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10559 10560 // The id-expression was parenthesized. 10561 if (OrigOp.get() != DRE) { 10562 Diag(OpLoc, diag::err_parens_pointer_member_function) 10563 << OrigOp.get()->getSourceRange(); 10564 10565 // The method was named without a qualifier. 10566 } else if (!DRE->getQualifier()) { 10567 if (MD->getParent()->getName().empty()) 10568 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10569 << op->getSourceRange(); 10570 else { 10571 SmallString<32> Str; 10572 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10573 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10574 << op->getSourceRange() 10575 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10576 } 10577 } 10578 10579 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10580 if (isa<CXXDestructorDecl>(MD)) 10581 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10582 10583 QualType MPTy = Context.getMemberPointerType( 10584 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10585 // Under the MS ABI, lock down the inheritance model now. 10586 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10587 (void)isCompleteType(OpLoc, MPTy); 10588 return MPTy; 10589 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10590 // C99 6.5.3.2p1 10591 // The operand must be either an l-value or a function designator 10592 if (!op->getType()->isFunctionType()) { 10593 // Use a special diagnostic for loads from property references. 10594 if (isa<PseudoObjectExpr>(op)) { 10595 AddressOfError = AO_Property_Expansion; 10596 } else { 10597 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10598 << op->getType() << op->getSourceRange(); 10599 return QualType(); 10600 } 10601 } 10602 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10603 // The operand cannot be a bit-field 10604 AddressOfError = AO_Bit_Field; 10605 } else if (op->getObjectKind() == OK_VectorComponent) { 10606 // The operand cannot be an element of a vector 10607 AddressOfError = AO_Vector_Element; 10608 } else if (dcl) { // C99 6.5.3.2p1 10609 // We have an lvalue with a decl. Make sure the decl is not declared 10610 // with the register storage-class specifier. 10611 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10612 // in C++ it is not error to take address of a register 10613 // variable (c++03 7.1.1P3) 10614 if (vd->getStorageClass() == SC_Register && 10615 !getLangOpts().CPlusPlus) { 10616 AddressOfError = AO_Register_Variable; 10617 } 10618 } else if (isa<MSPropertyDecl>(dcl)) { 10619 AddressOfError = AO_Property_Expansion; 10620 } else if (isa<FunctionTemplateDecl>(dcl)) { 10621 return Context.OverloadTy; 10622 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10623 // Okay: we can take the address of a field. 10624 // Could be a pointer to member, though, if there is an explicit 10625 // scope qualifier for the class. 10626 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10627 DeclContext *Ctx = dcl->getDeclContext(); 10628 if (Ctx && Ctx->isRecord()) { 10629 if (dcl->getType()->isReferenceType()) { 10630 Diag(OpLoc, 10631 diag::err_cannot_form_pointer_to_member_of_reference_type) 10632 << dcl->getDeclName() << dcl->getType(); 10633 return QualType(); 10634 } 10635 10636 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10637 Ctx = Ctx->getParent(); 10638 10639 QualType MPTy = Context.getMemberPointerType( 10640 op->getType(), 10641 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10642 // Under the MS ABI, lock down the inheritance model now. 10643 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10644 (void)isCompleteType(OpLoc, MPTy); 10645 return MPTy; 10646 } 10647 } 10648 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10649 !isa<BindingDecl>(dcl)) 10650 llvm_unreachable("Unknown/unexpected decl type"); 10651 } 10652 10653 if (AddressOfError != AO_No_Error) { 10654 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10655 return QualType(); 10656 } 10657 10658 if (lval == Expr::LV_IncompleteVoidType) { 10659 // Taking the address of a void variable is technically illegal, but we 10660 // allow it in cases which are otherwise valid. 10661 // Example: "extern void x; void* y = &x;". 10662 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10663 } 10664 10665 // If the operand has type "type", the result has type "pointer to type". 10666 if (op->getType()->isObjCObjectType()) 10667 return Context.getObjCObjectPointerType(op->getType()); 10668 10669 CheckAddressOfPackedMember(op); 10670 10671 return Context.getPointerType(op->getType()); 10672 } 10673 10674 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10675 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10676 if (!DRE) 10677 return; 10678 const Decl *D = DRE->getDecl(); 10679 if (!D) 10680 return; 10681 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10682 if (!Param) 10683 return; 10684 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10685 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10686 return; 10687 if (FunctionScopeInfo *FD = S.getCurFunction()) 10688 if (!FD->ModifiedNonNullParams.count(Param)) 10689 FD->ModifiedNonNullParams.insert(Param); 10690 } 10691 10692 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10693 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10694 SourceLocation OpLoc) { 10695 if (Op->isTypeDependent()) 10696 return S.Context.DependentTy; 10697 10698 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10699 if (ConvResult.isInvalid()) 10700 return QualType(); 10701 Op = ConvResult.get(); 10702 QualType OpTy = Op->getType(); 10703 QualType Result; 10704 10705 if (isa<CXXReinterpretCastExpr>(Op)) { 10706 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10707 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10708 Op->getSourceRange()); 10709 } 10710 10711 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10712 { 10713 Result = PT->getPointeeType(); 10714 } 10715 else if (const ObjCObjectPointerType *OPT = 10716 OpTy->getAs<ObjCObjectPointerType>()) 10717 Result = OPT->getPointeeType(); 10718 else { 10719 ExprResult PR = S.CheckPlaceholderExpr(Op); 10720 if (PR.isInvalid()) return QualType(); 10721 if (PR.get() != Op) 10722 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10723 } 10724 10725 if (Result.isNull()) { 10726 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10727 << OpTy << Op->getSourceRange(); 10728 return QualType(); 10729 } 10730 10731 // Note that per both C89 and C99, indirection is always legal, even if Result 10732 // is an incomplete type or void. It would be possible to warn about 10733 // dereferencing a void pointer, but it's completely well-defined, and such a 10734 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10735 // for pointers to 'void' but is fine for any other pointer type: 10736 // 10737 // C++ [expr.unary.op]p1: 10738 // [...] the expression to which [the unary * operator] is applied shall 10739 // be a pointer to an object type, or a pointer to a function type 10740 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10741 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10742 << OpTy << Op->getSourceRange(); 10743 10744 // Dereferences are usually l-values... 10745 VK = VK_LValue; 10746 10747 // ...except that certain expressions are never l-values in C. 10748 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10749 VK = VK_RValue; 10750 10751 return Result; 10752 } 10753 10754 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10755 BinaryOperatorKind Opc; 10756 switch (Kind) { 10757 default: llvm_unreachable("Unknown binop!"); 10758 case tok::periodstar: Opc = BO_PtrMemD; break; 10759 case tok::arrowstar: Opc = BO_PtrMemI; break; 10760 case tok::star: Opc = BO_Mul; break; 10761 case tok::slash: Opc = BO_Div; break; 10762 case tok::percent: Opc = BO_Rem; break; 10763 case tok::plus: Opc = BO_Add; break; 10764 case tok::minus: Opc = BO_Sub; break; 10765 case tok::lessless: Opc = BO_Shl; break; 10766 case tok::greatergreater: Opc = BO_Shr; break; 10767 case tok::lessequal: Opc = BO_LE; break; 10768 case tok::less: Opc = BO_LT; break; 10769 case tok::greaterequal: Opc = BO_GE; break; 10770 case tok::greater: Opc = BO_GT; break; 10771 case tok::exclaimequal: Opc = BO_NE; break; 10772 case tok::equalequal: Opc = BO_EQ; break; 10773 case tok::amp: Opc = BO_And; break; 10774 case tok::caret: Opc = BO_Xor; break; 10775 case tok::pipe: Opc = BO_Or; break; 10776 case tok::ampamp: Opc = BO_LAnd; break; 10777 case tok::pipepipe: Opc = BO_LOr; break; 10778 case tok::equal: Opc = BO_Assign; break; 10779 case tok::starequal: Opc = BO_MulAssign; break; 10780 case tok::slashequal: Opc = BO_DivAssign; break; 10781 case tok::percentequal: Opc = BO_RemAssign; break; 10782 case tok::plusequal: Opc = BO_AddAssign; break; 10783 case tok::minusequal: Opc = BO_SubAssign; break; 10784 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10785 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10786 case tok::ampequal: Opc = BO_AndAssign; break; 10787 case tok::caretequal: Opc = BO_XorAssign; break; 10788 case tok::pipeequal: Opc = BO_OrAssign; break; 10789 case tok::comma: Opc = BO_Comma; break; 10790 } 10791 return Opc; 10792 } 10793 10794 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10795 tok::TokenKind Kind) { 10796 UnaryOperatorKind Opc; 10797 switch (Kind) { 10798 default: llvm_unreachable("Unknown unary op!"); 10799 case tok::plusplus: Opc = UO_PreInc; break; 10800 case tok::minusminus: Opc = UO_PreDec; break; 10801 case tok::amp: Opc = UO_AddrOf; break; 10802 case tok::star: Opc = UO_Deref; break; 10803 case tok::plus: Opc = UO_Plus; break; 10804 case tok::minus: Opc = UO_Minus; break; 10805 case tok::tilde: Opc = UO_Not; break; 10806 case tok::exclaim: Opc = UO_LNot; break; 10807 case tok::kw___real: Opc = UO_Real; break; 10808 case tok::kw___imag: Opc = UO_Imag; break; 10809 case tok::kw___extension__: Opc = UO_Extension; break; 10810 } 10811 return Opc; 10812 } 10813 10814 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10815 /// This warning is only emitted for builtin assignment operations. It is also 10816 /// suppressed in the event of macro expansions. 10817 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10818 SourceLocation OpLoc) { 10819 if (!S.ActiveTemplateInstantiations.empty()) 10820 return; 10821 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10822 return; 10823 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10824 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10825 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10826 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10827 if (!LHSDeclRef || !RHSDeclRef || 10828 LHSDeclRef->getLocation().isMacroID() || 10829 RHSDeclRef->getLocation().isMacroID()) 10830 return; 10831 const ValueDecl *LHSDecl = 10832 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10833 const ValueDecl *RHSDecl = 10834 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10835 if (LHSDecl != RHSDecl) 10836 return; 10837 if (LHSDecl->getType().isVolatileQualified()) 10838 return; 10839 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10840 if (RefTy->getPointeeType().isVolatileQualified()) 10841 return; 10842 10843 S.Diag(OpLoc, diag::warn_self_assignment) 10844 << LHSDeclRef->getType() 10845 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10846 } 10847 10848 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10849 /// is usually indicative of introspection within the Objective-C pointer. 10850 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10851 SourceLocation OpLoc) { 10852 if (!S.getLangOpts().ObjC1) 10853 return; 10854 10855 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10856 const Expr *LHS = L.get(); 10857 const Expr *RHS = R.get(); 10858 10859 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10860 ObjCPointerExpr = LHS; 10861 OtherExpr = RHS; 10862 } 10863 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10864 ObjCPointerExpr = RHS; 10865 OtherExpr = LHS; 10866 } 10867 10868 // This warning is deliberately made very specific to reduce false 10869 // positives with logic that uses '&' for hashing. This logic mainly 10870 // looks for code trying to introspect into tagged pointers, which 10871 // code should generally never do. 10872 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10873 unsigned Diag = diag::warn_objc_pointer_masking; 10874 // Determine if we are introspecting the result of performSelectorXXX. 10875 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10876 // Special case messages to -performSelector and friends, which 10877 // can return non-pointer values boxed in a pointer value. 10878 // Some clients may wish to silence warnings in this subcase. 10879 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10880 Selector S = ME->getSelector(); 10881 StringRef SelArg0 = S.getNameForSlot(0); 10882 if (SelArg0.startswith("performSelector")) 10883 Diag = diag::warn_objc_pointer_masking_performSelector; 10884 } 10885 10886 S.Diag(OpLoc, Diag) 10887 << ObjCPointerExpr->getSourceRange(); 10888 } 10889 } 10890 10891 static NamedDecl *getDeclFromExpr(Expr *E) { 10892 if (!E) 10893 return nullptr; 10894 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10895 return DRE->getDecl(); 10896 if (auto *ME = dyn_cast<MemberExpr>(E)) 10897 return ME->getMemberDecl(); 10898 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10899 return IRE->getDecl(); 10900 return nullptr; 10901 } 10902 10903 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10904 /// operator @p Opc at location @c TokLoc. This routine only supports 10905 /// built-in operations; ActOnBinOp handles overloaded operators. 10906 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10907 BinaryOperatorKind Opc, 10908 Expr *LHSExpr, Expr *RHSExpr) { 10909 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10910 // The syntax only allows initializer lists on the RHS of assignment, 10911 // so we don't need to worry about accepting invalid code for 10912 // non-assignment operators. 10913 // C++11 5.17p9: 10914 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10915 // of x = {} is x = T(). 10916 InitializationKind Kind = 10917 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10918 InitializedEntity Entity = 10919 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10920 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10921 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10922 if (Init.isInvalid()) 10923 return Init; 10924 RHSExpr = Init.get(); 10925 } 10926 10927 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10928 QualType ResultTy; // Result type of the binary operator. 10929 // The following two variables are used for compound assignment operators 10930 QualType CompLHSTy; // Type of LHS after promotions for computation 10931 QualType CompResultTy; // Type of computation result 10932 ExprValueKind VK = VK_RValue; 10933 ExprObjectKind OK = OK_Ordinary; 10934 10935 if (!getLangOpts().CPlusPlus) { 10936 // C cannot handle TypoExpr nodes on either side of a binop because it 10937 // doesn't handle dependent types properly, so make sure any TypoExprs have 10938 // been dealt with before checking the operands. 10939 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10940 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10941 if (Opc != BO_Assign) 10942 return ExprResult(E); 10943 // Avoid correcting the RHS to the same Expr as the LHS. 10944 Decl *D = getDeclFromExpr(E); 10945 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10946 }); 10947 if (!LHS.isUsable() || !RHS.isUsable()) 10948 return ExprError(); 10949 } 10950 10951 if (getLangOpts().OpenCL) { 10952 QualType LHSTy = LHSExpr->getType(); 10953 QualType RHSTy = RHSExpr->getType(); 10954 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10955 // the ATOMIC_VAR_INIT macro. 10956 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 10957 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10958 if (BO_Assign == Opc) 10959 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10960 else 10961 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10962 return ExprError(); 10963 } 10964 10965 // OpenCL special types - image, sampler, pipe, and blocks are to be used 10966 // only with a builtin functions and therefore should be disallowed here. 10967 if (LHSTy->isImageType() || RHSTy->isImageType() || 10968 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 10969 LHSTy->isPipeType() || RHSTy->isPipeType() || 10970 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 10971 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10972 return ExprError(); 10973 } 10974 } 10975 10976 switch (Opc) { 10977 case BO_Assign: 10978 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10979 if (getLangOpts().CPlusPlus && 10980 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10981 VK = LHS.get()->getValueKind(); 10982 OK = LHS.get()->getObjectKind(); 10983 } 10984 if (!ResultTy.isNull()) { 10985 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10986 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10987 } 10988 RecordModifiableNonNullParam(*this, LHS.get()); 10989 break; 10990 case BO_PtrMemD: 10991 case BO_PtrMemI: 10992 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10993 Opc == BO_PtrMemI); 10994 break; 10995 case BO_Mul: 10996 case BO_Div: 10997 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10998 Opc == BO_Div); 10999 break; 11000 case BO_Rem: 11001 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11002 break; 11003 case BO_Add: 11004 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11005 break; 11006 case BO_Sub: 11007 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11008 break; 11009 case BO_Shl: 11010 case BO_Shr: 11011 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11012 break; 11013 case BO_LE: 11014 case BO_LT: 11015 case BO_GE: 11016 case BO_GT: 11017 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11018 break; 11019 case BO_EQ: 11020 case BO_NE: 11021 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11022 break; 11023 case BO_And: 11024 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11025 case BO_Xor: 11026 case BO_Or: 11027 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 11028 break; 11029 case BO_LAnd: 11030 case BO_LOr: 11031 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11032 break; 11033 case BO_MulAssign: 11034 case BO_DivAssign: 11035 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11036 Opc == BO_DivAssign); 11037 CompLHSTy = CompResultTy; 11038 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11039 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11040 break; 11041 case BO_RemAssign: 11042 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11043 CompLHSTy = CompResultTy; 11044 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11045 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11046 break; 11047 case BO_AddAssign: 11048 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11049 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11050 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11051 break; 11052 case BO_SubAssign: 11053 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11054 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11055 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11056 break; 11057 case BO_ShlAssign: 11058 case BO_ShrAssign: 11059 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11060 CompLHSTy = CompResultTy; 11061 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11062 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11063 break; 11064 case BO_AndAssign: 11065 case BO_OrAssign: // fallthrough 11066 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11067 case BO_XorAssign: 11068 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 11069 CompLHSTy = CompResultTy; 11070 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11071 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11072 break; 11073 case BO_Comma: 11074 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11075 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11076 VK = RHS.get()->getValueKind(); 11077 OK = RHS.get()->getObjectKind(); 11078 } 11079 break; 11080 } 11081 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11082 return ExprError(); 11083 11084 // Check for array bounds violations for both sides of the BinaryOperator 11085 CheckArrayAccess(LHS.get()); 11086 CheckArrayAccess(RHS.get()); 11087 11088 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11089 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11090 &Context.Idents.get("object_setClass"), 11091 SourceLocation(), LookupOrdinaryName); 11092 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11093 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11094 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11095 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11096 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11097 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11098 } 11099 else 11100 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11101 } 11102 else if (const ObjCIvarRefExpr *OIRE = 11103 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11104 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11105 11106 if (CompResultTy.isNull()) 11107 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11108 OK, OpLoc, FPFeatures.fp_contract); 11109 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11110 OK_ObjCProperty) { 11111 VK = VK_LValue; 11112 OK = LHS.get()->getObjectKind(); 11113 } 11114 return new (Context) CompoundAssignOperator( 11115 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11116 OpLoc, FPFeatures.fp_contract); 11117 } 11118 11119 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11120 /// operators are mixed in a way that suggests that the programmer forgot that 11121 /// comparison operators have higher precedence. The most typical example of 11122 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11123 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11124 SourceLocation OpLoc, Expr *LHSExpr, 11125 Expr *RHSExpr) { 11126 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11127 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11128 11129 // Check that one of the sides is a comparison operator and the other isn't. 11130 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11131 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11132 if (isLeftComp == isRightComp) 11133 return; 11134 11135 // Bitwise operations are sometimes used as eager logical ops. 11136 // Don't diagnose this. 11137 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11138 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11139 if (isLeftBitwise || isRightBitwise) 11140 return; 11141 11142 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11143 OpLoc) 11144 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11145 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11146 SourceRange ParensRange = isLeftComp ? 11147 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11148 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11149 11150 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11151 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11152 SuggestParentheses(Self, OpLoc, 11153 Self.PDiag(diag::note_precedence_silence) << OpStr, 11154 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11155 SuggestParentheses(Self, OpLoc, 11156 Self.PDiag(diag::note_precedence_bitwise_first) 11157 << BinaryOperator::getOpcodeStr(Opc), 11158 ParensRange); 11159 } 11160 11161 /// \brief It accepts a '&&' expr that is inside a '||' one. 11162 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11163 /// in parentheses. 11164 static void 11165 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11166 BinaryOperator *Bop) { 11167 assert(Bop->getOpcode() == BO_LAnd); 11168 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11169 << Bop->getSourceRange() << OpLoc; 11170 SuggestParentheses(Self, Bop->getOperatorLoc(), 11171 Self.PDiag(diag::note_precedence_silence) 11172 << Bop->getOpcodeStr(), 11173 Bop->getSourceRange()); 11174 } 11175 11176 /// \brief Returns true if the given expression can be evaluated as a constant 11177 /// 'true'. 11178 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11179 bool Res; 11180 return !E->isValueDependent() && 11181 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11182 } 11183 11184 /// \brief Returns true if the given expression can be evaluated as a constant 11185 /// 'false'. 11186 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11187 bool Res; 11188 return !E->isValueDependent() && 11189 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11190 } 11191 11192 /// \brief Look for '&&' in the left hand of a '||' expr. 11193 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11194 Expr *LHSExpr, Expr *RHSExpr) { 11195 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11196 if (Bop->getOpcode() == BO_LAnd) { 11197 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11198 if (EvaluatesAsFalse(S, RHSExpr)) 11199 return; 11200 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11201 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11202 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11203 } else if (Bop->getOpcode() == BO_LOr) { 11204 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11205 // If it's "a || b && 1 || c" we didn't warn earlier for 11206 // "a || b && 1", but warn now. 11207 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11208 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11209 } 11210 } 11211 } 11212 } 11213 11214 /// \brief Look for '&&' in the right hand of a '||' expr. 11215 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11216 Expr *LHSExpr, Expr *RHSExpr) { 11217 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11218 if (Bop->getOpcode() == BO_LAnd) { 11219 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11220 if (EvaluatesAsFalse(S, LHSExpr)) 11221 return; 11222 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11223 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11224 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11225 } 11226 } 11227 } 11228 11229 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11230 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11231 /// the '&' expression in parentheses. 11232 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11233 SourceLocation OpLoc, Expr *SubExpr) { 11234 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11235 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11236 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11237 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11238 << Bop->getSourceRange() << OpLoc; 11239 SuggestParentheses(S, Bop->getOperatorLoc(), 11240 S.PDiag(diag::note_precedence_silence) 11241 << Bop->getOpcodeStr(), 11242 Bop->getSourceRange()); 11243 } 11244 } 11245 } 11246 11247 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11248 Expr *SubExpr, StringRef Shift) { 11249 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11250 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11251 StringRef Op = Bop->getOpcodeStr(); 11252 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11253 << Bop->getSourceRange() << OpLoc << Shift << Op; 11254 SuggestParentheses(S, Bop->getOperatorLoc(), 11255 S.PDiag(diag::note_precedence_silence) << Op, 11256 Bop->getSourceRange()); 11257 } 11258 } 11259 } 11260 11261 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11262 Expr *LHSExpr, Expr *RHSExpr) { 11263 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11264 if (!OCE) 11265 return; 11266 11267 FunctionDecl *FD = OCE->getDirectCallee(); 11268 if (!FD || !FD->isOverloadedOperator()) 11269 return; 11270 11271 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11272 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11273 return; 11274 11275 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11276 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11277 << (Kind == OO_LessLess); 11278 SuggestParentheses(S, OCE->getOperatorLoc(), 11279 S.PDiag(diag::note_precedence_silence) 11280 << (Kind == OO_LessLess ? "<<" : ">>"), 11281 OCE->getSourceRange()); 11282 SuggestParentheses(S, OpLoc, 11283 S.PDiag(diag::note_evaluate_comparison_first), 11284 SourceRange(OCE->getArg(1)->getLocStart(), 11285 RHSExpr->getLocEnd())); 11286 } 11287 11288 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11289 /// precedence. 11290 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11291 SourceLocation OpLoc, Expr *LHSExpr, 11292 Expr *RHSExpr){ 11293 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11294 if (BinaryOperator::isBitwiseOp(Opc)) 11295 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11296 11297 // Diagnose "arg1 & arg2 | arg3" 11298 if ((Opc == BO_Or || Opc == BO_Xor) && 11299 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11300 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11301 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11302 } 11303 11304 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11305 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11306 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11307 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11308 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11309 } 11310 11311 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11312 || Opc == BO_Shr) { 11313 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11314 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11315 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11316 } 11317 11318 // Warn on overloaded shift operators and comparisons, such as: 11319 // cout << 5 == 4; 11320 if (BinaryOperator::isComparisonOp(Opc)) 11321 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11322 } 11323 11324 // Binary Operators. 'Tok' is the token for the operator. 11325 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11326 tok::TokenKind Kind, 11327 Expr *LHSExpr, Expr *RHSExpr) { 11328 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11329 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11330 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11331 11332 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11333 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11334 11335 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11336 } 11337 11338 /// Build an overloaded binary operator expression in the given scope. 11339 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11340 BinaryOperatorKind Opc, 11341 Expr *LHS, Expr *RHS) { 11342 // Find all of the overloaded operators visible from this 11343 // point. We perform both an operator-name lookup from the local 11344 // scope and an argument-dependent lookup based on the types of 11345 // the arguments. 11346 UnresolvedSet<16> Functions; 11347 OverloadedOperatorKind OverOp 11348 = BinaryOperator::getOverloadedOperator(Opc); 11349 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11350 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11351 RHS->getType(), Functions); 11352 11353 // Build the (potentially-overloaded, potentially-dependent) 11354 // binary operation. 11355 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11356 } 11357 11358 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11359 BinaryOperatorKind Opc, 11360 Expr *LHSExpr, Expr *RHSExpr) { 11361 // We want to end up calling one of checkPseudoObjectAssignment 11362 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11363 // both expressions are overloadable or either is type-dependent), 11364 // or CreateBuiltinBinOp (in any other case). We also want to get 11365 // any placeholder types out of the way. 11366 11367 // Handle pseudo-objects in the LHS. 11368 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11369 // Assignments with a pseudo-object l-value need special analysis. 11370 if (pty->getKind() == BuiltinType::PseudoObject && 11371 BinaryOperator::isAssignmentOp(Opc)) 11372 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11373 11374 // Don't resolve overloads if the other type is overloadable. 11375 if (pty->getKind() == BuiltinType::Overload) { 11376 // We can't actually test that if we still have a placeholder, 11377 // though. Fortunately, none of the exceptions we see in that 11378 // code below are valid when the LHS is an overload set. Note 11379 // that an overload set can be dependently-typed, but it never 11380 // instantiates to having an overloadable type. 11381 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11382 if (resolvedRHS.isInvalid()) return ExprError(); 11383 RHSExpr = resolvedRHS.get(); 11384 11385 if (RHSExpr->isTypeDependent() || 11386 RHSExpr->getType()->isOverloadableType()) 11387 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11388 } 11389 11390 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11391 if (LHS.isInvalid()) return ExprError(); 11392 LHSExpr = LHS.get(); 11393 } 11394 11395 // Handle pseudo-objects in the RHS. 11396 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11397 // An overload in the RHS can potentially be resolved by the type 11398 // being assigned to. 11399 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11400 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11401 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11402 11403 if (LHSExpr->getType()->isOverloadableType()) 11404 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11405 11406 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11407 } 11408 11409 // Don't resolve overloads if the other type is overloadable. 11410 if (pty->getKind() == BuiltinType::Overload && 11411 LHSExpr->getType()->isOverloadableType()) 11412 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11413 11414 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11415 if (!resolvedRHS.isUsable()) return ExprError(); 11416 RHSExpr = resolvedRHS.get(); 11417 } 11418 11419 if (getLangOpts().CPlusPlus) { 11420 // If either expression is type-dependent, always build an 11421 // overloaded op. 11422 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11423 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11424 11425 // Otherwise, build an overloaded op if either expression has an 11426 // overloadable type. 11427 if (LHSExpr->getType()->isOverloadableType() || 11428 RHSExpr->getType()->isOverloadableType()) 11429 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11430 } 11431 11432 // Build a built-in binary operation. 11433 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11434 } 11435 11436 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11437 UnaryOperatorKind Opc, 11438 Expr *InputExpr) { 11439 ExprResult Input = InputExpr; 11440 ExprValueKind VK = VK_RValue; 11441 ExprObjectKind OK = OK_Ordinary; 11442 QualType resultType; 11443 if (getLangOpts().OpenCL) { 11444 QualType Ty = InputExpr->getType(); 11445 // The only legal unary operation for atomics is '&'. 11446 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11447 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11448 // only with a builtin functions and therefore should be disallowed here. 11449 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11450 || Ty->isBlockPointerType())) { 11451 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11452 << InputExpr->getType() 11453 << Input.get()->getSourceRange()); 11454 } 11455 } 11456 switch (Opc) { 11457 case UO_PreInc: 11458 case UO_PreDec: 11459 case UO_PostInc: 11460 case UO_PostDec: 11461 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11462 OpLoc, 11463 Opc == UO_PreInc || 11464 Opc == UO_PostInc, 11465 Opc == UO_PreInc || 11466 Opc == UO_PreDec); 11467 break; 11468 case UO_AddrOf: 11469 resultType = CheckAddressOfOperand(Input, OpLoc); 11470 RecordModifiableNonNullParam(*this, InputExpr); 11471 break; 11472 case UO_Deref: { 11473 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11474 if (Input.isInvalid()) return ExprError(); 11475 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11476 break; 11477 } 11478 case UO_Plus: 11479 case UO_Minus: 11480 Input = UsualUnaryConversions(Input.get()); 11481 if (Input.isInvalid()) return ExprError(); 11482 resultType = Input.get()->getType(); 11483 if (resultType->isDependentType()) 11484 break; 11485 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11486 break; 11487 else if (resultType->isVectorType() && 11488 // The z vector extensions don't allow + or - with bool vectors. 11489 (!Context.getLangOpts().ZVector || 11490 resultType->getAs<VectorType>()->getVectorKind() != 11491 VectorType::AltiVecBool)) 11492 break; 11493 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11494 Opc == UO_Plus && 11495 resultType->isPointerType()) 11496 break; 11497 11498 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11499 << resultType << Input.get()->getSourceRange()); 11500 11501 case UO_Not: // bitwise complement 11502 Input = UsualUnaryConversions(Input.get()); 11503 if (Input.isInvalid()) 11504 return ExprError(); 11505 resultType = Input.get()->getType(); 11506 if (resultType->isDependentType()) 11507 break; 11508 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11509 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11510 // C99 does not support '~' for complex conjugation. 11511 Diag(OpLoc, diag::ext_integer_complement_complex) 11512 << resultType << Input.get()->getSourceRange(); 11513 else if (resultType->hasIntegerRepresentation()) 11514 break; 11515 else if (resultType->isExtVectorType()) { 11516 if (Context.getLangOpts().OpenCL) { 11517 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11518 // on vector float types. 11519 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11520 if (!T->isIntegerType()) 11521 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11522 << resultType << Input.get()->getSourceRange()); 11523 } 11524 break; 11525 } else { 11526 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11527 << resultType << Input.get()->getSourceRange()); 11528 } 11529 break; 11530 11531 case UO_LNot: // logical negation 11532 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11533 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11534 if (Input.isInvalid()) return ExprError(); 11535 resultType = Input.get()->getType(); 11536 11537 // Though we still have to promote half FP to float... 11538 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11539 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11540 resultType = Context.FloatTy; 11541 } 11542 11543 if (resultType->isDependentType()) 11544 break; 11545 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11546 // C99 6.5.3.3p1: ok, fallthrough; 11547 if (Context.getLangOpts().CPlusPlus) { 11548 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11549 // operand contextually converted to bool. 11550 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11551 ScalarTypeToBooleanCastKind(resultType)); 11552 } else if (Context.getLangOpts().OpenCL && 11553 Context.getLangOpts().OpenCLVersion < 120) { 11554 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11555 // operate on scalar float types. 11556 if (!resultType->isIntegerType()) 11557 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11558 << resultType << Input.get()->getSourceRange()); 11559 } 11560 } else if (resultType->isExtVectorType()) { 11561 if (Context.getLangOpts().OpenCL && 11562 Context.getLangOpts().OpenCLVersion < 120) { 11563 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11564 // operate on vector float types. 11565 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11566 if (!T->isIntegerType()) 11567 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11568 << resultType << Input.get()->getSourceRange()); 11569 } 11570 // Vector logical not returns the signed variant of the operand type. 11571 resultType = GetSignedVectorType(resultType); 11572 break; 11573 } else { 11574 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11575 << resultType << Input.get()->getSourceRange()); 11576 } 11577 11578 // LNot always has type int. C99 6.5.3.3p5. 11579 // In C++, it's bool. C++ 5.3.1p8 11580 resultType = Context.getLogicalOperationType(); 11581 break; 11582 case UO_Real: 11583 case UO_Imag: 11584 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11585 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11586 // complex l-values to ordinary l-values and all other values to r-values. 11587 if (Input.isInvalid()) return ExprError(); 11588 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11589 if (Input.get()->getValueKind() != VK_RValue && 11590 Input.get()->getObjectKind() == OK_Ordinary) 11591 VK = Input.get()->getValueKind(); 11592 } else if (!getLangOpts().CPlusPlus) { 11593 // In C, a volatile scalar is read by __imag. In C++, it is not. 11594 Input = DefaultLvalueConversion(Input.get()); 11595 } 11596 break; 11597 case UO_Extension: 11598 case UO_Coawait: 11599 resultType = Input.get()->getType(); 11600 VK = Input.get()->getValueKind(); 11601 OK = Input.get()->getObjectKind(); 11602 break; 11603 } 11604 if (resultType.isNull() || Input.isInvalid()) 11605 return ExprError(); 11606 11607 // Check for array bounds violations in the operand of the UnaryOperator, 11608 // except for the '*' and '&' operators that have to be handled specially 11609 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11610 // that are explicitly defined as valid by the standard). 11611 if (Opc != UO_AddrOf && Opc != UO_Deref) 11612 CheckArrayAccess(Input.get()); 11613 11614 return new (Context) 11615 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11616 } 11617 11618 /// \brief Determine whether the given expression is a qualified member 11619 /// access expression, of a form that could be turned into a pointer to member 11620 /// with the address-of operator. 11621 static bool isQualifiedMemberAccess(Expr *E) { 11622 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11623 if (!DRE->getQualifier()) 11624 return false; 11625 11626 ValueDecl *VD = DRE->getDecl(); 11627 if (!VD->isCXXClassMember()) 11628 return false; 11629 11630 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11631 return true; 11632 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11633 return Method->isInstance(); 11634 11635 return false; 11636 } 11637 11638 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11639 if (!ULE->getQualifier()) 11640 return false; 11641 11642 for (NamedDecl *D : ULE->decls()) { 11643 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11644 if (Method->isInstance()) 11645 return true; 11646 } else { 11647 // Overload set does not contain methods. 11648 break; 11649 } 11650 } 11651 11652 return false; 11653 } 11654 11655 return false; 11656 } 11657 11658 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11659 UnaryOperatorKind Opc, Expr *Input) { 11660 // First things first: handle placeholders so that the 11661 // overloaded-operator check considers the right type. 11662 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11663 // Increment and decrement of pseudo-object references. 11664 if (pty->getKind() == BuiltinType::PseudoObject && 11665 UnaryOperator::isIncrementDecrementOp(Opc)) 11666 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11667 11668 // extension is always a builtin operator. 11669 if (Opc == UO_Extension) 11670 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11671 11672 // & gets special logic for several kinds of placeholder. 11673 // The builtin code knows what to do. 11674 if (Opc == UO_AddrOf && 11675 (pty->getKind() == BuiltinType::Overload || 11676 pty->getKind() == BuiltinType::UnknownAny || 11677 pty->getKind() == BuiltinType::BoundMember)) 11678 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11679 11680 // Anything else needs to be handled now. 11681 ExprResult Result = CheckPlaceholderExpr(Input); 11682 if (Result.isInvalid()) return ExprError(); 11683 Input = Result.get(); 11684 } 11685 11686 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11687 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11688 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11689 // Find all of the overloaded operators visible from this 11690 // point. We perform both an operator-name lookup from the local 11691 // scope and an argument-dependent lookup based on the types of 11692 // the arguments. 11693 UnresolvedSet<16> Functions; 11694 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11695 if (S && OverOp != OO_None) 11696 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11697 Functions); 11698 11699 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11700 } 11701 11702 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11703 } 11704 11705 // Unary Operators. 'Tok' is the token for the operator. 11706 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11707 tok::TokenKind Op, Expr *Input) { 11708 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11709 } 11710 11711 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11712 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11713 LabelDecl *TheDecl) { 11714 TheDecl->markUsed(Context); 11715 // Create the AST node. The address of a label always has type 'void*'. 11716 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11717 Context.getPointerType(Context.VoidTy)); 11718 } 11719 11720 /// Given the last statement in a statement-expression, check whether 11721 /// the result is a producing expression (like a call to an 11722 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11723 /// release out of the full-expression. Otherwise, return null. 11724 /// Cannot fail. 11725 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11726 // Should always be wrapped with one of these. 11727 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11728 if (!cleanups) return nullptr; 11729 11730 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11731 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11732 return nullptr; 11733 11734 // Splice out the cast. This shouldn't modify any interesting 11735 // features of the statement. 11736 Expr *producer = cast->getSubExpr(); 11737 assert(producer->getType() == cast->getType()); 11738 assert(producer->getValueKind() == cast->getValueKind()); 11739 cleanups->setSubExpr(producer); 11740 return cleanups; 11741 } 11742 11743 void Sema::ActOnStartStmtExpr() { 11744 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11745 } 11746 11747 void Sema::ActOnStmtExprError() { 11748 // Note that function is also called by TreeTransform when leaving a 11749 // StmtExpr scope without rebuilding anything. 11750 11751 DiscardCleanupsInEvaluationContext(); 11752 PopExpressionEvaluationContext(); 11753 } 11754 11755 ExprResult 11756 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11757 SourceLocation RPLoc) { // "({..})" 11758 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11759 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11760 11761 if (hasAnyUnrecoverableErrorsInThisFunction()) 11762 DiscardCleanupsInEvaluationContext(); 11763 assert(!Cleanup.exprNeedsCleanups() && 11764 "cleanups within StmtExpr not correctly bound!"); 11765 PopExpressionEvaluationContext(); 11766 11767 // FIXME: there are a variety of strange constraints to enforce here, for 11768 // example, it is not possible to goto into a stmt expression apparently. 11769 // More semantic analysis is needed. 11770 11771 // If there are sub-stmts in the compound stmt, take the type of the last one 11772 // as the type of the stmtexpr. 11773 QualType Ty = Context.VoidTy; 11774 bool StmtExprMayBindToTemp = false; 11775 if (!Compound->body_empty()) { 11776 Stmt *LastStmt = Compound->body_back(); 11777 LabelStmt *LastLabelStmt = nullptr; 11778 // If LastStmt is a label, skip down through into the body. 11779 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11780 LastLabelStmt = Label; 11781 LastStmt = Label->getSubStmt(); 11782 } 11783 11784 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11785 // Do function/array conversion on the last expression, but not 11786 // lvalue-to-rvalue. However, initialize an unqualified type. 11787 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11788 if (LastExpr.isInvalid()) 11789 return ExprError(); 11790 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11791 11792 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11793 // In ARC, if the final expression ends in a consume, splice 11794 // the consume out and bind it later. In the alternate case 11795 // (when dealing with a retainable type), the result 11796 // initialization will create a produce. In both cases the 11797 // result will be +1, and we'll need to balance that out with 11798 // a bind. 11799 if (Expr *rebuiltLastStmt 11800 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11801 LastExpr = rebuiltLastStmt; 11802 } else { 11803 LastExpr = PerformCopyInitialization( 11804 InitializedEntity::InitializeResult(LPLoc, 11805 Ty, 11806 false), 11807 SourceLocation(), 11808 LastExpr); 11809 } 11810 11811 if (LastExpr.isInvalid()) 11812 return ExprError(); 11813 if (LastExpr.get() != nullptr) { 11814 if (!LastLabelStmt) 11815 Compound->setLastStmt(LastExpr.get()); 11816 else 11817 LastLabelStmt->setSubStmt(LastExpr.get()); 11818 StmtExprMayBindToTemp = true; 11819 } 11820 } 11821 } 11822 } 11823 11824 // FIXME: Check that expression type is complete/non-abstract; statement 11825 // expressions are not lvalues. 11826 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11827 if (StmtExprMayBindToTemp) 11828 return MaybeBindToTemporary(ResStmtExpr); 11829 return ResStmtExpr; 11830 } 11831 11832 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11833 TypeSourceInfo *TInfo, 11834 ArrayRef<OffsetOfComponent> Components, 11835 SourceLocation RParenLoc) { 11836 QualType ArgTy = TInfo->getType(); 11837 bool Dependent = ArgTy->isDependentType(); 11838 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11839 11840 // We must have at least one component that refers to the type, and the first 11841 // one is known to be a field designator. Verify that the ArgTy represents 11842 // a struct/union/class. 11843 if (!Dependent && !ArgTy->isRecordType()) 11844 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11845 << ArgTy << TypeRange); 11846 11847 // Type must be complete per C99 7.17p3 because a declaring a variable 11848 // with an incomplete type would be ill-formed. 11849 if (!Dependent 11850 && RequireCompleteType(BuiltinLoc, ArgTy, 11851 diag::err_offsetof_incomplete_type, TypeRange)) 11852 return ExprError(); 11853 11854 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11855 // GCC extension, diagnose them. 11856 // FIXME: This diagnostic isn't actually visible because the location is in 11857 // a system header! 11858 if (Components.size() != 1) 11859 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11860 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11861 11862 bool DidWarnAboutNonPOD = false; 11863 QualType CurrentType = ArgTy; 11864 SmallVector<OffsetOfNode, 4> Comps; 11865 SmallVector<Expr*, 4> Exprs; 11866 for (const OffsetOfComponent &OC : Components) { 11867 if (OC.isBrackets) { 11868 // Offset of an array sub-field. TODO: Should we allow vector elements? 11869 if (!CurrentType->isDependentType()) { 11870 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11871 if(!AT) 11872 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11873 << CurrentType); 11874 CurrentType = AT->getElementType(); 11875 } else 11876 CurrentType = Context.DependentTy; 11877 11878 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11879 if (IdxRval.isInvalid()) 11880 return ExprError(); 11881 Expr *Idx = IdxRval.get(); 11882 11883 // The expression must be an integral expression. 11884 // FIXME: An integral constant expression? 11885 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11886 !Idx->getType()->isIntegerType()) 11887 return ExprError(Diag(Idx->getLocStart(), 11888 diag::err_typecheck_subscript_not_integer) 11889 << Idx->getSourceRange()); 11890 11891 // Record this array index. 11892 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11893 Exprs.push_back(Idx); 11894 continue; 11895 } 11896 11897 // Offset of a field. 11898 if (CurrentType->isDependentType()) { 11899 // We have the offset of a field, but we can't look into the dependent 11900 // type. Just record the identifier of the field. 11901 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11902 CurrentType = Context.DependentTy; 11903 continue; 11904 } 11905 11906 // We need to have a complete type to look into. 11907 if (RequireCompleteType(OC.LocStart, CurrentType, 11908 diag::err_offsetof_incomplete_type)) 11909 return ExprError(); 11910 11911 // Look for the designated field. 11912 const RecordType *RC = CurrentType->getAs<RecordType>(); 11913 if (!RC) 11914 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11915 << CurrentType); 11916 RecordDecl *RD = RC->getDecl(); 11917 11918 // C++ [lib.support.types]p5: 11919 // The macro offsetof accepts a restricted set of type arguments in this 11920 // International Standard. type shall be a POD structure or a POD union 11921 // (clause 9). 11922 // C++11 [support.types]p4: 11923 // If type is not a standard-layout class (Clause 9), the results are 11924 // undefined. 11925 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11926 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11927 unsigned DiagID = 11928 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11929 : diag::ext_offsetof_non_pod_type; 11930 11931 if (!IsSafe && !DidWarnAboutNonPOD && 11932 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11933 PDiag(DiagID) 11934 << SourceRange(Components[0].LocStart, OC.LocEnd) 11935 << CurrentType)) 11936 DidWarnAboutNonPOD = true; 11937 } 11938 11939 // Look for the field. 11940 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11941 LookupQualifiedName(R, RD); 11942 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11943 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11944 if (!MemberDecl) { 11945 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11946 MemberDecl = IndirectMemberDecl->getAnonField(); 11947 } 11948 11949 if (!MemberDecl) 11950 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11951 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11952 OC.LocEnd)); 11953 11954 // C99 7.17p3: 11955 // (If the specified member is a bit-field, the behavior is undefined.) 11956 // 11957 // We diagnose this as an error. 11958 if (MemberDecl->isBitField()) { 11959 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11960 << MemberDecl->getDeclName() 11961 << SourceRange(BuiltinLoc, RParenLoc); 11962 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11963 return ExprError(); 11964 } 11965 11966 RecordDecl *Parent = MemberDecl->getParent(); 11967 if (IndirectMemberDecl) 11968 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11969 11970 // If the member was found in a base class, introduce OffsetOfNodes for 11971 // the base class indirections. 11972 CXXBasePaths Paths; 11973 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11974 Paths)) { 11975 if (Paths.getDetectedVirtual()) { 11976 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11977 << MemberDecl->getDeclName() 11978 << SourceRange(BuiltinLoc, RParenLoc); 11979 return ExprError(); 11980 } 11981 11982 CXXBasePath &Path = Paths.front(); 11983 for (const CXXBasePathElement &B : Path) 11984 Comps.push_back(OffsetOfNode(B.Base)); 11985 } 11986 11987 if (IndirectMemberDecl) { 11988 for (auto *FI : IndirectMemberDecl->chain()) { 11989 assert(isa<FieldDecl>(FI)); 11990 Comps.push_back(OffsetOfNode(OC.LocStart, 11991 cast<FieldDecl>(FI), OC.LocEnd)); 11992 } 11993 } else 11994 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11995 11996 CurrentType = MemberDecl->getType().getNonReferenceType(); 11997 } 11998 11999 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12000 Comps, Exprs, RParenLoc); 12001 } 12002 12003 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12004 SourceLocation BuiltinLoc, 12005 SourceLocation TypeLoc, 12006 ParsedType ParsedArgTy, 12007 ArrayRef<OffsetOfComponent> Components, 12008 SourceLocation RParenLoc) { 12009 12010 TypeSourceInfo *ArgTInfo; 12011 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12012 if (ArgTy.isNull()) 12013 return ExprError(); 12014 12015 if (!ArgTInfo) 12016 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12017 12018 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12019 } 12020 12021 12022 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12023 Expr *CondExpr, 12024 Expr *LHSExpr, Expr *RHSExpr, 12025 SourceLocation RPLoc) { 12026 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12027 12028 ExprValueKind VK = VK_RValue; 12029 ExprObjectKind OK = OK_Ordinary; 12030 QualType resType; 12031 bool ValueDependent = false; 12032 bool CondIsTrue = false; 12033 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12034 resType = Context.DependentTy; 12035 ValueDependent = true; 12036 } else { 12037 // The conditional expression is required to be a constant expression. 12038 llvm::APSInt condEval(32); 12039 ExprResult CondICE 12040 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12041 diag::err_typecheck_choose_expr_requires_constant, false); 12042 if (CondICE.isInvalid()) 12043 return ExprError(); 12044 CondExpr = CondICE.get(); 12045 CondIsTrue = condEval.getZExtValue(); 12046 12047 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12048 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12049 12050 resType = ActiveExpr->getType(); 12051 ValueDependent = ActiveExpr->isValueDependent(); 12052 VK = ActiveExpr->getValueKind(); 12053 OK = ActiveExpr->getObjectKind(); 12054 } 12055 12056 return new (Context) 12057 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12058 CondIsTrue, resType->isDependentType(), ValueDependent); 12059 } 12060 12061 //===----------------------------------------------------------------------===// 12062 // Clang Extensions. 12063 //===----------------------------------------------------------------------===// 12064 12065 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12066 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12067 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12068 12069 if (LangOpts.CPlusPlus) { 12070 Decl *ManglingContextDecl; 12071 if (MangleNumberingContext *MCtx = 12072 getCurrentMangleNumberContext(Block->getDeclContext(), 12073 ManglingContextDecl)) { 12074 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12075 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12076 } 12077 } 12078 12079 PushBlockScope(CurScope, Block); 12080 CurContext->addDecl(Block); 12081 if (CurScope) 12082 PushDeclContext(CurScope, Block); 12083 else 12084 CurContext = Block; 12085 12086 getCurBlock()->HasImplicitReturnType = true; 12087 12088 // Enter a new evaluation context to insulate the block from any 12089 // cleanups from the enclosing full-expression. 12090 PushExpressionEvaluationContext(PotentiallyEvaluated); 12091 } 12092 12093 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12094 Scope *CurScope) { 12095 assert(ParamInfo.getIdentifier() == nullptr && 12096 "block-id should have no identifier!"); 12097 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12098 BlockScopeInfo *CurBlock = getCurBlock(); 12099 12100 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12101 QualType T = Sig->getType(); 12102 12103 // FIXME: We should allow unexpanded parameter packs here, but that would, 12104 // in turn, make the block expression contain unexpanded parameter packs. 12105 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12106 // Drop the parameters. 12107 FunctionProtoType::ExtProtoInfo EPI; 12108 EPI.HasTrailingReturn = false; 12109 EPI.TypeQuals |= DeclSpec::TQ_const; 12110 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12111 Sig = Context.getTrivialTypeSourceInfo(T); 12112 } 12113 12114 // GetTypeForDeclarator always produces a function type for a block 12115 // literal signature. Furthermore, it is always a FunctionProtoType 12116 // unless the function was written with a typedef. 12117 assert(T->isFunctionType() && 12118 "GetTypeForDeclarator made a non-function block signature"); 12119 12120 // Look for an explicit signature in that function type. 12121 FunctionProtoTypeLoc ExplicitSignature; 12122 12123 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12124 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12125 12126 // Check whether that explicit signature was synthesized by 12127 // GetTypeForDeclarator. If so, don't save that as part of the 12128 // written signature. 12129 if (ExplicitSignature.getLocalRangeBegin() == 12130 ExplicitSignature.getLocalRangeEnd()) { 12131 // This would be much cheaper if we stored TypeLocs instead of 12132 // TypeSourceInfos. 12133 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12134 unsigned Size = Result.getFullDataSize(); 12135 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12136 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12137 12138 ExplicitSignature = FunctionProtoTypeLoc(); 12139 } 12140 } 12141 12142 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12143 CurBlock->FunctionType = T; 12144 12145 const FunctionType *Fn = T->getAs<FunctionType>(); 12146 QualType RetTy = Fn->getReturnType(); 12147 bool isVariadic = 12148 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12149 12150 CurBlock->TheDecl->setIsVariadic(isVariadic); 12151 12152 // Context.DependentTy is used as a placeholder for a missing block 12153 // return type. TODO: what should we do with declarators like: 12154 // ^ * { ... } 12155 // If the answer is "apply template argument deduction".... 12156 if (RetTy != Context.DependentTy) { 12157 CurBlock->ReturnType = RetTy; 12158 CurBlock->TheDecl->setBlockMissingReturnType(false); 12159 CurBlock->HasImplicitReturnType = false; 12160 } 12161 12162 // Push block parameters from the declarator if we had them. 12163 SmallVector<ParmVarDecl*, 8> Params; 12164 if (ExplicitSignature) { 12165 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12166 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12167 if (Param->getIdentifier() == nullptr && 12168 !Param->isImplicit() && 12169 !Param->isInvalidDecl() && 12170 !getLangOpts().CPlusPlus) 12171 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12172 Params.push_back(Param); 12173 } 12174 12175 // Fake up parameter variables if we have a typedef, like 12176 // ^ fntype { ... } 12177 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12178 for (const auto &I : Fn->param_types()) { 12179 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12180 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12181 Params.push_back(Param); 12182 } 12183 } 12184 12185 // Set the parameters on the block decl. 12186 if (!Params.empty()) { 12187 CurBlock->TheDecl->setParams(Params); 12188 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12189 /*CheckParameterNames=*/false); 12190 } 12191 12192 // Finally we can process decl attributes. 12193 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12194 12195 // Put the parameter variables in scope. 12196 for (auto AI : CurBlock->TheDecl->parameters()) { 12197 AI->setOwningFunction(CurBlock->TheDecl); 12198 12199 // If this has an identifier, add it to the scope stack. 12200 if (AI->getIdentifier()) { 12201 CheckShadow(CurBlock->TheScope, AI); 12202 12203 PushOnScopeChains(AI, CurBlock->TheScope); 12204 } 12205 } 12206 } 12207 12208 /// ActOnBlockError - If there is an error parsing a block, this callback 12209 /// is invoked to pop the information about the block from the action impl. 12210 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12211 // Leave the expression-evaluation context. 12212 DiscardCleanupsInEvaluationContext(); 12213 PopExpressionEvaluationContext(); 12214 12215 // Pop off CurBlock, handle nested blocks. 12216 PopDeclContext(); 12217 PopFunctionScopeInfo(); 12218 } 12219 12220 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12221 /// literal was successfully completed. ^(int x){...} 12222 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12223 Stmt *Body, Scope *CurScope) { 12224 // If blocks are disabled, emit an error. 12225 if (!LangOpts.Blocks) 12226 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12227 12228 // Leave the expression-evaluation context. 12229 if (hasAnyUnrecoverableErrorsInThisFunction()) 12230 DiscardCleanupsInEvaluationContext(); 12231 assert(!Cleanup.exprNeedsCleanups() && 12232 "cleanups within block not correctly bound!"); 12233 PopExpressionEvaluationContext(); 12234 12235 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12236 12237 if (BSI->HasImplicitReturnType) 12238 deduceClosureReturnType(*BSI); 12239 12240 PopDeclContext(); 12241 12242 QualType RetTy = Context.VoidTy; 12243 if (!BSI->ReturnType.isNull()) 12244 RetTy = BSI->ReturnType; 12245 12246 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12247 QualType BlockTy; 12248 12249 // Set the captured variables on the block. 12250 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12251 SmallVector<BlockDecl::Capture, 4> Captures; 12252 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12253 if (Cap.isThisCapture()) 12254 continue; 12255 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12256 Cap.isNested(), Cap.getInitExpr()); 12257 Captures.push_back(NewCap); 12258 } 12259 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12260 12261 // If the user wrote a function type in some form, try to use that. 12262 if (!BSI->FunctionType.isNull()) { 12263 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12264 12265 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12266 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12267 12268 // Turn protoless block types into nullary block types. 12269 if (isa<FunctionNoProtoType>(FTy)) { 12270 FunctionProtoType::ExtProtoInfo EPI; 12271 EPI.ExtInfo = Ext; 12272 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12273 12274 // Otherwise, if we don't need to change anything about the function type, 12275 // preserve its sugar structure. 12276 } else if (FTy->getReturnType() == RetTy && 12277 (!NoReturn || FTy->getNoReturnAttr())) { 12278 BlockTy = BSI->FunctionType; 12279 12280 // Otherwise, make the minimal modifications to the function type. 12281 } else { 12282 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12283 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12284 EPI.TypeQuals = 0; // FIXME: silently? 12285 EPI.ExtInfo = Ext; 12286 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12287 } 12288 12289 // If we don't have a function type, just build one from nothing. 12290 } else { 12291 FunctionProtoType::ExtProtoInfo EPI; 12292 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12293 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12294 } 12295 12296 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12297 BlockTy = Context.getBlockPointerType(BlockTy); 12298 12299 // If needed, diagnose invalid gotos and switches in the block. 12300 if (getCurFunction()->NeedsScopeChecking() && 12301 !PP.isCodeCompletionEnabled()) 12302 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12303 12304 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12305 12306 // Try to apply the named return value optimization. We have to check again 12307 // if we can do this, though, because blocks keep return statements around 12308 // to deduce an implicit return type. 12309 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12310 !BSI->TheDecl->isDependentContext()) 12311 computeNRVO(Body, BSI); 12312 12313 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12314 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12315 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12316 12317 // If the block isn't obviously global, i.e. it captures anything at 12318 // all, then we need to do a few things in the surrounding context: 12319 if (Result->getBlockDecl()->hasCaptures()) { 12320 // First, this expression has a new cleanup object. 12321 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12322 Cleanup.setExprNeedsCleanups(true); 12323 12324 // It also gets a branch-protected scope if any of the captured 12325 // variables needs destruction. 12326 for (const auto &CI : Result->getBlockDecl()->captures()) { 12327 const VarDecl *var = CI.getVariable(); 12328 if (var->getType().isDestructedType() != QualType::DK_none) { 12329 getCurFunction()->setHasBranchProtectedScope(); 12330 break; 12331 } 12332 } 12333 } 12334 12335 return Result; 12336 } 12337 12338 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12339 SourceLocation RPLoc) { 12340 TypeSourceInfo *TInfo; 12341 GetTypeFromParser(Ty, &TInfo); 12342 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12343 } 12344 12345 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12346 Expr *E, TypeSourceInfo *TInfo, 12347 SourceLocation RPLoc) { 12348 Expr *OrigExpr = E; 12349 bool IsMS = false; 12350 12351 // CUDA device code does not support varargs. 12352 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12353 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12354 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12355 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12356 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12357 } 12358 } 12359 12360 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12361 // as Microsoft ABI on an actual Microsoft platform, where 12362 // __builtin_ms_va_list and __builtin_va_list are the same.) 12363 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12364 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12365 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12366 if (Context.hasSameType(MSVaListType, E->getType())) { 12367 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12368 return ExprError(); 12369 IsMS = true; 12370 } 12371 } 12372 12373 // Get the va_list type 12374 QualType VaListType = Context.getBuiltinVaListType(); 12375 if (!IsMS) { 12376 if (VaListType->isArrayType()) { 12377 // Deal with implicit array decay; for example, on x86-64, 12378 // va_list is an array, but it's supposed to decay to 12379 // a pointer for va_arg. 12380 VaListType = Context.getArrayDecayedType(VaListType); 12381 // Make sure the input expression also decays appropriately. 12382 ExprResult Result = UsualUnaryConversions(E); 12383 if (Result.isInvalid()) 12384 return ExprError(); 12385 E = Result.get(); 12386 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12387 // If va_list is a record type and we are compiling in C++ mode, 12388 // check the argument using reference binding. 12389 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12390 Context, Context.getLValueReferenceType(VaListType), false); 12391 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12392 if (Init.isInvalid()) 12393 return ExprError(); 12394 E = Init.getAs<Expr>(); 12395 } else { 12396 // Otherwise, the va_list argument must be an l-value because 12397 // it is modified by va_arg. 12398 if (!E->isTypeDependent() && 12399 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12400 return ExprError(); 12401 } 12402 } 12403 12404 if (!IsMS && !E->isTypeDependent() && 12405 !Context.hasSameType(VaListType, E->getType())) 12406 return ExprError(Diag(E->getLocStart(), 12407 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12408 << OrigExpr->getType() << E->getSourceRange()); 12409 12410 if (!TInfo->getType()->isDependentType()) { 12411 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12412 diag::err_second_parameter_to_va_arg_incomplete, 12413 TInfo->getTypeLoc())) 12414 return ExprError(); 12415 12416 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12417 TInfo->getType(), 12418 diag::err_second_parameter_to_va_arg_abstract, 12419 TInfo->getTypeLoc())) 12420 return ExprError(); 12421 12422 if (!TInfo->getType().isPODType(Context)) { 12423 Diag(TInfo->getTypeLoc().getBeginLoc(), 12424 TInfo->getType()->isObjCLifetimeType() 12425 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12426 : diag::warn_second_parameter_to_va_arg_not_pod) 12427 << TInfo->getType() 12428 << TInfo->getTypeLoc().getSourceRange(); 12429 } 12430 12431 // Check for va_arg where arguments of the given type will be promoted 12432 // (i.e. this va_arg is guaranteed to have undefined behavior). 12433 QualType PromoteType; 12434 if (TInfo->getType()->isPromotableIntegerType()) { 12435 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12436 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12437 PromoteType = QualType(); 12438 } 12439 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12440 PromoteType = Context.DoubleTy; 12441 if (!PromoteType.isNull()) 12442 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12443 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12444 << TInfo->getType() 12445 << PromoteType 12446 << TInfo->getTypeLoc().getSourceRange()); 12447 } 12448 12449 QualType T = TInfo->getType().getNonLValueExprType(Context); 12450 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12451 } 12452 12453 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12454 // The type of __null will be int or long, depending on the size of 12455 // pointers on the target. 12456 QualType Ty; 12457 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12458 if (pw == Context.getTargetInfo().getIntWidth()) 12459 Ty = Context.IntTy; 12460 else if (pw == Context.getTargetInfo().getLongWidth()) 12461 Ty = Context.LongTy; 12462 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12463 Ty = Context.LongLongTy; 12464 else { 12465 llvm_unreachable("I don't know size of pointer!"); 12466 } 12467 12468 return new (Context) GNUNullExpr(Ty, TokenLoc); 12469 } 12470 12471 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12472 bool Diagnose) { 12473 if (!getLangOpts().ObjC1) 12474 return false; 12475 12476 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12477 if (!PT) 12478 return false; 12479 12480 if (!PT->isObjCIdType()) { 12481 // Check if the destination is the 'NSString' interface. 12482 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12483 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12484 return false; 12485 } 12486 12487 // Ignore any parens, implicit casts (should only be 12488 // array-to-pointer decays), and not-so-opaque values. The last is 12489 // important for making this trigger for property assignments. 12490 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12491 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12492 if (OV->getSourceExpr()) 12493 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12494 12495 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12496 if (!SL || !SL->isAscii()) 12497 return false; 12498 if (Diagnose) { 12499 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12500 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12501 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12502 } 12503 return true; 12504 } 12505 12506 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12507 const Expr *SrcExpr) { 12508 if (!DstType->isFunctionPointerType() || 12509 !SrcExpr->getType()->isFunctionType()) 12510 return false; 12511 12512 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12513 if (!DRE) 12514 return false; 12515 12516 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12517 if (!FD) 12518 return false; 12519 12520 return !S.checkAddressOfFunctionIsAvailable(FD, 12521 /*Complain=*/true, 12522 SrcExpr->getLocStart()); 12523 } 12524 12525 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12526 SourceLocation Loc, 12527 QualType DstType, QualType SrcType, 12528 Expr *SrcExpr, AssignmentAction Action, 12529 bool *Complained) { 12530 if (Complained) 12531 *Complained = false; 12532 12533 // Decode the result (notice that AST's are still created for extensions). 12534 bool CheckInferredResultType = false; 12535 bool isInvalid = false; 12536 unsigned DiagKind = 0; 12537 FixItHint Hint; 12538 ConversionFixItGenerator ConvHints; 12539 bool MayHaveConvFixit = false; 12540 bool MayHaveFunctionDiff = false; 12541 const ObjCInterfaceDecl *IFace = nullptr; 12542 const ObjCProtocolDecl *PDecl = nullptr; 12543 12544 switch (ConvTy) { 12545 case Compatible: 12546 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12547 return false; 12548 12549 case PointerToInt: 12550 DiagKind = diag::ext_typecheck_convert_pointer_int; 12551 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12552 MayHaveConvFixit = true; 12553 break; 12554 case IntToPointer: 12555 DiagKind = diag::ext_typecheck_convert_int_pointer; 12556 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12557 MayHaveConvFixit = true; 12558 break; 12559 case IncompatiblePointer: 12560 if (Action == AA_Passing_CFAudited) 12561 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12562 else if (SrcType->isFunctionPointerType() && 12563 DstType->isFunctionPointerType()) 12564 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12565 else 12566 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12567 12568 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12569 SrcType->isObjCObjectPointerType(); 12570 if (Hint.isNull() && !CheckInferredResultType) { 12571 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12572 } 12573 else if (CheckInferredResultType) { 12574 SrcType = SrcType.getUnqualifiedType(); 12575 DstType = DstType.getUnqualifiedType(); 12576 } 12577 MayHaveConvFixit = true; 12578 break; 12579 case IncompatiblePointerSign: 12580 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12581 break; 12582 case FunctionVoidPointer: 12583 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12584 break; 12585 case IncompatiblePointerDiscardsQualifiers: { 12586 // Perform array-to-pointer decay if necessary. 12587 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12588 12589 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12590 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12591 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12592 DiagKind = diag::err_typecheck_incompatible_address_space; 12593 break; 12594 12595 12596 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12597 DiagKind = diag::err_typecheck_incompatible_ownership; 12598 break; 12599 } 12600 12601 llvm_unreachable("unknown error case for discarding qualifiers!"); 12602 // fallthrough 12603 } 12604 case CompatiblePointerDiscardsQualifiers: 12605 // If the qualifiers lost were because we were applying the 12606 // (deprecated) C++ conversion from a string literal to a char* 12607 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12608 // Ideally, this check would be performed in 12609 // checkPointerTypesForAssignment. However, that would require a 12610 // bit of refactoring (so that the second argument is an 12611 // expression, rather than a type), which should be done as part 12612 // of a larger effort to fix checkPointerTypesForAssignment for 12613 // C++ semantics. 12614 if (getLangOpts().CPlusPlus && 12615 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12616 return false; 12617 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12618 break; 12619 case IncompatibleNestedPointerQualifiers: 12620 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12621 break; 12622 case IntToBlockPointer: 12623 DiagKind = diag::err_int_to_block_pointer; 12624 break; 12625 case IncompatibleBlockPointer: 12626 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12627 break; 12628 case IncompatibleObjCQualifiedId: { 12629 if (SrcType->isObjCQualifiedIdType()) { 12630 const ObjCObjectPointerType *srcOPT = 12631 SrcType->getAs<ObjCObjectPointerType>(); 12632 for (auto *srcProto : srcOPT->quals()) { 12633 PDecl = srcProto; 12634 break; 12635 } 12636 if (const ObjCInterfaceType *IFaceT = 12637 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12638 IFace = IFaceT->getDecl(); 12639 } 12640 else if (DstType->isObjCQualifiedIdType()) { 12641 const ObjCObjectPointerType *dstOPT = 12642 DstType->getAs<ObjCObjectPointerType>(); 12643 for (auto *dstProto : dstOPT->quals()) { 12644 PDecl = dstProto; 12645 break; 12646 } 12647 if (const ObjCInterfaceType *IFaceT = 12648 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12649 IFace = IFaceT->getDecl(); 12650 } 12651 DiagKind = diag::warn_incompatible_qualified_id; 12652 break; 12653 } 12654 case IncompatibleVectors: 12655 DiagKind = diag::warn_incompatible_vectors; 12656 break; 12657 case IncompatibleObjCWeakRef: 12658 DiagKind = diag::err_arc_weak_unavailable_assign; 12659 break; 12660 case Incompatible: 12661 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12662 if (Complained) 12663 *Complained = true; 12664 return true; 12665 } 12666 12667 DiagKind = diag::err_typecheck_convert_incompatible; 12668 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12669 MayHaveConvFixit = true; 12670 isInvalid = true; 12671 MayHaveFunctionDiff = true; 12672 break; 12673 } 12674 12675 QualType FirstType, SecondType; 12676 switch (Action) { 12677 case AA_Assigning: 12678 case AA_Initializing: 12679 // The destination type comes first. 12680 FirstType = DstType; 12681 SecondType = SrcType; 12682 break; 12683 12684 case AA_Returning: 12685 case AA_Passing: 12686 case AA_Passing_CFAudited: 12687 case AA_Converting: 12688 case AA_Sending: 12689 case AA_Casting: 12690 // The source type comes first. 12691 FirstType = SrcType; 12692 SecondType = DstType; 12693 break; 12694 } 12695 12696 PartialDiagnostic FDiag = PDiag(DiagKind); 12697 if (Action == AA_Passing_CFAudited) 12698 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12699 else 12700 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12701 12702 // If we can fix the conversion, suggest the FixIts. 12703 assert(ConvHints.isNull() || Hint.isNull()); 12704 if (!ConvHints.isNull()) { 12705 for (FixItHint &H : ConvHints.Hints) 12706 FDiag << H; 12707 } else { 12708 FDiag << Hint; 12709 } 12710 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12711 12712 if (MayHaveFunctionDiff) 12713 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12714 12715 Diag(Loc, FDiag); 12716 if (DiagKind == diag::warn_incompatible_qualified_id && 12717 PDecl && IFace && !IFace->hasDefinition()) 12718 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12719 << IFace->getName() << PDecl->getName(); 12720 12721 if (SecondType == Context.OverloadTy) 12722 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12723 FirstType, /*TakingAddress=*/true); 12724 12725 if (CheckInferredResultType) 12726 EmitRelatedResultTypeNote(SrcExpr); 12727 12728 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12729 EmitRelatedResultTypeNoteForReturn(DstType); 12730 12731 if (Complained) 12732 *Complained = true; 12733 return isInvalid; 12734 } 12735 12736 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12737 llvm::APSInt *Result) { 12738 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12739 public: 12740 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12741 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12742 } 12743 } Diagnoser; 12744 12745 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12746 } 12747 12748 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12749 llvm::APSInt *Result, 12750 unsigned DiagID, 12751 bool AllowFold) { 12752 class IDDiagnoser : public VerifyICEDiagnoser { 12753 unsigned DiagID; 12754 12755 public: 12756 IDDiagnoser(unsigned DiagID) 12757 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12758 12759 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12760 S.Diag(Loc, DiagID) << SR; 12761 } 12762 } Diagnoser(DiagID); 12763 12764 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12765 } 12766 12767 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12768 SourceRange SR) { 12769 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12770 } 12771 12772 ExprResult 12773 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12774 VerifyICEDiagnoser &Diagnoser, 12775 bool AllowFold) { 12776 SourceLocation DiagLoc = E->getLocStart(); 12777 12778 if (getLangOpts().CPlusPlus11) { 12779 // C++11 [expr.const]p5: 12780 // If an expression of literal class type is used in a context where an 12781 // integral constant expression is required, then that class type shall 12782 // have a single non-explicit conversion function to an integral or 12783 // unscoped enumeration type 12784 ExprResult Converted; 12785 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12786 public: 12787 CXX11ConvertDiagnoser(bool Silent) 12788 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12789 Silent, true) {} 12790 12791 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12792 QualType T) override { 12793 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12794 } 12795 12796 SemaDiagnosticBuilder diagnoseIncomplete( 12797 Sema &S, SourceLocation Loc, QualType T) override { 12798 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12799 } 12800 12801 SemaDiagnosticBuilder diagnoseExplicitConv( 12802 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12803 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12804 } 12805 12806 SemaDiagnosticBuilder noteExplicitConv( 12807 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12808 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12809 << ConvTy->isEnumeralType() << ConvTy; 12810 } 12811 12812 SemaDiagnosticBuilder diagnoseAmbiguous( 12813 Sema &S, SourceLocation Loc, QualType T) override { 12814 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12815 } 12816 12817 SemaDiagnosticBuilder noteAmbiguous( 12818 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12819 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12820 << ConvTy->isEnumeralType() << ConvTy; 12821 } 12822 12823 SemaDiagnosticBuilder diagnoseConversion( 12824 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12825 llvm_unreachable("conversion functions are permitted"); 12826 } 12827 } ConvertDiagnoser(Diagnoser.Suppress); 12828 12829 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12830 ConvertDiagnoser); 12831 if (Converted.isInvalid()) 12832 return Converted; 12833 E = Converted.get(); 12834 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12835 return ExprError(); 12836 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12837 // An ICE must be of integral or unscoped enumeration type. 12838 if (!Diagnoser.Suppress) 12839 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12840 return ExprError(); 12841 } 12842 12843 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12844 // in the non-ICE case. 12845 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12846 if (Result) 12847 *Result = E->EvaluateKnownConstInt(Context); 12848 return E; 12849 } 12850 12851 Expr::EvalResult EvalResult; 12852 SmallVector<PartialDiagnosticAt, 8> Notes; 12853 EvalResult.Diag = &Notes; 12854 12855 // Try to evaluate the expression, and produce diagnostics explaining why it's 12856 // not a constant expression as a side-effect. 12857 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12858 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12859 12860 // In C++11, we can rely on diagnostics being produced for any expression 12861 // which is not a constant expression. If no diagnostics were produced, then 12862 // this is a constant expression. 12863 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12864 if (Result) 12865 *Result = EvalResult.Val.getInt(); 12866 return E; 12867 } 12868 12869 // If our only note is the usual "invalid subexpression" note, just point 12870 // the caret at its location rather than producing an essentially 12871 // redundant note. 12872 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12873 diag::note_invalid_subexpr_in_const_expr) { 12874 DiagLoc = Notes[0].first; 12875 Notes.clear(); 12876 } 12877 12878 if (!Folded || !AllowFold) { 12879 if (!Diagnoser.Suppress) { 12880 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12881 for (const PartialDiagnosticAt &Note : Notes) 12882 Diag(Note.first, Note.second); 12883 } 12884 12885 return ExprError(); 12886 } 12887 12888 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12889 for (const PartialDiagnosticAt &Note : Notes) 12890 Diag(Note.first, Note.second); 12891 12892 if (Result) 12893 *Result = EvalResult.Val.getInt(); 12894 return E; 12895 } 12896 12897 namespace { 12898 // Handle the case where we conclude a expression which we speculatively 12899 // considered to be unevaluated is actually evaluated. 12900 class TransformToPE : public TreeTransform<TransformToPE> { 12901 typedef TreeTransform<TransformToPE> BaseTransform; 12902 12903 public: 12904 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12905 12906 // Make sure we redo semantic analysis 12907 bool AlwaysRebuild() { return true; } 12908 12909 // Make sure we handle LabelStmts correctly. 12910 // FIXME: This does the right thing, but maybe we need a more general 12911 // fix to TreeTransform? 12912 StmtResult TransformLabelStmt(LabelStmt *S) { 12913 S->getDecl()->setStmt(nullptr); 12914 return BaseTransform::TransformLabelStmt(S); 12915 } 12916 12917 // We need to special-case DeclRefExprs referring to FieldDecls which 12918 // are not part of a member pointer formation; normal TreeTransforming 12919 // doesn't catch this case because of the way we represent them in the AST. 12920 // FIXME: This is a bit ugly; is it really the best way to handle this 12921 // case? 12922 // 12923 // Error on DeclRefExprs referring to FieldDecls. 12924 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12925 if (isa<FieldDecl>(E->getDecl()) && 12926 !SemaRef.isUnevaluatedContext()) 12927 return SemaRef.Diag(E->getLocation(), 12928 diag::err_invalid_non_static_member_use) 12929 << E->getDecl() << E->getSourceRange(); 12930 12931 return BaseTransform::TransformDeclRefExpr(E); 12932 } 12933 12934 // Exception: filter out member pointer formation 12935 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12936 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12937 return E; 12938 12939 return BaseTransform::TransformUnaryOperator(E); 12940 } 12941 12942 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12943 // Lambdas never need to be transformed. 12944 return E; 12945 } 12946 }; 12947 } 12948 12949 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12950 assert(isUnevaluatedContext() && 12951 "Should only transform unevaluated expressions"); 12952 ExprEvalContexts.back().Context = 12953 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12954 if (isUnevaluatedContext()) 12955 return E; 12956 return TransformToPE(*this).TransformExpr(E); 12957 } 12958 12959 void 12960 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12961 Decl *LambdaContextDecl, 12962 bool IsDecltype) { 12963 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12964 LambdaContextDecl, IsDecltype); 12965 Cleanup.reset(); 12966 if (!MaybeODRUseExprs.empty()) 12967 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12968 } 12969 12970 void 12971 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12972 ReuseLambdaContextDecl_t, 12973 bool IsDecltype) { 12974 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12975 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12976 } 12977 12978 void Sema::PopExpressionEvaluationContext() { 12979 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12980 unsigned NumTypos = Rec.NumTypos; 12981 12982 if (!Rec.Lambdas.empty()) { 12983 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12984 unsigned D; 12985 if (Rec.isUnevaluated()) { 12986 // C++11 [expr.prim.lambda]p2: 12987 // A lambda-expression shall not appear in an unevaluated operand 12988 // (Clause 5). 12989 D = diag::err_lambda_unevaluated_operand; 12990 } else { 12991 // C++1y [expr.const]p2: 12992 // A conditional-expression e is a core constant expression unless the 12993 // evaluation of e, following the rules of the abstract machine, would 12994 // evaluate [...] a lambda-expression. 12995 D = diag::err_lambda_in_constant_expression; 12996 } 12997 for (const auto *L : Rec.Lambdas) 12998 Diag(L->getLocStart(), D); 12999 } else { 13000 // Mark the capture expressions odr-used. This was deferred 13001 // during lambda expression creation. 13002 for (auto *Lambda : Rec.Lambdas) { 13003 for (auto *C : Lambda->capture_inits()) 13004 MarkDeclarationsReferencedInExpr(C); 13005 } 13006 } 13007 } 13008 13009 // When are coming out of an unevaluated context, clear out any 13010 // temporaries that we may have created as part of the evaluation of 13011 // the expression in that context: they aren't relevant because they 13012 // will never be constructed. 13013 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13014 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13015 ExprCleanupObjects.end()); 13016 Cleanup = Rec.ParentCleanup; 13017 CleanupVarDeclMarking(); 13018 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13019 // Otherwise, merge the contexts together. 13020 } else { 13021 Cleanup.mergeFrom(Rec.ParentCleanup); 13022 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13023 Rec.SavedMaybeODRUseExprs.end()); 13024 } 13025 13026 // Pop the current expression evaluation context off the stack. 13027 ExprEvalContexts.pop_back(); 13028 13029 if (!ExprEvalContexts.empty()) 13030 ExprEvalContexts.back().NumTypos += NumTypos; 13031 else 13032 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13033 "last ExpressionEvaluationContextRecord"); 13034 } 13035 13036 void Sema::DiscardCleanupsInEvaluationContext() { 13037 ExprCleanupObjects.erase( 13038 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13039 ExprCleanupObjects.end()); 13040 Cleanup.reset(); 13041 MaybeODRUseExprs.clear(); 13042 } 13043 13044 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13045 if (!E->getType()->isVariablyModifiedType()) 13046 return E; 13047 return TransformToPotentiallyEvaluated(E); 13048 } 13049 13050 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 13051 // Do not mark anything as "used" within a dependent context; wait for 13052 // an instantiation. 13053 if (SemaRef.CurContext->isDependentContext()) 13054 return false; 13055 13056 switch (SemaRef.ExprEvalContexts.back().Context) { 13057 case Sema::Unevaluated: 13058 case Sema::UnevaluatedAbstract: 13059 // We are in an expression that is not potentially evaluated; do nothing. 13060 // (Depending on how you read the standard, we actually do need to do 13061 // something here for null pointer constants, but the standard's 13062 // definition of a null pointer constant is completely crazy.) 13063 return false; 13064 13065 case Sema::DiscardedStatement: 13066 // These are technically a potentially evaluated but they have the effect 13067 // of suppressing use marking. 13068 return false; 13069 13070 case Sema::ConstantEvaluated: 13071 case Sema::PotentiallyEvaluated: 13072 // We are in a potentially evaluated expression (or a constant-expression 13073 // in C++03); we need to do implicit template instantiation, implicitly 13074 // define class members, and mark most declarations as used. 13075 return true; 13076 13077 case Sema::PotentiallyEvaluatedIfUsed: 13078 // Referenced declarations will only be used if the construct in the 13079 // containing expression is used. 13080 return false; 13081 } 13082 llvm_unreachable("Invalid context"); 13083 } 13084 13085 /// \brief Mark a function referenced, and check whether it is odr-used 13086 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13087 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13088 bool MightBeOdrUse) { 13089 assert(Func && "No function?"); 13090 13091 Func->setReferenced(); 13092 13093 // C++11 [basic.def.odr]p3: 13094 // A function whose name appears as a potentially-evaluated expression is 13095 // odr-used if it is the unique lookup result or the selected member of a 13096 // set of overloaded functions [...]. 13097 // 13098 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13099 // can just check that here. 13100 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13101 13102 // Determine whether we require a function definition to exist, per 13103 // C++11 [temp.inst]p3: 13104 // Unless a function template specialization has been explicitly 13105 // instantiated or explicitly specialized, the function template 13106 // specialization is implicitly instantiated when the specialization is 13107 // referenced in a context that requires a function definition to exist. 13108 // 13109 // We consider constexpr function templates to be referenced in a context 13110 // that requires a definition to exist whenever they are referenced. 13111 // 13112 // FIXME: This instantiates constexpr functions too frequently. If this is 13113 // really an unevaluated context (and we're not just in the definition of a 13114 // function template or overload resolution or other cases which we 13115 // incorrectly consider to be unevaluated contexts), and we're not in a 13116 // subexpression which we actually need to evaluate (for instance, a 13117 // template argument, array bound or an expression in a braced-init-list), 13118 // we are not permitted to instantiate this constexpr function definition. 13119 // 13120 // FIXME: This also implicitly defines special members too frequently. They 13121 // are only supposed to be implicitly defined if they are odr-used, but they 13122 // are not odr-used from constant expressions in unevaluated contexts. 13123 // However, they cannot be referenced if they are deleted, and they are 13124 // deleted whenever the implicit definition of the special member would 13125 // fail (with very few exceptions). 13126 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13127 bool NeedDefinition = 13128 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13129 (MD && !MD->isUserProvided()))); 13130 13131 // C++14 [temp.expl.spec]p6: 13132 // If a template [...] is explicitly specialized then that specialization 13133 // shall be declared before the first use of that specialization that would 13134 // cause an implicit instantiation to take place, in every translation unit 13135 // in which such a use occurs 13136 if (NeedDefinition && 13137 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13138 Func->getMemberSpecializationInfo())) 13139 checkSpecializationVisibility(Loc, Func); 13140 13141 // If we don't need to mark the function as used, and we don't need to 13142 // try to provide a definition, there's nothing more to do. 13143 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13144 (!NeedDefinition || Func->getBody())) 13145 return; 13146 13147 // Note that this declaration has been used. 13148 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13149 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13150 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13151 if (Constructor->isDefaultConstructor()) { 13152 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13153 return; 13154 DefineImplicitDefaultConstructor(Loc, Constructor); 13155 } else if (Constructor->isCopyConstructor()) { 13156 DefineImplicitCopyConstructor(Loc, Constructor); 13157 } else if (Constructor->isMoveConstructor()) { 13158 DefineImplicitMoveConstructor(Loc, Constructor); 13159 } 13160 } else if (Constructor->getInheritedConstructor()) { 13161 DefineInheritingConstructor(Loc, Constructor); 13162 } 13163 } else if (CXXDestructorDecl *Destructor = 13164 dyn_cast<CXXDestructorDecl>(Func)) { 13165 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13166 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13167 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13168 return; 13169 DefineImplicitDestructor(Loc, Destructor); 13170 } 13171 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13172 MarkVTableUsed(Loc, Destructor->getParent()); 13173 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13174 if (MethodDecl->isOverloadedOperator() && 13175 MethodDecl->getOverloadedOperator() == OO_Equal) { 13176 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13177 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13178 if (MethodDecl->isCopyAssignmentOperator()) 13179 DefineImplicitCopyAssignment(Loc, MethodDecl); 13180 else if (MethodDecl->isMoveAssignmentOperator()) 13181 DefineImplicitMoveAssignment(Loc, MethodDecl); 13182 } 13183 } else if (isa<CXXConversionDecl>(MethodDecl) && 13184 MethodDecl->getParent()->isLambda()) { 13185 CXXConversionDecl *Conversion = 13186 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13187 if (Conversion->isLambdaToBlockPointerConversion()) 13188 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13189 else 13190 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13191 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13192 MarkVTableUsed(Loc, MethodDecl->getParent()); 13193 } 13194 13195 // Recursive functions should be marked when used from another function. 13196 // FIXME: Is this really right? 13197 if (CurContext == Func) return; 13198 13199 // Resolve the exception specification for any function which is 13200 // used: CodeGen will need it. 13201 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13202 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13203 ResolveExceptionSpec(Loc, FPT); 13204 13205 // Implicit instantiation of function templates and member functions of 13206 // class templates. 13207 if (Func->isImplicitlyInstantiable()) { 13208 bool AlreadyInstantiated = false; 13209 SourceLocation PointOfInstantiation = Loc; 13210 if (FunctionTemplateSpecializationInfo *SpecInfo 13211 = Func->getTemplateSpecializationInfo()) { 13212 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13213 SpecInfo->setPointOfInstantiation(Loc); 13214 else if (SpecInfo->getTemplateSpecializationKind() 13215 == TSK_ImplicitInstantiation) { 13216 AlreadyInstantiated = true; 13217 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13218 } 13219 } else if (MemberSpecializationInfo *MSInfo 13220 = Func->getMemberSpecializationInfo()) { 13221 if (MSInfo->getPointOfInstantiation().isInvalid()) 13222 MSInfo->setPointOfInstantiation(Loc); 13223 else if (MSInfo->getTemplateSpecializationKind() 13224 == TSK_ImplicitInstantiation) { 13225 AlreadyInstantiated = true; 13226 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13227 } 13228 } 13229 13230 if (!AlreadyInstantiated || Func->isConstexpr()) { 13231 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13232 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13233 ActiveTemplateInstantiations.size()) 13234 PendingLocalImplicitInstantiations.push_back( 13235 std::make_pair(Func, PointOfInstantiation)); 13236 else if (Func->isConstexpr()) 13237 // Do not defer instantiations of constexpr functions, to avoid the 13238 // expression evaluator needing to call back into Sema if it sees a 13239 // call to such a function. 13240 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13241 else { 13242 PendingInstantiations.push_back(std::make_pair(Func, 13243 PointOfInstantiation)); 13244 // Notify the consumer that a function was implicitly instantiated. 13245 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13246 } 13247 } 13248 } else { 13249 // Walk redefinitions, as some of them may be instantiable. 13250 for (auto i : Func->redecls()) { 13251 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13252 MarkFunctionReferenced(Loc, i, OdrUse); 13253 } 13254 } 13255 13256 if (!OdrUse) return; 13257 13258 // Keep track of used but undefined functions. 13259 if (!Func->isDefined()) { 13260 if (mightHaveNonExternalLinkage(Func)) 13261 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13262 else if (Func->getMostRecentDecl()->isInlined() && 13263 !LangOpts.GNUInline && 13264 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13265 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13266 } 13267 13268 Func->markUsed(Context); 13269 } 13270 13271 static void 13272 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13273 ValueDecl *var, DeclContext *DC) { 13274 DeclContext *VarDC = var->getDeclContext(); 13275 13276 // If the parameter still belongs to the translation unit, then 13277 // we're actually just using one parameter in the declaration of 13278 // the next. 13279 if (isa<ParmVarDecl>(var) && 13280 isa<TranslationUnitDecl>(VarDC)) 13281 return; 13282 13283 // For C code, don't diagnose about capture if we're not actually in code 13284 // right now; it's impossible to write a non-constant expression outside of 13285 // function context, so we'll get other (more useful) diagnostics later. 13286 // 13287 // For C++, things get a bit more nasty... it would be nice to suppress this 13288 // diagnostic for certain cases like using a local variable in an array bound 13289 // for a member of a local class, but the correct predicate is not obvious. 13290 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13291 return; 13292 13293 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13294 unsigned ContextKind = 3; // unknown 13295 if (isa<CXXMethodDecl>(VarDC) && 13296 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13297 ContextKind = 2; 13298 } else if (isa<FunctionDecl>(VarDC)) { 13299 ContextKind = 0; 13300 } else if (isa<BlockDecl>(VarDC)) { 13301 ContextKind = 1; 13302 } 13303 13304 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13305 << var << ValueKind << ContextKind << VarDC; 13306 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13307 << var; 13308 13309 // FIXME: Add additional diagnostic info about class etc. which prevents 13310 // capture. 13311 } 13312 13313 13314 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13315 bool &SubCapturesAreNested, 13316 QualType &CaptureType, 13317 QualType &DeclRefType) { 13318 // Check whether we've already captured it. 13319 if (CSI->CaptureMap.count(Var)) { 13320 // If we found a capture, any subcaptures are nested. 13321 SubCapturesAreNested = true; 13322 13323 // Retrieve the capture type for this variable. 13324 CaptureType = CSI->getCapture(Var).getCaptureType(); 13325 13326 // Compute the type of an expression that refers to this variable. 13327 DeclRefType = CaptureType.getNonReferenceType(); 13328 13329 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13330 // are mutable in the sense that user can change their value - they are 13331 // private instances of the captured declarations. 13332 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13333 if (Cap.isCopyCapture() && 13334 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13335 !(isa<CapturedRegionScopeInfo>(CSI) && 13336 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13337 DeclRefType.addConst(); 13338 return true; 13339 } 13340 return false; 13341 } 13342 13343 // Only block literals, captured statements, and lambda expressions can 13344 // capture; other scopes don't work. 13345 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13346 SourceLocation Loc, 13347 const bool Diagnose, Sema &S) { 13348 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13349 return getLambdaAwareParentOfDeclContext(DC); 13350 else if (Var->hasLocalStorage()) { 13351 if (Diagnose) 13352 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13353 } 13354 return nullptr; 13355 } 13356 13357 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13358 // certain types of variables (unnamed, variably modified types etc.) 13359 // so check for eligibility. 13360 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13361 SourceLocation Loc, 13362 const bool Diagnose, Sema &S) { 13363 13364 bool IsBlock = isa<BlockScopeInfo>(CSI); 13365 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13366 13367 // Lambdas are not allowed to capture unnamed variables 13368 // (e.g. anonymous unions). 13369 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13370 // assuming that's the intent. 13371 if (IsLambda && !Var->getDeclName()) { 13372 if (Diagnose) { 13373 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13374 S.Diag(Var->getLocation(), diag::note_declared_at); 13375 } 13376 return false; 13377 } 13378 13379 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13380 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13381 if (Diagnose) { 13382 S.Diag(Loc, diag::err_ref_vm_type); 13383 S.Diag(Var->getLocation(), diag::note_previous_decl) 13384 << Var->getDeclName(); 13385 } 13386 return false; 13387 } 13388 // Prohibit structs with flexible array members too. 13389 // We cannot capture what is in the tail end of the struct. 13390 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13391 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13392 if (Diagnose) { 13393 if (IsBlock) 13394 S.Diag(Loc, diag::err_ref_flexarray_type); 13395 else 13396 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13397 << Var->getDeclName(); 13398 S.Diag(Var->getLocation(), diag::note_previous_decl) 13399 << Var->getDeclName(); 13400 } 13401 return false; 13402 } 13403 } 13404 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13405 // Lambdas and captured statements are not allowed to capture __block 13406 // variables; they don't support the expected semantics. 13407 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13408 if (Diagnose) { 13409 S.Diag(Loc, diag::err_capture_block_variable) 13410 << Var->getDeclName() << !IsLambda; 13411 S.Diag(Var->getLocation(), diag::note_previous_decl) 13412 << Var->getDeclName(); 13413 } 13414 return false; 13415 } 13416 13417 return true; 13418 } 13419 13420 // Returns true if the capture by block was successful. 13421 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13422 SourceLocation Loc, 13423 const bool BuildAndDiagnose, 13424 QualType &CaptureType, 13425 QualType &DeclRefType, 13426 const bool Nested, 13427 Sema &S) { 13428 Expr *CopyExpr = nullptr; 13429 bool ByRef = false; 13430 13431 // Blocks are not allowed to capture arrays. 13432 if (CaptureType->isArrayType()) { 13433 if (BuildAndDiagnose) { 13434 S.Diag(Loc, diag::err_ref_array_type); 13435 S.Diag(Var->getLocation(), diag::note_previous_decl) 13436 << Var->getDeclName(); 13437 } 13438 return false; 13439 } 13440 13441 // Forbid the block-capture of autoreleasing variables. 13442 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13443 if (BuildAndDiagnose) { 13444 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13445 << /*block*/ 0; 13446 S.Diag(Var->getLocation(), diag::note_previous_decl) 13447 << Var->getDeclName(); 13448 } 13449 return false; 13450 } 13451 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13452 if (HasBlocksAttr || CaptureType->isReferenceType() || 13453 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13454 // Block capture by reference does not change the capture or 13455 // declaration reference types. 13456 ByRef = true; 13457 } else { 13458 // Block capture by copy introduces 'const'. 13459 CaptureType = CaptureType.getNonReferenceType().withConst(); 13460 DeclRefType = CaptureType; 13461 13462 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13463 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13464 // The capture logic needs the destructor, so make sure we mark it. 13465 // Usually this is unnecessary because most local variables have 13466 // their destructors marked at declaration time, but parameters are 13467 // an exception because it's technically only the call site that 13468 // actually requires the destructor. 13469 if (isa<ParmVarDecl>(Var)) 13470 S.FinalizeVarWithDestructor(Var, Record); 13471 13472 // Enter a new evaluation context to insulate the copy 13473 // full-expression. 13474 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13475 13476 // According to the blocks spec, the capture of a variable from 13477 // the stack requires a const copy constructor. This is not true 13478 // of the copy/move done to move a __block variable to the heap. 13479 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13480 DeclRefType.withConst(), 13481 VK_LValue, Loc); 13482 13483 ExprResult Result 13484 = S.PerformCopyInitialization( 13485 InitializedEntity::InitializeBlock(Var->getLocation(), 13486 CaptureType, false), 13487 Loc, DeclRef); 13488 13489 // Build a full-expression copy expression if initialization 13490 // succeeded and used a non-trivial constructor. Recover from 13491 // errors by pretending that the copy isn't necessary. 13492 if (!Result.isInvalid() && 13493 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13494 ->isTrivial()) { 13495 Result = S.MaybeCreateExprWithCleanups(Result); 13496 CopyExpr = Result.get(); 13497 } 13498 } 13499 } 13500 } 13501 13502 // Actually capture the variable. 13503 if (BuildAndDiagnose) 13504 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13505 SourceLocation(), CaptureType, CopyExpr); 13506 13507 return true; 13508 13509 } 13510 13511 13512 /// \brief Capture the given variable in the captured region. 13513 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13514 VarDecl *Var, 13515 SourceLocation Loc, 13516 const bool BuildAndDiagnose, 13517 QualType &CaptureType, 13518 QualType &DeclRefType, 13519 const bool RefersToCapturedVariable, 13520 Sema &S) { 13521 // By default, capture variables by reference. 13522 bool ByRef = true; 13523 // Using an LValue reference type is consistent with Lambdas (see below). 13524 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13525 if (S.IsOpenMPCapturedDecl(Var)) 13526 DeclRefType = DeclRefType.getUnqualifiedType(); 13527 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13528 } 13529 13530 if (ByRef) 13531 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13532 else 13533 CaptureType = DeclRefType; 13534 13535 Expr *CopyExpr = nullptr; 13536 if (BuildAndDiagnose) { 13537 // The current implementation assumes that all variables are captured 13538 // by references. Since there is no capture by copy, no expression 13539 // evaluation will be needed. 13540 RecordDecl *RD = RSI->TheRecordDecl; 13541 13542 FieldDecl *Field 13543 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13544 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13545 nullptr, false, ICIS_NoInit); 13546 Field->setImplicit(true); 13547 Field->setAccess(AS_private); 13548 RD->addDecl(Field); 13549 13550 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13551 DeclRefType, VK_LValue, Loc); 13552 Var->setReferenced(true); 13553 Var->markUsed(S.Context); 13554 } 13555 13556 // Actually capture the variable. 13557 if (BuildAndDiagnose) 13558 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13559 SourceLocation(), CaptureType, CopyExpr); 13560 13561 13562 return true; 13563 } 13564 13565 /// \brief Create a field within the lambda class for the variable 13566 /// being captured. 13567 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13568 QualType FieldType, QualType DeclRefType, 13569 SourceLocation Loc, 13570 bool RefersToCapturedVariable) { 13571 CXXRecordDecl *Lambda = LSI->Lambda; 13572 13573 // Build the non-static data member. 13574 FieldDecl *Field 13575 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13576 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13577 nullptr, false, ICIS_NoInit); 13578 Field->setImplicit(true); 13579 Field->setAccess(AS_private); 13580 Lambda->addDecl(Field); 13581 } 13582 13583 /// \brief Capture the given variable in the lambda. 13584 static bool captureInLambda(LambdaScopeInfo *LSI, 13585 VarDecl *Var, 13586 SourceLocation Loc, 13587 const bool BuildAndDiagnose, 13588 QualType &CaptureType, 13589 QualType &DeclRefType, 13590 const bool RefersToCapturedVariable, 13591 const Sema::TryCaptureKind Kind, 13592 SourceLocation EllipsisLoc, 13593 const bool IsTopScope, 13594 Sema &S) { 13595 13596 // Determine whether we are capturing by reference or by value. 13597 bool ByRef = false; 13598 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13599 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13600 } else { 13601 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13602 } 13603 13604 // Compute the type of the field that will capture this variable. 13605 if (ByRef) { 13606 // C++11 [expr.prim.lambda]p15: 13607 // An entity is captured by reference if it is implicitly or 13608 // explicitly captured but not captured by copy. It is 13609 // unspecified whether additional unnamed non-static data 13610 // members are declared in the closure type for entities 13611 // captured by reference. 13612 // 13613 // FIXME: It is not clear whether we want to build an lvalue reference 13614 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13615 // to do the former, while EDG does the latter. Core issue 1249 will 13616 // clarify, but for now we follow GCC because it's a more permissive and 13617 // easily defensible position. 13618 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13619 } else { 13620 // C++11 [expr.prim.lambda]p14: 13621 // For each entity captured by copy, an unnamed non-static 13622 // data member is declared in the closure type. The 13623 // declaration order of these members is unspecified. The type 13624 // of such a data member is the type of the corresponding 13625 // captured entity if the entity is not a reference to an 13626 // object, or the referenced type otherwise. [Note: If the 13627 // captured entity is a reference to a function, the 13628 // corresponding data member is also a reference to a 13629 // function. - end note ] 13630 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13631 if (!RefType->getPointeeType()->isFunctionType()) 13632 CaptureType = RefType->getPointeeType(); 13633 } 13634 13635 // Forbid the lambda copy-capture of autoreleasing variables. 13636 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13637 if (BuildAndDiagnose) { 13638 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13639 S.Diag(Var->getLocation(), diag::note_previous_decl) 13640 << Var->getDeclName(); 13641 } 13642 return false; 13643 } 13644 13645 // Make sure that by-copy captures are of a complete and non-abstract type. 13646 if (BuildAndDiagnose) { 13647 if (!CaptureType->isDependentType() && 13648 S.RequireCompleteType(Loc, CaptureType, 13649 diag::err_capture_of_incomplete_type, 13650 Var->getDeclName())) 13651 return false; 13652 13653 if (S.RequireNonAbstractType(Loc, CaptureType, 13654 diag::err_capture_of_abstract_type)) 13655 return false; 13656 } 13657 } 13658 13659 // Capture this variable in the lambda. 13660 if (BuildAndDiagnose) 13661 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13662 RefersToCapturedVariable); 13663 13664 // Compute the type of a reference to this captured variable. 13665 if (ByRef) 13666 DeclRefType = CaptureType.getNonReferenceType(); 13667 else { 13668 // C++ [expr.prim.lambda]p5: 13669 // The closure type for a lambda-expression has a public inline 13670 // function call operator [...]. This function call operator is 13671 // declared const (9.3.1) if and only if the lambda-expression's 13672 // parameter-declaration-clause is not followed by mutable. 13673 DeclRefType = CaptureType.getNonReferenceType(); 13674 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13675 DeclRefType.addConst(); 13676 } 13677 13678 // Add the capture. 13679 if (BuildAndDiagnose) 13680 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13681 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13682 13683 return true; 13684 } 13685 13686 bool Sema::tryCaptureVariable( 13687 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13688 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13689 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13690 // An init-capture is notionally from the context surrounding its 13691 // declaration, but its parent DC is the lambda class. 13692 DeclContext *VarDC = Var->getDeclContext(); 13693 if (Var->isInitCapture()) 13694 VarDC = VarDC->getParent(); 13695 13696 DeclContext *DC = CurContext; 13697 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13698 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13699 // We need to sync up the Declaration Context with the 13700 // FunctionScopeIndexToStopAt 13701 if (FunctionScopeIndexToStopAt) { 13702 unsigned FSIndex = FunctionScopes.size() - 1; 13703 while (FSIndex != MaxFunctionScopesIndex) { 13704 DC = getLambdaAwareParentOfDeclContext(DC); 13705 --FSIndex; 13706 } 13707 } 13708 13709 13710 // If the variable is declared in the current context, there is no need to 13711 // capture it. 13712 if (VarDC == DC) return true; 13713 13714 // Capture global variables if it is required to use private copy of this 13715 // variable. 13716 bool IsGlobal = !Var->hasLocalStorage(); 13717 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13718 return true; 13719 13720 // Walk up the stack to determine whether we can capture the variable, 13721 // performing the "simple" checks that don't depend on type. We stop when 13722 // we've either hit the declared scope of the variable or find an existing 13723 // capture of that variable. We start from the innermost capturing-entity 13724 // (the DC) and ensure that all intervening capturing-entities 13725 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13726 // declcontext can either capture the variable or have already captured 13727 // the variable. 13728 CaptureType = Var->getType(); 13729 DeclRefType = CaptureType.getNonReferenceType(); 13730 bool Nested = false; 13731 bool Explicit = (Kind != TryCapture_Implicit); 13732 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13733 do { 13734 // Only block literals, captured statements, and lambda expressions can 13735 // capture; other scopes don't work. 13736 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13737 ExprLoc, 13738 BuildAndDiagnose, 13739 *this); 13740 // We need to check for the parent *first* because, if we *have* 13741 // private-captured a global variable, we need to recursively capture it in 13742 // intermediate blocks, lambdas, etc. 13743 if (!ParentDC) { 13744 if (IsGlobal) { 13745 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13746 break; 13747 } 13748 return true; 13749 } 13750 13751 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13752 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13753 13754 13755 // Check whether we've already captured it. 13756 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13757 DeclRefType)) 13758 break; 13759 // If we are instantiating a generic lambda call operator body, 13760 // we do not want to capture new variables. What was captured 13761 // during either a lambdas transformation or initial parsing 13762 // should be used. 13763 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13764 if (BuildAndDiagnose) { 13765 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13766 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13767 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13768 Diag(Var->getLocation(), diag::note_previous_decl) 13769 << Var->getDeclName(); 13770 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13771 } else 13772 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13773 } 13774 return true; 13775 } 13776 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13777 // certain types of variables (unnamed, variably modified types etc.) 13778 // so check for eligibility. 13779 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13780 return true; 13781 13782 // Try to capture variable-length arrays types. 13783 if (Var->getType()->isVariablyModifiedType()) { 13784 // We're going to walk down into the type and look for VLA 13785 // expressions. 13786 QualType QTy = Var->getType(); 13787 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13788 QTy = PVD->getOriginalType(); 13789 captureVariablyModifiedType(Context, QTy, CSI); 13790 } 13791 13792 if (getLangOpts().OpenMP) { 13793 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13794 // OpenMP private variables should not be captured in outer scope, so 13795 // just break here. Similarly, global variables that are captured in a 13796 // target region should not be captured outside the scope of the region. 13797 if (RSI->CapRegionKind == CR_OpenMP) { 13798 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13799 // When we detect target captures we are looking from inside the 13800 // target region, therefore we need to propagate the capture from the 13801 // enclosing region. Therefore, the capture is not initially nested. 13802 if (IsTargetCap) 13803 FunctionScopesIndex--; 13804 13805 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13806 Nested = !IsTargetCap; 13807 DeclRefType = DeclRefType.getUnqualifiedType(); 13808 CaptureType = Context.getLValueReferenceType(DeclRefType); 13809 break; 13810 } 13811 } 13812 } 13813 } 13814 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13815 // No capture-default, and this is not an explicit capture 13816 // so cannot capture this variable. 13817 if (BuildAndDiagnose) { 13818 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13819 Diag(Var->getLocation(), diag::note_previous_decl) 13820 << Var->getDeclName(); 13821 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13822 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13823 diag::note_lambda_decl); 13824 // FIXME: If we error out because an outer lambda can not implicitly 13825 // capture a variable that an inner lambda explicitly captures, we 13826 // should have the inner lambda do the explicit capture - because 13827 // it makes for cleaner diagnostics later. This would purely be done 13828 // so that the diagnostic does not misleadingly claim that a variable 13829 // can not be captured by a lambda implicitly even though it is captured 13830 // explicitly. Suggestion: 13831 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13832 // at the function head 13833 // - cache the StartingDeclContext - this must be a lambda 13834 // - captureInLambda in the innermost lambda the variable. 13835 } 13836 return true; 13837 } 13838 13839 FunctionScopesIndex--; 13840 DC = ParentDC; 13841 Explicit = false; 13842 } while (!VarDC->Equals(DC)); 13843 13844 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13845 // computing the type of the capture at each step, checking type-specific 13846 // requirements, and adding captures if requested. 13847 // If the variable had already been captured previously, we start capturing 13848 // at the lambda nested within that one. 13849 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13850 ++I) { 13851 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13852 13853 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13854 if (!captureInBlock(BSI, Var, ExprLoc, 13855 BuildAndDiagnose, CaptureType, 13856 DeclRefType, Nested, *this)) 13857 return true; 13858 Nested = true; 13859 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13860 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13861 BuildAndDiagnose, CaptureType, 13862 DeclRefType, Nested, *this)) 13863 return true; 13864 Nested = true; 13865 } else { 13866 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13867 if (!captureInLambda(LSI, Var, ExprLoc, 13868 BuildAndDiagnose, CaptureType, 13869 DeclRefType, Nested, Kind, EllipsisLoc, 13870 /*IsTopScope*/I == N - 1, *this)) 13871 return true; 13872 Nested = true; 13873 } 13874 } 13875 return false; 13876 } 13877 13878 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13879 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13880 QualType CaptureType; 13881 QualType DeclRefType; 13882 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13883 /*BuildAndDiagnose=*/true, CaptureType, 13884 DeclRefType, nullptr); 13885 } 13886 13887 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13888 QualType CaptureType; 13889 QualType DeclRefType; 13890 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13891 /*BuildAndDiagnose=*/false, CaptureType, 13892 DeclRefType, nullptr); 13893 } 13894 13895 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13896 QualType CaptureType; 13897 QualType DeclRefType; 13898 13899 // Determine whether we can capture this variable. 13900 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13901 /*BuildAndDiagnose=*/false, CaptureType, 13902 DeclRefType, nullptr)) 13903 return QualType(); 13904 13905 return DeclRefType; 13906 } 13907 13908 13909 13910 // If either the type of the variable or the initializer is dependent, 13911 // return false. Otherwise, determine whether the variable is a constant 13912 // expression. Use this if you need to know if a variable that might or 13913 // might not be dependent is truly a constant expression. 13914 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13915 ASTContext &Context) { 13916 13917 if (Var->getType()->isDependentType()) 13918 return false; 13919 const VarDecl *DefVD = nullptr; 13920 Var->getAnyInitializer(DefVD); 13921 if (!DefVD) 13922 return false; 13923 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13924 Expr *Init = cast<Expr>(Eval->Value); 13925 if (Init->isValueDependent()) 13926 return false; 13927 return IsVariableAConstantExpression(Var, Context); 13928 } 13929 13930 13931 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13932 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13933 // an object that satisfies the requirements for appearing in a 13934 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13935 // is immediately applied." This function handles the lvalue-to-rvalue 13936 // conversion part. 13937 MaybeODRUseExprs.erase(E->IgnoreParens()); 13938 13939 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13940 // to a variable that is a constant expression, and if so, identify it as 13941 // a reference to a variable that does not involve an odr-use of that 13942 // variable. 13943 if (LambdaScopeInfo *LSI = getCurLambda()) { 13944 Expr *SansParensExpr = E->IgnoreParens(); 13945 VarDecl *Var = nullptr; 13946 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13947 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13948 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13949 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13950 13951 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13952 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13953 } 13954 } 13955 13956 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13957 Res = CorrectDelayedTyposInExpr(Res); 13958 13959 if (!Res.isUsable()) 13960 return Res; 13961 13962 // If a constant-expression is a reference to a variable where we delay 13963 // deciding whether it is an odr-use, just assume we will apply the 13964 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13965 // (a non-type template argument), we have special handling anyway. 13966 UpdateMarkingForLValueToRValue(Res.get()); 13967 return Res; 13968 } 13969 13970 void Sema::CleanupVarDeclMarking() { 13971 for (Expr *E : MaybeODRUseExprs) { 13972 VarDecl *Var; 13973 SourceLocation Loc; 13974 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13975 Var = cast<VarDecl>(DRE->getDecl()); 13976 Loc = DRE->getLocation(); 13977 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13978 Var = cast<VarDecl>(ME->getMemberDecl()); 13979 Loc = ME->getMemberLoc(); 13980 } else { 13981 llvm_unreachable("Unexpected expression"); 13982 } 13983 13984 MarkVarDeclODRUsed(Var, Loc, *this, 13985 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13986 } 13987 13988 MaybeODRUseExprs.clear(); 13989 } 13990 13991 13992 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13993 VarDecl *Var, Expr *E) { 13994 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13995 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13996 Var->setReferenced(); 13997 13998 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13999 bool MarkODRUsed = true; 14000 14001 // If the context is not potentially evaluated, this is not an odr-use and 14002 // does not trigger instantiation. 14003 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 14004 if (SemaRef.isUnevaluatedContext()) 14005 return; 14006 14007 // If we don't yet know whether this context is going to end up being an 14008 // evaluated context, and we're referencing a variable from an enclosing 14009 // scope, add a potential capture. 14010 // 14011 // FIXME: Is this necessary? These contexts are only used for default 14012 // arguments, where local variables can't be used. 14013 const bool RefersToEnclosingScope = 14014 (SemaRef.CurContext != Var->getDeclContext() && 14015 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14016 if (RefersToEnclosingScope) { 14017 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 14018 // If a variable could potentially be odr-used, defer marking it so 14019 // until we finish analyzing the full expression for any 14020 // lvalue-to-rvalue 14021 // or discarded value conversions that would obviate odr-use. 14022 // Add it to the list of potential captures that will be analyzed 14023 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14024 // unless the variable is a reference that was initialized by a constant 14025 // expression (this will never need to be captured or odr-used). 14026 assert(E && "Capture variable should be used in an expression."); 14027 if (!Var->getType()->isReferenceType() || 14028 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14029 LSI->addPotentialCapture(E->IgnoreParens()); 14030 } 14031 } 14032 14033 if (!isTemplateInstantiation(TSK)) 14034 return; 14035 14036 // Instantiate, but do not mark as odr-used, variable templates. 14037 MarkODRUsed = false; 14038 } 14039 14040 VarTemplateSpecializationDecl *VarSpec = 14041 dyn_cast<VarTemplateSpecializationDecl>(Var); 14042 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14043 "Can't instantiate a partial template specialization."); 14044 14045 // If this might be a member specialization of a static data member, check 14046 // the specialization is visible. We already did the checks for variable 14047 // template specializations when we created them. 14048 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 14049 SemaRef.checkSpecializationVisibility(Loc, Var); 14050 14051 // Perform implicit instantiation of static data members, static data member 14052 // templates of class templates, and variable template specializations. Delay 14053 // instantiations of variable templates, except for those that could be used 14054 // in a constant expression. 14055 if (isTemplateInstantiation(TSK)) { 14056 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14057 14058 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14059 if (Var->getPointOfInstantiation().isInvalid()) { 14060 // This is a modification of an existing AST node. Notify listeners. 14061 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14062 L->StaticDataMemberInstantiated(Var); 14063 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14064 // Don't bother trying to instantiate it again, unless we might need 14065 // its initializer before we get to the end of the TU. 14066 TryInstantiating = false; 14067 } 14068 14069 if (Var->getPointOfInstantiation().isInvalid()) 14070 Var->setTemplateSpecializationKind(TSK, Loc); 14071 14072 if (TryInstantiating) { 14073 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14074 bool InstantiationDependent = false; 14075 bool IsNonDependent = 14076 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14077 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14078 : true; 14079 14080 // Do not instantiate specializations that are still type-dependent. 14081 if (IsNonDependent) { 14082 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14083 // Do not defer instantiations of variables which could be used in a 14084 // constant expression. 14085 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14086 } else { 14087 SemaRef.PendingInstantiations 14088 .push_back(std::make_pair(Var, PointOfInstantiation)); 14089 } 14090 } 14091 } 14092 } 14093 14094 if (!MarkODRUsed) 14095 return; 14096 14097 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14098 // the requirements for appearing in a constant expression (5.19) and, if 14099 // it is an object, the lvalue-to-rvalue conversion (4.1) 14100 // is immediately applied." We check the first part here, and 14101 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14102 // Note that we use the C++11 definition everywhere because nothing in 14103 // C++03 depends on whether we get the C++03 version correct. The second 14104 // part does not apply to references, since they are not objects. 14105 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14106 // A reference initialized by a constant expression can never be 14107 // odr-used, so simply ignore it. 14108 if (!Var->getType()->isReferenceType()) 14109 SemaRef.MaybeODRUseExprs.insert(E); 14110 } else 14111 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14112 /*MaxFunctionScopeIndex ptr*/ nullptr); 14113 } 14114 14115 /// \brief Mark a variable referenced, and check whether it is odr-used 14116 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14117 /// used directly for normal expressions referring to VarDecl. 14118 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14119 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14120 } 14121 14122 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14123 Decl *D, Expr *E, bool MightBeOdrUse) { 14124 if (SemaRef.isInOpenMPDeclareTargetContext()) 14125 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14126 14127 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14128 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14129 return; 14130 } 14131 14132 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14133 14134 // If this is a call to a method via a cast, also mark the method in the 14135 // derived class used in case codegen can devirtualize the call. 14136 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14137 if (!ME) 14138 return; 14139 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14140 if (!MD) 14141 return; 14142 // Only attempt to devirtualize if this is truly a virtual call. 14143 bool IsVirtualCall = MD->isVirtual() && 14144 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14145 if (!IsVirtualCall) 14146 return; 14147 const Expr *Base = ME->getBase(); 14148 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14149 if (!MostDerivedClassDecl) 14150 return; 14151 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14152 if (!DM || DM->isPure()) 14153 return; 14154 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14155 } 14156 14157 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14158 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14159 // TODO: update this with DR# once a defect report is filed. 14160 // C++11 defect. The address of a pure member should not be an ODR use, even 14161 // if it's a qualified reference. 14162 bool OdrUse = true; 14163 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14164 if (Method->isVirtual()) 14165 OdrUse = false; 14166 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14167 } 14168 14169 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14170 void Sema::MarkMemberReferenced(MemberExpr *E) { 14171 // C++11 [basic.def.odr]p2: 14172 // A non-overloaded function whose name appears as a potentially-evaluated 14173 // expression or a member of a set of candidate functions, if selected by 14174 // overload resolution when referred to from a potentially-evaluated 14175 // expression, is odr-used, unless it is a pure virtual function and its 14176 // name is not explicitly qualified. 14177 bool MightBeOdrUse = true; 14178 if (E->performsVirtualDispatch(getLangOpts())) { 14179 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14180 if (Method->isPure()) 14181 MightBeOdrUse = false; 14182 } 14183 SourceLocation Loc = E->getMemberLoc().isValid() ? 14184 E->getMemberLoc() : E->getLocStart(); 14185 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14186 } 14187 14188 /// \brief Perform marking for a reference to an arbitrary declaration. It 14189 /// marks the declaration referenced, and performs odr-use checking for 14190 /// functions and variables. This method should not be used when building a 14191 /// normal expression which refers to a variable. 14192 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14193 bool MightBeOdrUse) { 14194 if (MightBeOdrUse) { 14195 if (auto *VD = dyn_cast<VarDecl>(D)) { 14196 MarkVariableReferenced(Loc, VD); 14197 return; 14198 } 14199 } 14200 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14201 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14202 return; 14203 } 14204 D->setReferenced(); 14205 } 14206 14207 namespace { 14208 // Mark all of the declarations referenced 14209 // FIXME: Not fully implemented yet! We need to have a better understanding 14210 // of when we're entering 14211 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14212 Sema &S; 14213 SourceLocation Loc; 14214 14215 public: 14216 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14217 14218 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14219 14220 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14221 bool TraverseRecordType(RecordType *T); 14222 }; 14223 } 14224 14225 bool MarkReferencedDecls::TraverseTemplateArgument( 14226 const TemplateArgument &Arg) { 14227 if (Arg.getKind() == TemplateArgument::Declaration) { 14228 if (Decl *D = Arg.getAsDecl()) 14229 S.MarkAnyDeclReferenced(Loc, D, true); 14230 } 14231 14232 return Inherited::TraverseTemplateArgument(Arg); 14233 } 14234 14235 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14236 if (ClassTemplateSpecializationDecl *Spec 14237 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14238 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14239 return TraverseTemplateArguments(Args.data(), Args.size()); 14240 } 14241 14242 return true; 14243 } 14244 14245 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14246 MarkReferencedDecls Marker(*this, Loc); 14247 Marker.TraverseType(Context.getCanonicalType(T)); 14248 } 14249 14250 namespace { 14251 /// \brief Helper class that marks all of the declarations referenced by 14252 /// potentially-evaluated subexpressions as "referenced". 14253 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14254 Sema &S; 14255 bool SkipLocalVariables; 14256 14257 public: 14258 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14259 14260 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14261 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14262 14263 void VisitDeclRefExpr(DeclRefExpr *E) { 14264 // If we were asked not to visit local variables, don't. 14265 if (SkipLocalVariables) { 14266 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14267 if (VD->hasLocalStorage()) 14268 return; 14269 } 14270 14271 S.MarkDeclRefReferenced(E); 14272 } 14273 14274 void VisitMemberExpr(MemberExpr *E) { 14275 S.MarkMemberReferenced(E); 14276 Inherited::VisitMemberExpr(E); 14277 } 14278 14279 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14280 S.MarkFunctionReferenced(E->getLocStart(), 14281 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14282 Visit(E->getSubExpr()); 14283 } 14284 14285 void VisitCXXNewExpr(CXXNewExpr *E) { 14286 if (E->getOperatorNew()) 14287 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14288 if (E->getOperatorDelete()) 14289 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14290 Inherited::VisitCXXNewExpr(E); 14291 } 14292 14293 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14294 if (E->getOperatorDelete()) 14295 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14296 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14297 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14298 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14299 S.MarkFunctionReferenced(E->getLocStart(), 14300 S.LookupDestructor(Record)); 14301 } 14302 14303 Inherited::VisitCXXDeleteExpr(E); 14304 } 14305 14306 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14307 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14308 Inherited::VisitCXXConstructExpr(E); 14309 } 14310 14311 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14312 Visit(E->getExpr()); 14313 } 14314 14315 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14316 Inherited::VisitImplicitCastExpr(E); 14317 14318 if (E->getCastKind() == CK_LValueToRValue) 14319 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14320 } 14321 }; 14322 } 14323 14324 /// \brief Mark any declarations that appear within this expression or any 14325 /// potentially-evaluated subexpressions as "referenced". 14326 /// 14327 /// \param SkipLocalVariables If true, don't mark local variables as 14328 /// 'referenced'. 14329 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14330 bool SkipLocalVariables) { 14331 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14332 } 14333 14334 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14335 /// of the program being compiled. 14336 /// 14337 /// This routine emits the given diagnostic when the code currently being 14338 /// type-checked is "potentially evaluated", meaning that there is a 14339 /// possibility that the code will actually be executable. Code in sizeof() 14340 /// expressions, code used only during overload resolution, etc., are not 14341 /// potentially evaluated. This routine will suppress such diagnostics or, 14342 /// in the absolutely nutty case of potentially potentially evaluated 14343 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14344 /// later. 14345 /// 14346 /// This routine should be used for all diagnostics that describe the run-time 14347 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14348 /// Failure to do so will likely result in spurious diagnostics or failures 14349 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14350 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14351 const PartialDiagnostic &PD) { 14352 switch (ExprEvalContexts.back().Context) { 14353 case Unevaluated: 14354 case UnevaluatedAbstract: 14355 case DiscardedStatement: 14356 // The argument will never be evaluated, so don't complain. 14357 break; 14358 14359 case ConstantEvaluated: 14360 // Relevant diagnostics should be produced by constant evaluation. 14361 break; 14362 14363 case PotentiallyEvaluated: 14364 case PotentiallyEvaluatedIfUsed: 14365 if (Statement && getCurFunctionOrMethodDecl()) { 14366 FunctionScopes.back()->PossiblyUnreachableDiags. 14367 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14368 } 14369 else 14370 Diag(Loc, PD); 14371 14372 return true; 14373 } 14374 14375 return false; 14376 } 14377 14378 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14379 CallExpr *CE, FunctionDecl *FD) { 14380 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14381 return false; 14382 14383 // If we're inside a decltype's expression, don't check for a valid return 14384 // type or construct temporaries until we know whether this is the last call. 14385 if (ExprEvalContexts.back().IsDecltype) { 14386 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14387 return false; 14388 } 14389 14390 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14391 FunctionDecl *FD; 14392 CallExpr *CE; 14393 14394 public: 14395 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14396 : FD(FD), CE(CE) { } 14397 14398 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14399 if (!FD) { 14400 S.Diag(Loc, diag::err_call_incomplete_return) 14401 << T << CE->getSourceRange(); 14402 return; 14403 } 14404 14405 S.Diag(Loc, diag::err_call_function_incomplete_return) 14406 << CE->getSourceRange() << FD->getDeclName() << T; 14407 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14408 << FD->getDeclName(); 14409 } 14410 } Diagnoser(FD, CE); 14411 14412 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14413 return true; 14414 14415 return false; 14416 } 14417 14418 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14419 // will prevent this condition from triggering, which is what we want. 14420 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14421 SourceLocation Loc; 14422 14423 unsigned diagnostic = diag::warn_condition_is_assignment; 14424 bool IsOrAssign = false; 14425 14426 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14427 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14428 return; 14429 14430 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14431 14432 // Greylist some idioms by putting them into a warning subcategory. 14433 if (ObjCMessageExpr *ME 14434 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14435 Selector Sel = ME->getSelector(); 14436 14437 // self = [<foo> init...] 14438 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14439 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14440 14441 // <foo> = [<bar> nextObject] 14442 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14443 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14444 } 14445 14446 Loc = Op->getOperatorLoc(); 14447 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14448 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14449 return; 14450 14451 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14452 Loc = Op->getOperatorLoc(); 14453 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14454 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14455 else { 14456 // Not an assignment. 14457 return; 14458 } 14459 14460 Diag(Loc, diagnostic) << E->getSourceRange(); 14461 14462 SourceLocation Open = E->getLocStart(); 14463 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14464 Diag(Loc, diag::note_condition_assign_silence) 14465 << FixItHint::CreateInsertion(Open, "(") 14466 << FixItHint::CreateInsertion(Close, ")"); 14467 14468 if (IsOrAssign) 14469 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14470 << FixItHint::CreateReplacement(Loc, "!="); 14471 else 14472 Diag(Loc, diag::note_condition_assign_to_comparison) 14473 << FixItHint::CreateReplacement(Loc, "=="); 14474 } 14475 14476 /// \brief Redundant parentheses over an equality comparison can indicate 14477 /// that the user intended an assignment used as condition. 14478 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14479 // Don't warn if the parens came from a macro. 14480 SourceLocation parenLoc = ParenE->getLocStart(); 14481 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14482 return; 14483 // Don't warn for dependent expressions. 14484 if (ParenE->isTypeDependent()) 14485 return; 14486 14487 Expr *E = ParenE->IgnoreParens(); 14488 14489 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14490 if (opE->getOpcode() == BO_EQ && 14491 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14492 == Expr::MLV_Valid) { 14493 SourceLocation Loc = opE->getOperatorLoc(); 14494 14495 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14496 SourceRange ParenERange = ParenE->getSourceRange(); 14497 Diag(Loc, diag::note_equality_comparison_silence) 14498 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14499 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14500 Diag(Loc, diag::note_equality_comparison_to_assign) 14501 << FixItHint::CreateReplacement(Loc, "="); 14502 } 14503 } 14504 14505 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14506 bool IsConstexpr) { 14507 DiagnoseAssignmentAsCondition(E); 14508 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14509 DiagnoseEqualityWithExtraParens(parenE); 14510 14511 ExprResult result = CheckPlaceholderExpr(E); 14512 if (result.isInvalid()) return ExprError(); 14513 E = result.get(); 14514 14515 if (!E->isTypeDependent()) { 14516 if (getLangOpts().CPlusPlus) 14517 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14518 14519 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14520 if (ERes.isInvalid()) 14521 return ExprError(); 14522 E = ERes.get(); 14523 14524 QualType T = E->getType(); 14525 if (!T->isScalarType()) { // C99 6.8.4.1p1 14526 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14527 << T << E->getSourceRange(); 14528 return ExprError(); 14529 } 14530 CheckBoolLikeConversion(E, Loc); 14531 } 14532 14533 return E; 14534 } 14535 14536 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14537 Expr *SubExpr, ConditionKind CK) { 14538 // Empty conditions are valid in for-statements. 14539 if (!SubExpr) 14540 return ConditionResult(); 14541 14542 ExprResult Cond; 14543 switch (CK) { 14544 case ConditionKind::Boolean: 14545 Cond = CheckBooleanCondition(Loc, SubExpr); 14546 break; 14547 14548 case ConditionKind::ConstexprIf: 14549 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14550 break; 14551 14552 case ConditionKind::Switch: 14553 Cond = CheckSwitchCondition(Loc, SubExpr); 14554 break; 14555 } 14556 if (Cond.isInvalid()) 14557 return ConditionError(); 14558 14559 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14560 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14561 if (!FullExpr.get()) 14562 return ConditionError(); 14563 14564 return ConditionResult(*this, nullptr, FullExpr, 14565 CK == ConditionKind::ConstexprIf); 14566 } 14567 14568 namespace { 14569 /// A visitor for rebuilding a call to an __unknown_any expression 14570 /// to have an appropriate type. 14571 struct RebuildUnknownAnyFunction 14572 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14573 14574 Sema &S; 14575 14576 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14577 14578 ExprResult VisitStmt(Stmt *S) { 14579 llvm_unreachable("unexpected statement!"); 14580 } 14581 14582 ExprResult VisitExpr(Expr *E) { 14583 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14584 << E->getSourceRange(); 14585 return ExprError(); 14586 } 14587 14588 /// Rebuild an expression which simply semantically wraps another 14589 /// expression which it shares the type and value kind of. 14590 template <class T> ExprResult rebuildSugarExpr(T *E) { 14591 ExprResult SubResult = Visit(E->getSubExpr()); 14592 if (SubResult.isInvalid()) return ExprError(); 14593 14594 Expr *SubExpr = SubResult.get(); 14595 E->setSubExpr(SubExpr); 14596 E->setType(SubExpr->getType()); 14597 E->setValueKind(SubExpr->getValueKind()); 14598 assert(E->getObjectKind() == OK_Ordinary); 14599 return E; 14600 } 14601 14602 ExprResult VisitParenExpr(ParenExpr *E) { 14603 return rebuildSugarExpr(E); 14604 } 14605 14606 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14607 return rebuildSugarExpr(E); 14608 } 14609 14610 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14611 ExprResult SubResult = Visit(E->getSubExpr()); 14612 if (SubResult.isInvalid()) return ExprError(); 14613 14614 Expr *SubExpr = SubResult.get(); 14615 E->setSubExpr(SubExpr); 14616 E->setType(S.Context.getPointerType(SubExpr->getType())); 14617 assert(E->getValueKind() == VK_RValue); 14618 assert(E->getObjectKind() == OK_Ordinary); 14619 return E; 14620 } 14621 14622 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14623 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14624 14625 E->setType(VD->getType()); 14626 14627 assert(E->getValueKind() == VK_RValue); 14628 if (S.getLangOpts().CPlusPlus && 14629 !(isa<CXXMethodDecl>(VD) && 14630 cast<CXXMethodDecl>(VD)->isInstance())) 14631 E->setValueKind(VK_LValue); 14632 14633 return E; 14634 } 14635 14636 ExprResult VisitMemberExpr(MemberExpr *E) { 14637 return resolveDecl(E, E->getMemberDecl()); 14638 } 14639 14640 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14641 return resolveDecl(E, E->getDecl()); 14642 } 14643 }; 14644 } 14645 14646 /// Given a function expression of unknown-any type, try to rebuild it 14647 /// to have a function type. 14648 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14649 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14650 if (Result.isInvalid()) return ExprError(); 14651 return S.DefaultFunctionArrayConversion(Result.get()); 14652 } 14653 14654 namespace { 14655 /// A visitor for rebuilding an expression of type __unknown_anytype 14656 /// into one which resolves the type directly on the referring 14657 /// expression. Strict preservation of the original source 14658 /// structure is not a goal. 14659 struct RebuildUnknownAnyExpr 14660 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14661 14662 Sema &S; 14663 14664 /// The current destination type. 14665 QualType DestType; 14666 14667 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14668 : S(S), DestType(CastType) {} 14669 14670 ExprResult VisitStmt(Stmt *S) { 14671 llvm_unreachable("unexpected statement!"); 14672 } 14673 14674 ExprResult VisitExpr(Expr *E) { 14675 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14676 << E->getSourceRange(); 14677 return ExprError(); 14678 } 14679 14680 ExprResult VisitCallExpr(CallExpr *E); 14681 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14682 14683 /// Rebuild an expression which simply semantically wraps another 14684 /// expression which it shares the type and value kind of. 14685 template <class T> ExprResult rebuildSugarExpr(T *E) { 14686 ExprResult SubResult = Visit(E->getSubExpr()); 14687 if (SubResult.isInvalid()) return ExprError(); 14688 Expr *SubExpr = SubResult.get(); 14689 E->setSubExpr(SubExpr); 14690 E->setType(SubExpr->getType()); 14691 E->setValueKind(SubExpr->getValueKind()); 14692 assert(E->getObjectKind() == OK_Ordinary); 14693 return E; 14694 } 14695 14696 ExprResult VisitParenExpr(ParenExpr *E) { 14697 return rebuildSugarExpr(E); 14698 } 14699 14700 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14701 return rebuildSugarExpr(E); 14702 } 14703 14704 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14705 const PointerType *Ptr = DestType->getAs<PointerType>(); 14706 if (!Ptr) { 14707 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14708 << E->getSourceRange(); 14709 return ExprError(); 14710 } 14711 assert(E->getValueKind() == VK_RValue); 14712 assert(E->getObjectKind() == OK_Ordinary); 14713 E->setType(DestType); 14714 14715 // Build the sub-expression as if it were an object of the pointee type. 14716 DestType = Ptr->getPointeeType(); 14717 ExprResult SubResult = Visit(E->getSubExpr()); 14718 if (SubResult.isInvalid()) return ExprError(); 14719 E->setSubExpr(SubResult.get()); 14720 return E; 14721 } 14722 14723 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14724 14725 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14726 14727 ExprResult VisitMemberExpr(MemberExpr *E) { 14728 return resolveDecl(E, E->getMemberDecl()); 14729 } 14730 14731 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14732 return resolveDecl(E, E->getDecl()); 14733 } 14734 }; 14735 } 14736 14737 /// Rebuilds a call expression which yielded __unknown_anytype. 14738 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14739 Expr *CalleeExpr = E->getCallee(); 14740 14741 enum FnKind { 14742 FK_MemberFunction, 14743 FK_FunctionPointer, 14744 FK_BlockPointer 14745 }; 14746 14747 FnKind Kind; 14748 QualType CalleeType = CalleeExpr->getType(); 14749 if (CalleeType == S.Context.BoundMemberTy) { 14750 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14751 Kind = FK_MemberFunction; 14752 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14753 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14754 CalleeType = Ptr->getPointeeType(); 14755 Kind = FK_FunctionPointer; 14756 } else { 14757 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14758 Kind = FK_BlockPointer; 14759 } 14760 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14761 14762 // Verify that this is a legal result type of a function. 14763 if (DestType->isArrayType() || DestType->isFunctionType()) { 14764 unsigned diagID = diag::err_func_returning_array_function; 14765 if (Kind == FK_BlockPointer) 14766 diagID = diag::err_block_returning_array_function; 14767 14768 S.Diag(E->getExprLoc(), diagID) 14769 << DestType->isFunctionType() << DestType; 14770 return ExprError(); 14771 } 14772 14773 // Otherwise, go ahead and set DestType as the call's result. 14774 E->setType(DestType.getNonLValueExprType(S.Context)); 14775 E->setValueKind(Expr::getValueKindForType(DestType)); 14776 assert(E->getObjectKind() == OK_Ordinary); 14777 14778 // Rebuild the function type, replacing the result type with DestType. 14779 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14780 if (Proto) { 14781 // __unknown_anytype(...) is a special case used by the debugger when 14782 // it has no idea what a function's signature is. 14783 // 14784 // We want to build this call essentially under the K&R 14785 // unprototyped rules, but making a FunctionNoProtoType in C++ 14786 // would foul up all sorts of assumptions. However, we cannot 14787 // simply pass all arguments as variadic arguments, nor can we 14788 // portably just call the function under a non-variadic type; see 14789 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14790 // However, it turns out that in practice it is generally safe to 14791 // call a function declared as "A foo(B,C,D);" under the prototype 14792 // "A foo(B,C,D,...);". The only known exception is with the 14793 // Windows ABI, where any variadic function is implicitly cdecl 14794 // regardless of its normal CC. Therefore we change the parameter 14795 // types to match the types of the arguments. 14796 // 14797 // This is a hack, but it is far superior to moving the 14798 // corresponding target-specific code from IR-gen to Sema/AST. 14799 14800 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14801 SmallVector<QualType, 8> ArgTypes; 14802 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14803 ArgTypes.reserve(E->getNumArgs()); 14804 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14805 Expr *Arg = E->getArg(i); 14806 QualType ArgType = Arg->getType(); 14807 if (E->isLValue()) { 14808 ArgType = S.Context.getLValueReferenceType(ArgType); 14809 } else if (E->isXValue()) { 14810 ArgType = S.Context.getRValueReferenceType(ArgType); 14811 } 14812 ArgTypes.push_back(ArgType); 14813 } 14814 ParamTypes = ArgTypes; 14815 } 14816 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14817 Proto->getExtProtoInfo()); 14818 } else { 14819 DestType = S.Context.getFunctionNoProtoType(DestType, 14820 FnType->getExtInfo()); 14821 } 14822 14823 // Rebuild the appropriate pointer-to-function type. 14824 switch (Kind) { 14825 case FK_MemberFunction: 14826 // Nothing to do. 14827 break; 14828 14829 case FK_FunctionPointer: 14830 DestType = S.Context.getPointerType(DestType); 14831 break; 14832 14833 case FK_BlockPointer: 14834 DestType = S.Context.getBlockPointerType(DestType); 14835 break; 14836 } 14837 14838 // Finally, we can recurse. 14839 ExprResult CalleeResult = Visit(CalleeExpr); 14840 if (!CalleeResult.isUsable()) return ExprError(); 14841 E->setCallee(CalleeResult.get()); 14842 14843 // Bind a temporary if necessary. 14844 return S.MaybeBindToTemporary(E); 14845 } 14846 14847 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14848 // Verify that this is a legal result type of a call. 14849 if (DestType->isArrayType() || DestType->isFunctionType()) { 14850 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14851 << DestType->isFunctionType() << DestType; 14852 return ExprError(); 14853 } 14854 14855 // Rewrite the method result type if available. 14856 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14857 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14858 Method->setReturnType(DestType); 14859 } 14860 14861 // Change the type of the message. 14862 E->setType(DestType.getNonReferenceType()); 14863 E->setValueKind(Expr::getValueKindForType(DestType)); 14864 14865 return S.MaybeBindToTemporary(E); 14866 } 14867 14868 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14869 // The only case we should ever see here is a function-to-pointer decay. 14870 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14871 assert(E->getValueKind() == VK_RValue); 14872 assert(E->getObjectKind() == OK_Ordinary); 14873 14874 E->setType(DestType); 14875 14876 // Rebuild the sub-expression as the pointee (function) type. 14877 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14878 14879 ExprResult Result = Visit(E->getSubExpr()); 14880 if (!Result.isUsable()) return ExprError(); 14881 14882 E->setSubExpr(Result.get()); 14883 return E; 14884 } else if (E->getCastKind() == CK_LValueToRValue) { 14885 assert(E->getValueKind() == VK_RValue); 14886 assert(E->getObjectKind() == OK_Ordinary); 14887 14888 assert(isa<BlockPointerType>(E->getType())); 14889 14890 E->setType(DestType); 14891 14892 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14893 DestType = S.Context.getLValueReferenceType(DestType); 14894 14895 ExprResult Result = Visit(E->getSubExpr()); 14896 if (!Result.isUsable()) return ExprError(); 14897 14898 E->setSubExpr(Result.get()); 14899 return E; 14900 } else { 14901 llvm_unreachable("Unhandled cast type!"); 14902 } 14903 } 14904 14905 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14906 ExprValueKind ValueKind = VK_LValue; 14907 QualType Type = DestType; 14908 14909 // We know how to make this work for certain kinds of decls: 14910 14911 // - functions 14912 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14913 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14914 DestType = Ptr->getPointeeType(); 14915 ExprResult Result = resolveDecl(E, VD); 14916 if (Result.isInvalid()) return ExprError(); 14917 return S.ImpCastExprToType(Result.get(), Type, 14918 CK_FunctionToPointerDecay, VK_RValue); 14919 } 14920 14921 if (!Type->isFunctionType()) { 14922 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14923 << VD << E->getSourceRange(); 14924 return ExprError(); 14925 } 14926 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14927 // We must match the FunctionDecl's type to the hack introduced in 14928 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14929 // type. See the lengthy commentary in that routine. 14930 QualType FDT = FD->getType(); 14931 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14932 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14933 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14934 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14935 SourceLocation Loc = FD->getLocation(); 14936 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14937 FD->getDeclContext(), 14938 Loc, Loc, FD->getNameInfo().getName(), 14939 DestType, FD->getTypeSourceInfo(), 14940 SC_None, false/*isInlineSpecified*/, 14941 FD->hasPrototype(), 14942 false/*isConstexprSpecified*/); 14943 14944 if (FD->getQualifier()) 14945 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14946 14947 SmallVector<ParmVarDecl*, 16> Params; 14948 for (const auto &AI : FT->param_types()) { 14949 ParmVarDecl *Param = 14950 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14951 Param->setScopeInfo(0, Params.size()); 14952 Params.push_back(Param); 14953 } 14954 NewFD->setParams(Params); 14955 DRE->setDecl(NewFD); 14956 VD = DRE->getDecl(); 14957 } 14958 } 14959 14960 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14961 if (MD->isInstance()) { 14962 ValueKind = VK_RValue; 14963 Type = S.Context.BoundMemberTy; 14964 } 14965 14966 // Function references aren't l-values in C. 14967 if (!S.getLangOpts().CPlusPlus) 14968 ValueKind = VK_RValue; 14969 14970 // - variables 14971 } else if (isa<VarDecl>(VD)) { 14972 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14973 Type = RefTy->getPointeeType(); 14974 } else if (Type->isFunctionType()) { 14975 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14976 << VD << E->getSourceRange(); 14977 return ExprError(); 14978 } 14979 14980 // - nothing else 14981 } else { 14982 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14983 << VD << E->getSourceRange(); 14984 return ExprError(); 14985 } 14986 14987 // Modifying the declaration like this is friendly to IR-gen but 14988 // also really dangerous. 14989 VD->setType(DestType); 14990 E->setType(Type); 14991 E->setValueKind(ValueKind); 14992 return E; 14993 } 14994 14995 /// Check a cast of an unknown-any type. We intentionally only 14996 /// trigger this for C-style casts. 14997 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14998 Expr *CastExpr, CastKind &CastKind, 14999 ExprValueKind &VK, CXXCastPath &Path) { 15000 // The type we're casting to must be either void or complete. 15001 if (!CastType->isVoidType() && 15002 RequireCompleteType(TypeRange.getBegin(), CastType, 15003 diag::err_typecheck_cast_to_incomplete)) 15004 return ExprError(); 15005 15006 // Rewrite the casted expression from scratch. 15007 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15008 if (!result.isUsable()) return ExprError(); 15009 15010 CastExpr = result.get(); 15011 VK = CastExpr->getValueKind(); 15012 CastKind = CK_NoOp; 15013 15014 return CastExpr; 15015 } 15016 15017 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15018 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15019 } 15020 15021 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15022 Expr *arg, QualType ¶mType) { 15023 // If the syntactic form of the argument is not an explicit cast of 15024 // any sort, just do default argument promotion. 15025 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15026 if (!castArg) { 15027 ExprResult result = DefaultArgumentPromotion(arg); 15028 if (result.isInvalid()) return ExprError(); 15029 paramType = result.get()->getType(); 15030 return result; 15031 } 15032 15033 // Otherwise, use the type that was written in the explicit cast. 15034 assert(!arg->hasPlaceholderType()); 15035 paramType = castArg->getTypeAsWritten(); 15036 15037 // Copy-initialize a parameter of that type. 15038 InitializedEntity entity = 15039 InitializedEntity::InitializeParameter(Context, paramType, 15040 /*consumed*/ false); 15041 return PerformCopyInitialization(entity, callLoc, arg); 15042 } 15043 15044 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15045 Expr *orig = E; 15046 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15047 while (true) { 15048 E = E->IgnoreParenImpCasts(); 15049 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15050 E = call->getCallee(); 15051 diagID = diag::err_uncasted_call_of_unknown_any; 15052 } else { 15053 break; 15054 } 15055 } 15056 15057 SourceLocation loc; 15058 NamedDecl *d; 15059 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15060 loc = ref->getLocation(); 15061 d = ref->getDecl(); 15062 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15063 loc = mem->getMemberLoc(); 15064 d = mem->getMemberDecl(); 15065 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15066 diagID = diag::err_uncasted_call_of_unknown_any; 15067 loc = msg->getSelectorStartLoc(); 15068 d = msg->getMethodDecl(); 15069 if (!d) { 15070 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15071 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15072 << orig->getSourceRange(); 15073 return ExprError(); 15074 } 15075 } else { 15076 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15077 << E->getSourceRange(); 15078 return ExprError(); 15079 } 15080 15081 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15082 15083 // Never recoverable. 15084 return ExprError(); 15085 } 15086 15087 /// Check for operands with placeholder types and complain if found. 15088 /// Returns true if there was an error and no recovery was possible. 15089 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15090 if (!getLangOpts().CPlusPlus) { 15091 // C cannot handle TypoExpr nodes on either side of a binop because it 15092 // doesn't handle dependent types properly, so make sure any TypoExprs have 15093 // been dealt with before checking the operands. 15094 ExprResult Result = CorrectDelayedTyposInExpr(E); 15095 if (!Result.isUsable()) return ExprError(); 15096 E = Result.get(); 15097 } 15098 15099 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15100 if (!placeholderType) return E; 15101 15102 switch (placeholderType->getKind()) { 15103 15104 // Overloaded expressions. 15105 case BuiltinType::Overload: { 15106 // Try to resolve a single function template specialization. 15107 // This is obligatory. 15108 ExprResult Result = E; 15109 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15110 return Result; 15111 15112 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15113 // leaves Result unchanged on failure. 15114 Result = E; 15115 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15116 return Result; 15117 15118 // If that failed, try to recover with a call. 15119 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15120 /*complain*/ true); 15121 return Result; 15122 } 15123 15124 // Bound member functions. 15125 case BuiltinType::BoundMember: { 15126 ExprResult result = E; 15127 const Expr *BME = E->IgnoreParens(); 15128 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15129 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15130 if (isa<CXXPseudoDestructorExpr>(BME)) { 15131 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15132 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15133 if (ME->getMemberNameInfo().getName().getNameKind() == 15134 DeclarationName::CXXDestructorName) 15135 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15136 } 15137 tryToRecoverWithCall(result, PD, 15138 /*complain*/ true); 15139 return result; 15140 } 15141 15142 // ARC unbridged casts. 15143 case BuiltinType::ARCUnbridgedCast: { 15144 Expr *realCast = stripARCUnbridgedCast(E); 15145 diagnoseARCUnbridgedCast(realCast); 15146 return realCast; 15147 } 15148 15149 // Expressions of unknown type. 15150 case BuiltinType::UnknownAny: 15151 return diagnoseUnknownAnyExpr(*this, E); 15152 15153 // Pseudo-objects. 15154 case BuiltinType::PseudoObject: 15155 return checkPseudoObjectRValue(E); 15156 15157 case BuiltinType::BuiltinFn: { 15158 // Accept __noop without parens by implicitly converting it to a call expr. 15159 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15160 if (DRE) { 15161 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15162 if (FD->getBuiltinID() == Builtin::BI__noop) { 15163 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15164 CK_BuiltinFnToFnPtr).get(); 15165 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15166 VK_RValue, SourceLocation()); 15167 } 15168 } 15169 15170 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15171 return ExprError(); 15172 } 15173 15174 // Expressions of unknown type. 15175 case BuiltinType::OMPArraySection: 15176 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15177 return ExprError(); 15178 15179 // Everything else should be impossible. 15180 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15181 case BuiltinType::Id: 15182 #include "clang/Basic/OpenCLImageTypes.def" 15183 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15184 #define PLACEHOLDER_TYPE(Id, SingletonId) 15185 #include "clang/AST/BuiltinTypes.def" 15186 break; 15187 } 15188 15189 llvm_unreachable("invalid placeholder type!"); 15190 } 15191 15192 bool Sema::CheckCaseExpression(Expr *E) { 15193 if (E->isTypeDependent()) 15194 return true; 15195 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15196 return E->getType()->isIntegralOrEnumerationType(); 15197 return false; 15198 } 15199 15200 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15201 ExprResult 15202 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15203 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15204 "Unknown Objective-C Boolean value!"); 15205 QualType BoolT = Context.ObjCBuiltinBoolTy; 15206 if (!Context.getBOOLDecl()) { 15207 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15208 Sema::LookupOrdinaryName); 15209 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15210 NamedDecl *ND = Result.getFoundDecl(); 15211 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15212 Context.setBOOLDecl(TD); 15213 } 15214 } 15215 if (Context.getBOOLDecl()) 15216 BoolT = Context.getBOOLType(); 15217 return new (Context) 15218 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15219 } 15220 15221 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15222 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15223 SourceLocation RParen) { 15224 15225 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15226 15227 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15228 [&](const AvailabilitySpec &Spec) { 15229 return Spec.getPlatform() == Platform; 15230 }); 15231 15232 VersionTuple Version; 15233 if (Spec != AvailSpecs.end()) 15234 Version = Spec->getVersion(); 15235 15236 return new (Context) 15237 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15238 } 15239