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 const ObjCPropertyDecl *ObjCPDecl = nullptr; 188 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 189 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 190 AvailabilityResult PDeclResult = 191 PD->getAvailability(nullptr, ContextVersion); 192 if (PDeclResult == Result) 193 ObjCPDecl = PD; 194 } 195 } 196 197 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 198 ObjCPDecl, ObjCPropertyAccess); 199 } 200 } 201 202 /// \brief Emit a note explaining that this function is deleted. 203 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 204 assert(Decl->isDeleted()); 205 206 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 207 208 if (Method && Method->isDeleted() && Method->isDefaulted()) { 209 // If the method was explicitly defaulted, point at that declaration. 210 if (!Method->isImplicit()) 211 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 212 213 // Try to diagnose why this special member function was implicitly 214 // deleted. This might fail, if that reason no longer applies. 215 CXXSpecialMember CSM = getSpecialMember(Method); 216 if (CSM != CXXInvalid) 217 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 218 219 return; 220 } 221 222 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 223 if (Ctor && Ctor->isInheritingConstructor()) 224 return NoteDeletedInheritingConstructor(Ctor); 225 226 Diag(Decl->getLocation(), diag::note_availability_specified_here) 227 << Decl << true; 228 } 229 230 /// \brief Determine whether a FunctionDecl was ever declared with an 231 /// explicit storage class. 232 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 233 for (auto I : D->redecls()) { 234 if (I->getStorageClass() != SC_None) 235 return true; 236 } 237 return false; 238 } 239 240 /// \brief Check whether we're in an extern inline function and referring to a 241 /// variable or function with internal linkage (C11 6.7.4p3). 242 /// 243 /// This is only a warning because we used to silently accept this code, but 244 /// in many cases it will not behave correctly. This is not enabled in C++ mode 245 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 246 /// and so while there may still be user mistakes, most of the time we can't 247 /// prove that there are errors. 248 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 249 const NamedDecl *D, 250 SourceLocation Loc) { 251 // This is disabled under C++; there are too many ways for this to fire in 252 // contexts where the warning is a false positive, or where it is technically 253 // correct but benign. 254 if (S.getLangOpts().CPlusPlus) 255 return; 256 257 // Check if this is an inlined function or method. 258 FunctionDecl *Current = S.getCurFunctionDecl(); 259 if (!Current) 260 return; 261 if (!Current->isInlined()) 262 return; 263 if (!Current->isExternallyVisible()) 264 return; 265 266 // Check if the decl has internal linkage. 267 if (D->getFormalLinkage() != InternalLinkage) 268 return; 269 270 // Downgrade from ExtWarn to Extension if 271 // (1) the supposedly external inline function is in the main file, 272 // and probably won't be included anywhere else. 273 // (2) the thing we're referencing is a pure function. 274 // (3) the thing we're referencing is another inline function. 275 // This last can give us false negatives, but it's better than warning on 276 // wrappers for simple C library functions. 277 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 278 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 279 if (!DowngradeWarning && UsedFn) 280 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 281 282 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 283 : diag::ext_internal_in_extern_inline) 284 << /*IsVar=*/!UsedFn << D; 285 286 S.MaybeSuggestAddingStaticToDecl(Current); 287 288 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 289 << D; 290 } 291 292 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 293 const FunctionDecl *First = Cur->getFirstDecl(); 294 295 // Suggest "static" on the function, if possible. 296 if (!hasAnyExplicitStorageClass(First)) { 297 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 298 Diag(DeclBegin, diag::note_convert_inline_to_static) 299 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 300 } 301 } 302 303 /// \brief Determine whether the use of this declaration is valid, and 304 /// emit any corresponding diagnostics. 305 /// 306 /// This routine diagnoses various problems with referencing 307 /// declarations that can occur when using a declaration. For example, 308 /// it might warn if a deprecated or unavailable declaration is being 309 /// used, or produce an error (and return true) if a C++0x deleted 310 /// function is being used. 311 /// 312 /// \returns true if there was an error (this declaration cannot be 313 /// referenced), false otherwise. 314 /// 315 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 316 const ObjCInterfaceDecl *UnknownObjCClass, 317 bool ObjCPropertyAccess) { 318 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 319 // If there were any diagnostics suppressed by template argument deduction, 320 // emit them now. 321 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 322 if (Pos != SuppressedDiagnostics.end()) { 323 for (const PartialDiagnosticAt &Suppressed : Pos->second) 324 Diag(Suppressed.first, Suppressed.second); 325 326 // Clear out the list of suppressed diagnostics, so that we don't emit 327 // them again for this specialization. However, we don't obsolete this 328 // entry from the table, because we want to avoid ever emitting these 329 // diagnostics again. 330 Pos->second.clear(); 331 } 332 333 // C++ [basic.start.main]p3: 334 // The function 'main' shall not be used within a program. 335 if (cast<FunctionDecl>(D)->isMain()) 336 Diag(Loc, diag::ext_main_used); 337 } 338 339 // See if this is an auto-typed variable whose initializer we are parsing. 340 if (ParsingInitForAutoVars.count(D)) { 341 if (isa<BindingDecl>(D)) { 342 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 343 << D->getDeclName(); 344 } else { 345 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 346 347 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 348 << D->getDeclName() << (unsigned)AT->getKeyword(); 349 } 350 return true; 351 } 352 353 // See if this is a deleted function. 354 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 355 if (FD->isDeleted()) { 356 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 357 if (Ctor && Ctor->isInheritingConstructor()) 358 Diag(Loc, diag::err_deleted_inherited_ctor_use) 359 << Ctor->getParent() 360 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 361 else 362 Diag(Loc, diag::err_deleted_function_use); 363 NoteDeletedFunction(FD); 364 return true; 365 } 366 367 // If the function has a deduced return type, and we can't deduce it, 368 // then we can't use it either. 369 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 370 DeduceReturnType(FD, Loc)) 371 return true; 372 } 373 374 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 375 // Only the variables omp_in and omp_out are allowed in the combiner. 376 // Only the variables omp_priv and omp_orig are allowed in the 377 // initializer-clause. 378 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 379 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 380 isa<VarDecl>(D)) { 381 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 382 << getCurFunction()->HasOMPDeclareReductionCombiner; 383 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 384 return true; 385 } 386 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 387 ObjCPropertyAccess); 388 389 DiagnoseUnusedOfDecl(*this, D, Loc); 390 391 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 392 393 return false; 394 } 395 396 /// \brief Retrieve the message suffix that should be added to a 397 /// diagnostic complaining about the given function being deleted or 398 /// unavailable. 399 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 400 std::string Message; 401 if (FD->getAvailability(&Message)) 402 return ": " + Message; 403 404 return std::string(); 405 } 406 407 /// DiagnoseSentinelCalls - This routine checks whether a call or 408 /// message-send is to a declaration with the sentinel attribute, and 409 /// if so, it checks that the requirements of the sentinel are 410 /// satisfied. 411 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 412 ArrayRef<Expr *> Args) { 413 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 414 if (!attr) 415 return; 416 417 // The number of formal parameters of the declaration. 418 unsigned numFormalParams; 419 420 // The kind of declaration. This is also an index into a %select in 421 // the diagnostic. 422 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 423 424 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 425 numFormalParams = MD->param_size(); 426 calleeType = CT_Method; 427 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 428 numFormalParams = FD->param_size(); 429 calleeType = CT_Function; 430 } else if (isa<VarDecl>(D)) { 431 QualType type = cast<ValueDecl>(D)->getType(); 432 const FunctionType *fn = nullptr; 433 if (const PointerType *ptr = type->getAs<PointerType>()) { 434 fn = ptr->getPointeeType()->getAs<FunctionType>(); 435 if (!fn) return; 436 calleeType = CT_Function; 437 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 438 fn = ptr->getPointeeType()->castAs<FunctionType>(); 439 calleeType = CT_Block; 440 } else { 441 return; 442 } 443 444 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 445 numFormalParams = proto->getNumParams(); 446 } else { 447 numFormalParams = 0; 448 } 449 } else { 450 return; 451 } 452 453 // "nullPos" is the number of formal parameters at the end which 454 // effectively count as part of the variadic arguments. This is 455 // useful if you would prefer to not have *any* formal parameters, 456 // but the language forces you to have at least one. 457 unsigned nullPos = attr->getNullPos(); 458 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 459 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 460 461 // The number of arguments which should follow the sentinel. 462 unsigned numArgsAfterSentinel = attr->getSentinel(); 463 464 // If there aren't enough arguments for all the formal parameters, 465 // the sentinel, and the args after the sentinel, complain. 466 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 467 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 468 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 469 return; 470 } 471 472 // Otherwise, find the sentinel expression. 473 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 474 if (!sentinelExpr) return; 475 if (sentinelExpr->isValueDependent()) return; 476 if (Context.isSentinelNullExpr(sentinelExpr)) return; 477 478 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 479 // or 'NULL' if those are actually defined in the context. Only use 480 // 'nil' for ObjC methods, where it's much more likely that the 481 // variadic arguments form a list of object pointers. 482 SourceLocation MissingNilLoc 483 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 484 std::string NullValue; 485 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 486 NullValue = "nil"; 487 else if (getLangOpts().CPlusPlus11) 488 NullValue = "nullptr"; 489 else if (PP.isMacroDefined("NULL")) 490 NullValue = "NULL"; 491 else 492 NullValue = "(void*) 0"; 493 494 if (MissingNilLoc.isInvalid()) 495 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 496 else 497 Diag(MissingNilLoc, diag::warn_missing_sentinel) 498 << int(calleeType) 499 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 500 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 501 } 502 503 SourceRange Sema::getExprRange(Expr *E) const { 504 return E ? E->getSourceRange() : SourceRange(); 505 } 506 507 //===----------------------------------------------------------------------===// 508 // Standard Promotions and Conversions 509 //===----------------------------------------------------------------------===// 510 511 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 512 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 513 // Handle any placeholder expressions which made it here. 514 if (E->getType()->isPlaceholderType()) { 515 ExprResult result = CheckPlaceholderExpr(E); 516 if (result.isInvalid()) return ExprError(); 517 E = result.get(); 518 } 519 520 QualType Ty = E->getType(); 521 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 522 523 if (Ty->isFunctionType()) { 524 // If we are here, we are not calling a function but taking 525 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 526 if (getLangOpts().OpenCL) { 527 if (Diagnose) 528 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 529 return ExprError(); 530 } 531 532 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 533 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 534 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 535 return ExprError(); 536 537 E = ImpCastExprToType(E, Context.getPointerType(Ty), 538 CK_FunctionToPointerDecay).get(); 539 } else if (Ty->isArrayType()) { 540 // In C90 mode, arrays only promote to pointers if the array expression is 541 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 542 // type 'array of type' is converted to an expression that has type 'pointer 543 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 544 // that has type 'array of type' ...". The relevant change is "an lvalue" 545 // (C90) to "an expression" (C99). 546 // 547 // C++ 4.2p1: 548 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 549 // T" can be converted to an rvalue of type "pointer to T". 550 // 551 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 552 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 553 CK_ArrayToPointerDecay).get(); 554 } 555 return E; 556 } 557 558 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 559 // Check to see if we are dereferencing a null pointer. If so, 560 // and if not volatile-qualified, this is undefined behavior that the 561 // optimizer will delete, so warn about it. People sometimes try to use this 562 // to get a deterministic trap and are surprised by clang's behavior. This 563 // only handles the pattern "*null", which is a very syntactic check. 564 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 565 if (UO->getOpcode() == UO_Deref && 566 UO->getSubExpr()->IgnoreParenCasts()-> 567 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 568 !UO->getType().isVolatileQualified()) { 569 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 570 S.PDiag(diag::warn_indirection_through_null) 571 << UO->getSubExpr()->getSourceRange()); 572 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 573 S.PDiag(diag::note_indirection_through_null)); 574 } 575 } 576 577 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 578 SourceLocation AssignLoc, 579 const Expr* RHS) { 580 const ObjCIvarDecl *IV = OIRE->getDecl(); 581 if (!IV) 582 return; 583 584 DeclarationName MemberName = IV->getDeclName(); 585 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 586 if (!Member || !Member->isStr("isa")) 587 return; 588 589 const Expr *Base = OIRE->getBase(); 590 QualType BaseType = Base->getType(); 591 if (OIRE->isArrow()) 592 BaseType = BaseType->getPointeeType(); 593 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 594 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 595 ObjCInterfaceDecl *ClassDeclared = nullptr; 596 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 597 if (!ClassDeclared->getSuperClass() 598 && (*ClassDeclared->ivar_begin()) == IV) { 599 if (RHS) { 600 NamedDecl *ObjectSetClass = 601 S.LookupSingleName(S.TUScope, 602 &S.Context.Idents.get("object_setClass"), 603 SourceLocation(), S.LookupOrdinaryName); 604 if (ObjectSetClass) { 605 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 606 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 607 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 608 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 609 AssignLoc), ",") << 610 FixItHint::CreateInsertion(RHSLocEnd, ")"); 611 } 612 else 613 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 614 } else { 615 NamedDecl *ObjectGetClass = 616 S.LookupSingleName(S.TUScope, 617 &S.Context.Idents.get("object_getClass"), 618 SourceLocation(), S.LookupOrdinaryName); 619 if (ObjectGetClass) 620 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 621 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 622 FixItHint::CreateReplacement( 623 SourceRange(OIRE->getOpLoc(), 624 OIRE->getLocEnd()), ")"); 625 else 626 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 627 } 628 S.Diag(IV->getLocation(), diag::note_ivar_decl); 629 } 630 } 631 } 632 633 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 634 // Handle any placeholder expressions which made it here. 635 if (E->getType()->isPlaceholderType()) { 636 ExprResult result = CheckPlaceholderExpr(E); 637 if (result.isInvalid()) return ExprError(); 638 E = result.get(); 639 } 640 641 // C++ [conv.lval]p1: 642 // A glvalue of a non-function, non-array type T can be 643 // converted to a prvalue. 644 if (!E->isGLValue()) return E; 645 646 QualType T = E->getType(); 647 assert(!T.isNull() && "r-value conversion on typeless expression?"); 648 649 // We don't want to throw lvalue-to-rvalue casts on top of 650 // expressions of certain types in C++. 651 if (getLangOpts().CPlusPlus && 652 (E->getType() == Context.OverloadTy || 653 T->isDependentType() || 654 T->isRecordType())) 655 return E; 656 657 // The C standard is actually really unclear on this point, and 658 // DR106 tells us what the result should be but not why. It's 659 // generally best to say that void types just doesn't undergo 660 // lvalue-to-rvalue at all. Note that expressions of unqualified 661 // 'void' type are never l-values, but qualified void can be. 662 if (T->isVoidType()) 663 return E; 664 665 // OpenCL usually rejects direct accesses to values of 'half' type. 666 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 667 T->isHalfType()) { 668 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 669 << 0 << T; 670 return ExprError(); 671 } 672 673 CheckForNullPointerDereference(*this, E); 674 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 675 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 676 &Context.Idents.get("object_getClass"), 677 SourceLocation(), LookupOrdinaryName); 678 if (ObjectGetClass) 679 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 680 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 681 FixItHint::CreateReplacement( 682 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 683 else 684 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 685 } 686 else if (const ObjCIvarRefExpr *OIRE = 687 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 688 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 689 690 // C++ [conv.lval]p1: 691 // [...] If T is a non-class type, the type of the prvalue is the 692 // cv-unqualified version of T. Otherwise, the type of the 693 // rvalue is T. 694 // 695 // C99 6.3.2.1p2: 696 // If the lvalue has qualified type, the value has the unqualified 697 // version of the type of the lvalue; otherwise, the value has the 698 // type of the lvalue. 699 if (T.hasQualifiers()) 700 T = T.getUnqualifiedType(); 701 702 // Under the MS ABI, lock down the inheritance model now. 703 if (T->isMemberPointerType() && 704 Context.getTargetInfo().getCXXABI().isMicrosoft()) 705 (void)isCompleteType(E->getExprLoc(), T); 706 707 UpdateMarkingForLValueToRValue(E); 708 709 // Loading a __weak object implicitly retains the value, so we need a cleanup to 710 // balance that. 711 if (getLangOpts().ObjCAutoRefCount && 712 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 713 Cleanup.setExprNeedsCleanups(true); 714 715 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 716 nullptr, VK_RValue); 717 718 // C11 6.3.2.1p2: 719 // ... if the lvalue has atomic type, the value has the non-atomic version 720 // of the type of the lvalue ... 721 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 722 T = Atomic->getValueType().getUnqualifiedType(); 723 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 724 nullptr, VK_RValue); 725 } 726 727 return Res; 728 } 729 730 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 731 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 732 if (Res.isInvalid()) 733 return ExprError(); 734 Res = DefaultLvalueConversion(Res.get()); 735 if (Res.isInvalid()) 736 return ExprError(); 737 return Res; 738 } 739 740 /// CallExprUnaryConversions - a special case of an unary conversion 741 /// performed on a function designator of a call expression. 742 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 743 QualType Ty = E->getType(); 744 ExprResult Res = E; 745 // Only do implicit cast for a function type, but not for a pointer 746 // to function type. 747 if (Ty->isFunctionType()) { 748 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 749 CK_FunctionToPointerDecay).get(); 750 if (Res.isInvalid()) 751 return ExprError(); 752 } 753 Res = DefaultLvalueConversion(Res.get()); 754 if (Res.isInvalid()) 755 return ExprError(); 756 return Res.get(); 757 } 758 759 /// UsualUnaryConversions - Performs various conversions that are common to most 760 /// operators (C99 6.3). The conversions of array and function types are 761 /// sometimes suppressed. For example, the array->pointer conversion doesn't 762 /// apply if the array is an argument to the sizeof or address (&) operators. 763 /// In these instances, this routine should *not* be called. 764 ExprResult Sema::UsualUnaryConversions(Expr *E) { 765 // First, convert to an r-value. 766 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 767 if (Res.isInvalid()) 768 return ExprError(); 769 E = Res.get(); 770 771 QualType Ty = E->getType(); 772 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 773 774 // Half FP have to be promoted to float unless it is natively supported 775 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 776 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 777 778 // Try to perform integral promotions if the object has a theoretically 779 // promotable type. 780 if (Ty->isIntegralOrUnscopedEnumerationType()) { 781 // C99 6.3.1.1p2: 782 // 783 // The following may be used in an expression wherever an int or 784 // unsigned int may be used: 785 // - an object or expression with an integer type whose integer 786 // conversion rank is less than or equal to the rank of int 787 // and unsigned int. 788 // - A bit-field of type _Bool, int, signed int, or unsigned int. 789 // 790 // If an int can represent all values of the original type, the 791 // value is converted to an int; otherwise, it is converted to an 792 // unsigned int. These are called the integer promotions. All 793 // other types are unchanged by the integer promotions. 794 795 QualType PTy = Context.isPromotableBitField(E); 796 if (!PTy.isNull()) { 797 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 798 return E; 799 } 800 if (Ty->isPromotableIntegerType()) { 801 QualType PT = Context.getPromotedIntegerType(Ty); 802 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 803 return E; 804 } 805 } 806 return E; 807 } 808 809 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 810 /// do not have a prototype. Arguments that have type float or __fp16 811 /// are promoted to double. All other argument types are converted by 812 /// UsualUnaryConversions(). 813 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 814 QualType Ty = E->getType(); 815 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 816 817 ExprResult Res = UsualUnaryConversions(E); 818 if (Res.isInvalid()) 819 return ExprError(); 820 E = Res.get(); 821 822 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 823 // double. 824 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 825 if (BTy && (BTy->getKind() == BuiltinType::Half || 826 BTy->getKind() == BuiltinType::Float)) 827 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 828 829 // C++ performs lvalue-to-rvalue conversion as a default argument 830 // promotion, even on class types, but note: 831 // C++11 [conv.lval]p2: 832 // When an lvalue-to-rvalue conversion occurs in an unevaluated 833 // operand or a subexpression thereof the value contained in the 834 // referenced object is not accessed. Otherwise, if the glvalue 835 // has a class type, the conversion copy-initializes a temporary 836 // of type T from the glvalue and the result of the conversion 837 // is a prvalue for the temporary. 838 // FIXME: add some way to gate this entire thing for correctness in 839 // potentially potentially evaluated contexts. 840 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 841 ExprResult Temp = PerformCopyInitialization( 842 InitializedEntity::InitializeTemporary(E->getType()), 843 E->getExprLoc(), E); 844 if (Temp.isInvalid()) 845 return ExprError(); 846 E = Temp.get(); 847 } 848 849 return E; 850 } 851 852 /// Determine the degree of POD-ness for an expression. 853 /// Incomplete types are considered POD, since this check can be performed 854 /// when we're in an unevaluated context. 855 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 856 if (Ty->isIncompleteType()) { 857 // C++11 [expr.call]p7: 858 // After these conversions, if the argument does not have arithmetic, 859 // enumeration, pointer, pointer to member, or class type, the program 860 // is ill-formed. 861 // 862 // Since we've already performed array-to-pointer and function-to-pointer 863 // decay, the only such type in C++ is cv void. This also handles 864 // initializer lists as variadic arguments. 865 if (Ty->isVoidType()) 866 return VAK_Invalid; 867 868 if (Ty->isObjCObjectType()) 869 return VAK_Invalid; 870 return VAK_Valid; 871 } 872 873 if (Ty.isCXX98PODType(Context)) 874 return VAK_Valid; 875 876 // C++11 [expr.call]p7: 877 // Passing a potentially-evaluated argument of class type (Clause 9) 878 // having a non-trivial copy constructor, a non-trivial move constructor, 879 // or a non-trivial destructor, with no corresponding parameter, 880 // is conditionally-supported with implementation-defined semantics. 881 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 882 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 883 if (!Record->hasNonTrivialCopyConstructor() && 884 !Record->hasNonTrivialMoveConstructor() && 885 !Record->hasNonTrivialDestructor()) 886 return VAK_ValidInCXX11; 887 888 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 889 return VAK_Valid; 890 891 if (Ty->isObjCObjectType()) 892 return VAK_Invalid; 893 894 if (getLangOpts().MSVCCompat) 895 return VAK_MSVCUndefined; 896 897 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 898 // permitted to reject them. We should consider doing so. 899 return VAK_Undefined; 900 } 901 902 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 903 // Don't allow one to pass an Objective-C interface to a vararg. 904 const QualType &Ty = E->getType(); 905 VarArgKind VAK = isValidVarArgType(Ty); 906 907 // Complain about passing non-POD types through varargs. 908 switch (VAK) { 909 case VAK_ValidInCXX11: 910 DiagRuntimeBehavior( 911 E->getLocStart(), nullptr, 912 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 913 << Ty << CT); 914 // Fall through. 915 case VAK_Valid: 916 if (Ty->isRecordType()) { 917 // This is unlikely to be what the user intended. If the class has a 918 // 'c_str' member function, the user probably meant to call that. 919 DiagRuntimeBehavior(E->getLocStart(), nullptr, 920 PDiag(diag::warn_pass_class_arg_to_vararg) 921 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 922 } 923 break; 924 925 case VAK_Undefined: 926 case VAK_MSVCUndefined: 927 DiagRuntimeBehavior( 928 E->getLocStart(), nullptr, 929 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 930 << getLangOpts().CPlusPlus11 << Ty << CT); 931 break; 932 933 case VAK_Invalid: 934 if (Ty->isObjCObjectType()) 935 DiagRuntimeBehavior( 936 E->getLocStart(), nullptr, 937 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 938 << Ty << CT); 939 else 940 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 941 << isa<InitListExpr>(E) << Ty << CT; 942 break; 943 } 944 } 945 946 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 947 /// will create a trap if the resulting type is not a POD type. 948 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 949 FunctionDecl *FDecl) { 950 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 951 // Strip the unbridged-cast placeholder expression off, if applicable. 952 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 953 (CT == VariadicMethod || 954 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 955 E = stripARCUnbridgedCast(E); 956 957 // Otherwise, do normal placeholder checking. 958 } else { 959 ExprResult ExprRes = CheckPlaceholderExpr(E); 960 if (ExprRes.isInvalid()) 961 return ExprError(); 962 E = ExprRes.get(); 963 } 964 } 965 966 ExprResult ExprRes = DefaultArgumentPromotion(E); 967 if (ExprRes.isInvalid()) 968 return ExprError(); 969 E = ExprRes.get(); 970 971 // Diagnostics regarding non-POD argument types are 972 // emitted along with format string checking in Sema::CheckFunctionCall(). 973 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 974 // Turn this into a trap. 975 CXXScopeSpec SS; 976 SourceLocation TemplateKWLoc; 977 UnqualifiedId Name; 978 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 979 E->getLocStart()); 980 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 981 Name, true, false); 982 if (TrapFn.isInvalid()) 983 return ExprError(); 984 985 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 986 E->getLocStart(), None, 987 E->getLocEnd()); 988 if (Call.isInvalid()) 989 return ExprError(); 990 991 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 992 Call.get(), E); 993 if (Comma.isInvalid()) 994 return ExprError(); 995 return Comma.get(); 996 } 997 998 if (!getLangOpts().CPlusPlus && 999 RequireCompleteType(E->getExprLoc(), E->getType(), 1000 diag::err_call_incomplete_argument)) 1001 return ExprError(); 1002 1003 return E; 1004 } 1005 1006 /// \brief Converts an integer to complex float type. Helper function of 1007 /// UsualArithmeticConversions() 1008 /// 1009 /// \return false if the integer expression is an integer type and is 1010 /// successfully converted to the complex type. 1011 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1012 ExprResult &ComplexExpr, 1013 QualType IntTy, 1014 QualType ComplexTy, 1015 bool SkipCast) { 1016 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1017 if (SkipCast) return false; 1018 if (IntTy->isIntegerType()) { 1019 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1020 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1021 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1022 CK_FloatingRealToComplex); 1023 } else { 1024 assert(IntTy->isComplexIntegerType()); 1025 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1026 CK_IntegralComplexToFloatingComplex); 1027 } 1028 return false; 1029 } 1030 1031 /// \brief Handle arithmetic conversion with complex types. Helper function of 1032 /// UsualArithmeticConversions() 1033 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1034 ExprResult &RHS, QualType LHSType, 1035 QualType RHSType, 1036 bool IsCompAssign) { 1037 // if we have an integer operand, the result is the complex type. 1038 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1039 /*skipCast*/false)) 1040 return LHSType; 1041 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1042 /*skipCast*/IsCompAssign)) 1043 return RHSType; 1044 1045 // This handles complex/complex, complex/float, or float/complex. 1046 // When both operands are complex, the shorter operand is converted to the 1047 // type of the longer, and that is the type of the result. This corresponds 1048 // to what is done when combining two real floating-point operands. 1049 // The fun begins when size promotion occur across type domains. 1050 // From H&S 6.3.4: When one operand is complex and the other is a real 1051 // floating-point type, the less precise type is converted, within it's 1052 // real or complex domain, to the precision of the other type. For example, 1053 // when combining a "long double" with a "double _Complex", the 1054 // "double _Complex" is promoted to "long double _Complex". 1055 1056 // Compute the rank of the two types, regardless of whether they are complex. 1057 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1058 1059 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1060 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1061 QualType LHSElementType = 1062 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1063 QualType RHSElementType = 1064 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1065 1066 QualType ResultType = S.Context.getComplexType(LHSElementType); 1067 if (Order < 0) { 1068 // Promote the precision of the LHS if not an assignment. 1069 ResultType = S.Context.getComplexType(RHSElementType); 1070 if (!IsCompAssign) { 1071 if (LHSComplexType) 1072 LHS = 1073 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1074 else 1075 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1076 } 1077 } else if (Order > 0) { 1078 // Promote the precision of the RHS. 1079 if (RHSComplexType) 1080 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1081 else 1082 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1083 } 1084 return ResultType; 1085 } 1086 1087 /// \brief Hande arithmetic conversion from integer to float. Helper function 1088 /// of UsualArithmeticConversions() 1089 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1090 ExprResult &IntExpr, 1091 QualType FloatTy, QualType IntTy, 1092 bool ConvertFloat, bool ConvertInt) { 1093 if (IntTy->isIntegerType()) { 1094 if (ConvertInt) 1095 // Convert intExpr to the lhs floating point type. 1096 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1097 CK_IntegralToFloating); 1098 return FloatTy; 1099 } 1100 1101 // Convert both sides to the appropriate complex float. 1102 assert(IntTy->isComplexIntegerType()); 1103 QualType result = S.Context.getComplexType(FloatTy); 1104 1105 // _Complex int -> _Complex float 1106 if (ConvertInt) 1107 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1108 CK_IntegralComplexToFloatingComplex); 1109 1110 // float -> _Complex float 1111 if (ConvertFloat) 1112 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1113 CK_FloatingRealToComplex); 1114 1115 return result; 1116 } 1117 1118 /// \brief Handle arithmethic conversion with floating point types. Helper 1119 /// function of UsualArithmeticConversions() 1120 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1121 ExprResult &RHS, QualType LHSType, 1122 QualType RHSType, bool IsCompAssign) { 1123 bool LHSFloat = LHSType->isRealFloatingType(); 1124 bool RHSFloat = RHSType->isRealFloatingType(); 1125 1126 // If we have two real floating types, convert the smaller operand 1127 // to the bigger result. 1128 if (LHSFloat && RHSFloat) { 1129 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1130 if (order > 0) { 1131 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1132 return LHSType; 1133 } 1134 1135 assert(order < 0 && "illegal float comparison"); 1136 if (!IsCompAssign) 1137 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1138 return RHSType; 1139 } 1140 1141 if (LHSFloat) { 1142 // Half FP has to be promoted to float unless it is natively supported 1143 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1144 LHSType = S.Context.FloatTy; 1145 1146 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1147 /*convertFloat=*/!IsCompAssign, 1148 /*convertInt=*/ true); 1149 } 1150 assert(RHSFloat); 1151 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1152 /*convertInt=*/ true, 1153 /*convertFloat=*/!IsCompAssign); 1154 } 1155 1156 /// \brief Diagnose attempts to convert between __float128 and long double if 1157 /// there is no support for such conversion. Helper function of 1158 /// UsualArithmeticConversions(). 1159 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1160 QualType RHSType) { 1161 /* No issue converting if at least one of the types is not a floating point 1162 type or the two types have the same rank. 1163 */ 1164 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1165 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1166 return false; 1167 1168 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1169 "The remaining types must be floating point types."); 1170 1171 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1172 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1173 1174 QualType LHSElemType = LHSComplex ? 1175 LHSComplex->getElementType() : LHSType; 1176 QualType RHSElemType = RHSComplex ? 1177 RHSComplex->getElementType() : RHSType; 1178 1179 // No issue if the two types have the same representation 1180 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1181 &S.Context.getFloatTypeSemantics(RHSElemType)) 1182 return false; 1183 1184 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1185 RHSElemType == S.Context.LongDoubleTy); 1186 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1187 RHSElemType == S.Context.Float128Ty); 1188 1189 /* We've handled the situation where __float128 and long double have the same 1190 representation. The only other allowable conversion is if long double is 1191 really just double. 1192 */ 1193 return Float128AndLongDouble && 1194 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1195 &llvm::APFloat::IEEEdouble); 1196 } 1197 1198 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1199 1200 namespace { 1201 /// These helper callbacks are placed in an anonymous namespace to 1202 /// permit their use as function template parameters. 1203 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1204 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1205 } 1206 1207 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1208 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1209 CK_IntegralComplexCast); 1210 } 1211 } 1212 1213 /// \brief Handle integer arithmetic conversions. Helper function of 1214 /// UsualArithmeticConversions() 1215 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1216 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1217 ExprResult &RHS, QualType LHSType, 1218 QualType RHSType, bool IsCompAssign) { 1219 // The rules for this case are in C99 6.3.1.8 1220 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1221 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1222 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1223 if (LHSSigned == RHSSigned) { 1224 // Same signedness; use the higher-ranked type 1225 if (order >= 0) { 1226 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1227 return LHSType; 1228 } else if (!IsCompAssign) 1229 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1230 return RHSType; 1231 } else if (order != (LHSSigned ? 1 : -1)) { 1232 // The unsigned type has greater than or equal rank to the 1233 // signed type, so use the unsigned type 1234 if (RHSSigned) { 1235 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1236 return LHSType; 1237 } else if (!IsCompAssign) 1238 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1239 return RHSType; 1240 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1241 // The two types are different widths; if we are here, that 1242 // means the signed type is larger than the unsigned type, so 1243 // use the signed type. 1244 if (LHSSigned) { 1245 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1246 return LHSType; 1247 } else if (!IsCompAssign) 1248 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1249 return RHSType; 1250 } else { 1251 // The signed type is higher-ranked than the unsigned type, 1252 // but isn't actually any bigger (like unsigned int and long 1253 // on most 32-bit systems). Use the unsigned type corresponding 1254 // to the signed type. 1255 QualType result = 1256 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1257 RHS = (*doRHSCast)(S, RHS.get(), result); 1258 if (!IsCompAssign) 1259 LHS = (*doLHSCast)(S, LHS.get(), result); 1260 return result; 1261 } 1262 } 1263 1264 /// \brief Handle conversions with GCC complex int extension. Helper function 1265 /// of UsualArithmeticConversions() 1266 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1267 ExprResult &RHS, QualType LHSType, 1268 QualType RHSType, 1269 bool IsCompAssign) { 1270 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1271 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1272 1273 if (LHSComplexInt && RHSComplexInt) { 1274 QualType LHSEltType = LHSComplexInt->getElementType(); 1275 QualType RHSEltType = RHSComplexInt->getElementType(); 1276 QualType ScalarType = 1277 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1278 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1279 1280 return S.Context.getComplexType(ScalarType); 1281 } 1282 1283 if (LHSComplexInt) { 1284 QualType LHSEltType = LHSComplexInt->getElementType(); 1285 QualType ScalarType = 1286 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1287 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1288 QualType ComplexType = S.Context.getComplexType(ScalarType); 1289 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1290 CK_IntegralRealToComplex); 1291 1292 return ComplexType; 1293 } 1294 1295 assert(RHSComplexInt); 1296 1297 QualType RHSEltType = RHSComplexInt->getElementType(); 1298 QualType ScalarType = 1299 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1300 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1301 QualType ComplexType = S.Context.getComplexType(ScalarType); 1302 1303 if (!IsCompAssign) 1304 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1305 CK_IntegralRealToComplex); 1306 return ComplexType; 1307 } 1308 1309 /// UsualArithmeticConversions - Performs various conversions that are common to 1310 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1311 /// routine returns the first non-arithmetic type found. The client is 1312 /// responsible for emitting appropriate error diagnostics. 1313 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1314 bool IsCompAssign) { 1315 if (!IsCompAssign) { 1316 LHS = UsualUnaryConversions(LHS.get()); 1317 if (LHS.isInvalid()) 1318 return QualType(); 1319 } 1320 1321 RHS = UsualUnaryConversions(RHS.get()); 1322 if (RHS.isInvalid()) 1323 return QualType(); 1324 1325 // For conversion purposes, we ignore any qualifiers. 1326 // For example, "const float" and "float" are equivalent. 1327 QualType LHSType = 1328 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1329 QualType RHSType = 1330 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1331 1332 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1333 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1334 LHSType = AtomicLHS->getValueType(); 1335 1336 // If both types are identical, no conversion is needed. 1337 if (LHSType == RHSType) 1338 return LHSType; 1339 1340 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1341 // The caller can deal with this (e.g. pointer + int). 1342 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1343 return QualType(); 1344 1345 // Apply unary and bitfield promotions to the LHS's type. 1346 QualType LHSUnpromotedType = LHSType; 1347 if (LHSType->isPromotableIntegerType()) 1348 LHSType = Context.getPromotedIntegerType(LHSType); 1349 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1350 if (!LHSBitfieldPromoteTy.isNull()) 1351 LHSType = LHSBitfieldPromoteTy; 1352 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1353 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1354 1355 // If both types are identical, no conversion is needed. 1356 if (LHSType == RHSType) 1357 return LHSType; 1358 1359 // At this point, we have two different arithmetic types. 1360 1361 // Diagnose attempts to convert between __float128 and long double where 1362 // such conversions currently can't be handled. 1363 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1364 return QualType(); 1365 1366 // Handle complex types first (C99 6.3.1.8p1). 1367 if (LHSType->isComplexType() || RHSType->isComplexType()) 1368 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1369 IsCompAssign); 1370 1371 // Now handle "real" floating types (i.e. float, double, long double). 1372 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1373 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1374 IsCompAssign); 1375 1376 // Handle GCC complex int extension. 1377 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1378 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1379 IsCompAssign); 1380 1381 // Finally, we have two differing integer types. 1382 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1383 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1384 } 1385 1386 1387 //===----------------------------------------------------------------------===// 1388 // Semantic Analysis for various Expression Types 1389 //===----------------------------------------------------------------------===// 1390 1391 1392 ExprResult 1393 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1394 SourceLocation DefaultLoc, 1395 SourceLocation RParenLoc, 1396 Expr *ControllingExpr, 1397 ArrayRef<ParsedType> ArgTypes, 1398 ArrayRef<Expr *> ArgExprs) { 1399 unsigned NumAssocs = ArgTypes.size(); 1400 assert(NumAssocs == ArgExprs.size()); 1401 1402 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1403 for (unsigned i = 0; i < NumAssocs; ++i) { 1404 if (ArgTypes[i]) 1405 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1406 else 1407 Types[i] = nullptr; 1408 } 1409 1410 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1411 ControllingExpr, 1412 llvm::makeArrayRef(Types, NumAssocs), 1413 ArgExprs); 1414 delete [] Types; 1415 return ER; 1416 } 1417 1418 ExprResult 1419 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1420 SourceLocation DefaultLoc, 1421 SourceLocation RParenLoc, 1422 Expr *ControllingExpr, 1423 ArrayRef<TypeSourceInfo *> Types, 1424 ArrayRef<Expr *> Exprs) { 1425 unsigned NumAssocs = Types.size(); 1426 assert(NumAssocs == Exprs.size()); 1427 1428 // Decay and strip qualifiers for the controlling expression type, and handle 1429 // placeholder type replacement. See committee discussion from WG14 DR423. 1430 { 1431 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1432 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1433 if (R.isInvalid()) 1434 return ExprError(); 1435 ControllingExpr = R.get(); 1436 } 1437 1438 // The controlling expression is an unevaluated operand, so side effects are 1439 // likely unintended. 1440 if (ActiveTemplateInstantiations.empty() && 1441 ControllingExpr->HasSideEffects(Context, false)) 1442 Diag(ControllingExpr->getExprLoc(), 1443 diag::warn_side_effects_unevaluated_context); 1444 1445 bool TypeErrorFound = false, 1446 IsResultDependent = ControllingExpr->isTypeDependent(), 1447 ContainsUnexpandedParameterPack 1448 = ControllingExpr->containsUnexpandedParameterPack(); 1449 1450 for (unsigned i = 0; i < NumAssocs; ++i) { 1451 if (Exprs[i]->containsUnexpandedParameterPack()) 1452 ContainsUnexpandedParameterPack = true; 1453 1454 if (Types[i]) { 1455 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1456 ContainsUnexpandedParameterPack = true; 1457 1458 if (Types[i]->getType()->isDependentType()) { 1459 IsResultDependent = true; 1460 } else { 1461 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1462 // complete object type other than a variably modified type." 1463 unsigned D = 0; 1464 if (Types[i]->getType()->isIncompleteType()) 1465 D = diag::err_assoc_type_incomplete; 1466 else if (!Types[i]->getType()->isObjectType()) 1467 D = diag::err_assoc_type_nonobject; 1468 else if (Types[i]->getType()->isVariablyModifiedType()) 1469 D = diag::err_assoc_type_variably_modified; 1470 1471 if (D != 0) { 1472 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1473 << Types[i]->getTypeLoc().getSourceRange() 1474 << Types[i]->getType(); 1475 TypeErrorFound = true; 1476 } 1477 1478 // C11 6.5.1.1p2 "No two generic associations in the same generic 1479 // selection shall specify compatible types." 1480 for (unsigned j = i+1; j < NumAssocs; ++j) 1481 if (Types[j] && !Types[j]->getType()->isDependentType() && 1482 Context.typesAreCompatible(Types[i]->getType(), 1483 Types[j]->getType())) { 1484 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1485 diag::err_assoc_compatible_types) 1486 << Types[j]->getTypeLoc().getSourceRange() 1487 << Types[j]->getType() 1488 << Types[i]->getType(); 1489 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1490 diag::note_compat_assoc) 1491 << Types[i]->getTypeLoc().getSourceRange() 1492 << Types[i]->getType(); 1493 TypeErrorFound = true; 1494 } 1495 } 1496 } 1497 } 1498 if (TypeErrorFound) 1499 return ExprError(); 1500 1501 // If we determined that the generic selection is result-dependent, don't 1502 // try to compute the result expression. 1503 if (IsResultDependent) 1504 return new (Context) GenericSelectionExpr( 1505 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1506 ContainsUnexpandedParameterPack); 1507 1508 SmallVector<unsigned, 1> CompatIndices; 1509 unsigned DefaultIndex = -1U; 1510 for (unsigned i = 0; i < NumAssocs; ++i) { 1511 if (!Types[i]) 1512 DefaultIndex = i; 1513 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1514 Types[i]->getType())) 1515 CompatIndices.push_back(i); 1516 } 1517 1518 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1519 // type compatible with at most one of the types named in its generic 1520 // association list." 1521 if (CompatIndices.size() > 1) { 1522 // We strip parens here because the controlling expression is typically 1523 // parenthesized in macro definitions. 1524 ControllingExpr = ControllingExpr->IgnoreParens(); 1525 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1526 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1527 << (unsigned) CompatIndices.size(); 1528 for (unsigned I : CompatIndices) { 1529 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1530 diag::note_compat_assoc) 1531 << Types[I]->getTypeLoc().getSourceRange() 1532 << Types[I]->getType(); 1533 } 1534 return ExprError(); 1535 } 1536 1537 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1538 // its controlling expression shall have type compatible with exactly one of 1539 // the types named in its generic association list." 1540 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1541 // We strip parens here because the controlling expression is typically 1542 // parenthesized in macro definitions. 1543 ControllingExpr = ControllingExpr->IgnoreParens(); 1544 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1545 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1546 return ExprError(); 1547 } 1548 1549 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1550 // type name that is compatible with the type of the controlling expression, 1551 // then the result expression of the generic selection is the expression 1552 // in that generic association. Otherwise, the result expression of the 1553 // generic selection is the expression in the default generic association." 1554 unsigned ResultIndex = 1555 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1556 1557 return new (Context) GenericSelectionExpr( 1558 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1559 ContainsUnexpandedParameterPack, ResultIndex); 1560 } 1561 1562 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1563 /// location of the token and the offset of the ud-suffix within it. 1564 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1565 unsigned Offset) { 1566 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1567 S.getLangOpts()); 1568 } 1569 1570 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1571 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1572 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1573 IdentifierInfo *UDSuffix, 1574 SourceLocation UDSuffixLoc, 1575 ArrayRef<Expr*> Args, 1576 SourceLocation LitEndLoc) { 1577 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1578 1579 QualType ArgTy[2]; 1580 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1581 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1582 if (ArgTy[ArgIdx]->isArrayType()) 1583 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1584 } 1585 1586 DeclarationName OpName = 1587 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1588 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1589 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1590 1591 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1592 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1593 /*AllowRaw*/false, /*AllowTemplate*/false, 1594 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1595 return ExprError(); 1596 1597 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1598 } 1599 1600 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1601 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1602 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1603 /// multiple tokens. However, the common case is that StringToks points to one 1604 /// string. 1605 /// 1606 ExprResult 1607 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1608 assert(!StringToks.empty() && "Must have at least one string!"); 1609 1610 StringLiteralParser Literal(StringToks, PP); 1611 if (Literal.hadError) 1612 return ExprError(); 1613 1614 SmallVector<SourceLocation, 4> StringTokLocs; 1615 for (const Token &Tok : StringToks) 1616 StringTokLocs.push_back(Tok.getLocation()); 1617 1618 QualType CharTy = Context.CharTy; 1619 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1620 if (Literal.isWide()) { 1621 CharTy = Context.getWideCharType(); 1622 Kind = StringLiteral::Wide; 1623 } else if (Literal.isUTF8()) { 1624 Kind = StringLiteral::UTF8; 1625 } else if (Literal.isUTF16()) { 1626 CharTy = Context.Char16Ty; 1627 Kind = StringLiteral::UTF16; 1628 } else if (Literal.isUTF32()) { 1629 CharTy = Context.Char32Ty; 1630 Kind = StringLiteral::UTF32; 1631 } else if (Literal.isPascal()) { 1632 CharTy = Context.UnsignedCharTy; 1633 } 1634 1635 QualType CharTyConst = CharTy; 1636 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1637 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1638 CharTyConst.addConst(); 1639 1640 // Get an array type for the string, according to C99 6.4.5. This includes 1641 // the nul terminator character as well as the string length for pascal 1642 // strings. 1643 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1644 llvm::APInt(32, Literal.GetNumStringChars()+1), 1645 ArrayType::Normal, 0); 1646 1647 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1648 if (getLangOpts().OpenCL) { 1649 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1650 } 1651 1652 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1653 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1654 Kind, Literal.Pascal, StrTy, 1655 &StringTokLocs[0], 1656 StringTokLocs.size()); 1657 if (Literal.getUDSuffix().empty()) 1658 return Lit; 1659 1660 // We're building a user-defined literal. 1661 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1662 SourceLocation UDSuffixLoc = 1663 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1664 Literal.getUDSuffixOffset()); 1665 1666 // Make sure we're allowed user-defined literals here. 1667 if (!UDLScope) 1668 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1669 1670 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1671 // operator "" X (str, len) 1672 QualType SizeType = Context.getSizeType(); 1673 1674 DeclarationName OpName = 1675 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1676 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1677 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1678 1679 QualType ArgTy[] = { 1680 Context.getArrayDecayedType(StrTy), SizeType 1681 }; 1682 1683 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1684 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1685 /*AllowRaw*/false, /*AllowTemplate*/false, 1686 /*AllowStringTemplate*/true)) { 1687 1688 case LOLR_Cooked: { 1689 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1690 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1691 StringTokLocs[0]); 1692 Expr *Args[] = { Lit, LenArg }; 1693 1694 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1695 } 1696 1697 case LOLR_StringTemplate: { 1698 TemplateArgumentListInfo ExplicitArgs; 1699 1700 unsigned CharBits = Context.getIntWidth(CharTy); 1701 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1702 llvm::APSInt Value(CharBits, CharIsUnsigned); 1703 1704 TemplateArgument TypeArg(CharTy); 1705 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1706 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1707 1708 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1709 Value = Lit->getCodeUnit(I); 1710 TemplateArgument Arg(Context, Value, CharTy); 1711 TemplateArgumentLocInfo ArgInfo; 1712 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1713 } 1714 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1715 &ExplicitArgs); 1716 } 1717 case LOLR_Raw: 1718 case LOLR_Template: 1719 llvm_unreachable("unexpected literal operator lookup result"); 1720 case LOLR_Error: 1721 return ExprError(); 1722 } 1723 llvm_unreachable("unexpected literal operator lookup result"); 1724 } 1725 1726 ExprResult 1727 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1728 SourceLocation Loc, 1729 const CXXScopeSpec *SS) { 1730 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1731 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1732 } 1733 1734 /// BuildDeclRefExpr - Build an expression that references a 1735 /// declaration that does not require a closure capture. 1736 ExprResult 1737 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1738 const DeclarationNameInfo &NameInfo, 1739 const CXXScopeSpec *SS, NamedDecl *FoundD, 1740 const TemplateArgumentListInfo *TemplateArgs) { 1741 if (getLangOpts().CUDA) 1742 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1743 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1744 if (!IsAllowedCUDACall(Caller, Callee)) { 1745 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1746 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1747 << IdentifyCUDATarget(Caller); 1748 Diag(D->getLocation(), diag::note_previous_decl) 1749 << D->getIdentifier(); 1750 return ExprError(); 1751 } 1752 } 1753 1754 bool RefersToCapturedVariable = 1755 isa<VarDecl>(D) && 1756 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1757 1758 DeclRefExpr *E; 1759 if (isa<VarTemplateSpecializationDecl>(D)) { 1760 VarTemplateSpecializationDecl *VarSpec = 1761 cast<VarTemplateSpecializationDecl>(D); 1762 1763 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1764 : NestedNameSpecifierLoc(), 1765 VarSpec->getTemplateKeywordLoc(), D, 1766 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1767 FoundD, TemplateArgs); 1768 } else { 1769 assert(!TemplateArgs && "No template arguments for non-variable" 1770 " template specialization references"); 1771 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1772 : NestedNameSpecifierLoc(), 1773 SourceLocation(), D, RefersToCapturedVariable, 1774 NameInfo, Ty, VK, FoundD); 1775 } 1776 1777 MarkDeclRefReferenced(E); 1778 1779 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1780 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1781 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1782 recordUseOfEvaluatedWeak(E); 1783 1784 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1785 UnusedPrivateFields.remove(FD); 1786 // Just in case we're building an illegal pointer-to-member. 1787 if (FD->isBitField()) 1788 E->setObjectKind(OK_BitField); 1789 } 1790 1791 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1792 // designates a bit-field. 1793 if (auto *BD = dyn_cast<BindingDecl>(D)) 1794 if (auto *BE = BD->getBinding()) 1795 E->setObjectKind(BE->getObjectKind()); 1796 1797 return E; 1798 } 1799 1800 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1801 /// possibly a list of template arguments. 1802 /// 1803 /// If this produces template arguments, it is permitted to call 1804 /// DecomposeTemplateName. 1805 /// 1806 /// This actually loses a lot of source location information for 1807 /// non-standard name kinds; we should consider preserving that in 1808 /// some way. 1809 void 1810 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1811 TemplateArgumentListInfo &Buffer, 1812 DeclarationNameInfo &NameInfo, 1813 const TemplateArgumentListInfo *&TemplateArgs) { 1814 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1815 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1816 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1817 1818 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1819 Id.TemplateId->NumArgs); 1820 translateTemplateArguments(TemplateArgsPtr, Buffer); 1821 1822 TemplateName TName = Id.TemplateId->Template.get(); 1823 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1824 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1825 TemplateArgs = &Buffer; 1826 } else { 1827 NameInfo = GetNameFromUnqualifiedId(Id); 1828 TemplateArgs = nullptr; 1829 } 1830 } 1831 1832 static void emitEmptyLookupTypoDiagnostic( 1833 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1834 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1835 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1836 DeclContext *Ctx = 1837 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1838 if (!TC) { 1839 // Emit a special diagnostic for failed member lookups. 1840 // FIXME: computing the declaration context might fail here (?) 1841 if (Ctx) 1842 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1843 << SS.getRange(); 1844 else 1845 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1846 return; 1847 } 1848 1849 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1850 bool DroppedSpecifier = 1851 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1852 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1853 ? diag::note_implicit_param_decl 1854 : diag::note_previous_decl; 1855 if (!Ctx) 1856 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1857 SemaRef.PDiag(NoteID)); 1858 else 1859 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1860 << Typo << Ctx << DroppedSpecifier 1861 << SS.getRange(), 1862 SemaRef.PDiag(NoteID)); 1863 } 1864 1865 /// Diagnose an empty lookup. 1866 /// 1867 /// \return false if new lookup candidates were found 1868 bool 1869 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1870 std::unique_ptr<CorrectionCandidateCallback> CCC, 1871 TemplateArgumentListInfo *ExplicitTemplateArgs, 1872 ArrayRef<Expr *> Args, TypoExpr **Out) { 1873 DeclarationName Name = R.getLookupName(); 1874 1875 unsigned diagnostic = diag::err_undeclared_var_use; 1876 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1877 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1878 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1879 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1880 diagnostic = diag::err_undeclared_use; 1881 diagnostic_suggest = diag::err_undeclared_use_suggest; 1882 } 1883 1884 // If the original lookup was an unqualified lookup, fake an 1885 // unqualified lookup. This is useful when (for example) the 1886 // original lookup would not have found something because it was a 1887 // dependent name. 1888 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1889 while (DC) { 1890 if (isa<CXXRecordDecl>(DC)) { 1891 LookupQualifiedName(R, DC); 1892 1893 if (!R.empty()) { 1894 // Don't give errors about ambiguities in this lookup. 1895 R.suppressDiagnostics(); 1896 1897 // During a default argument instantiation the CurContext points 1898 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1899 // function parameter list, hence add an explicit check. 1900 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1901 ActiveTemplateInstantiations.back().Kind == 1902 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1903 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1904 bool isInstance = CurMethod && 1905 CurMethod->isInstance() && 1906 DC == CurMethod->getParent() && !isDefaultArgument; 1907 1908 // Give a code modification hint to insert 'this->'. 1909 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1910 // Actually quite difficult! 1911 if (getLangOpts().MSVCCompat) 1912 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1913 if (isInstance) { 1914 Diag(R.getNameLoc(), diagnostic) << Name 1915 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1916 CheckCXXThisCapture(R.getNameLoc()); 1917 } else { 1918 Diag(R.getNameLoc(), diagnostic) << Name; 1919 } 1920 1921 // Do we really want to note all of these? 1922 for (NamedDecl *D : R) 1923 Diag(D->getLocation(), diag::note_dependent_var_use); 1924 1925 // Return true if we are inside a default argument instantiation 1926 // and the found name refers to an instance member function, otherwise 1927 // the function calling DiagnoseEmptyLookup will try to create an 1928 // implicit member call and this is wrong for default argument. 1929 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1930 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1931 return true; 1932 } 1933 1934 // Tell the callee to try to recover. 1935 return false; 1936 } 1937 1938 R.clear(); 1939 } 1940 1941 // In Microsoft mode, if we are performing lookup from within a friend 1942 // function definition declared at class scope then we must set 1943 // DC to the lexical parent to be able to search into the parent 1944 // class. 1945 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1946 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1947 DC->getLexicalParent()->isRecord()) 1948 DC = DC->getLexicalParent(); 1949 else 1950 DC = DC->getParent(); 1951 } 1952 1953 // We didn't find anything, so try to correct for a typo. 1954 TypoCorrection Corrected; 1955 if (S && Out) { 1956 SourceLocation TypoLoc = R.getNameLoc(); 1957 assert(!ExplicitTemplateArgs && 1958 "Diagnosing an empty lookup with explicit template args!"); 1959 *Out = CorrectTypoDelayed( 1960 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1961 [=](const TypoCorrection &TC) { 1962 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1963 diagnostic, diagnostic_suggest); 1964 }, 1965 nullptr, CTK_ErrorRecovery); 1966 if (*Out) 1967 return true; 1968 } else if (S && (Corrected = 1969 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1970 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1971 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1972 bool DroppedSpecifier = 1973 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1974 R.setLookupName(Corrected.getCorrection()); 1975 1976 bool AcceptableWithRecovery = false; 1977 bool AcceptableWithoutRecovery = false; 1978 NamedDecl *ND = Corrected.getFoundDecl(); 1979 if (ND) { 1980 if (Corrected.isOverloaded()) { 1981 OverloadCandidateSet OCS(R.getNameLoc(), 1982 OverloadCandidateSet::CSK_Normal); 1983 OverloadCandidateSet::iterator Best; 1984 for (NamedDecl *CD : Corrected) { 1985 if (FunctionTemplateDecl *FTD = 1986 dyn_cast<FunctionTemplateDecl>(CD)) 1987 AddTemplateOverloadCandidate( 1988 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1989 Args, OCS); 1990 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1991 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1992 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1993 Args, OCS); 1994 } 1995 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1996 case OR_Success: 1997 ND = Best->FoundDecl; 1998 Corrected.setCorrectionDecl(ND); 1999 break; 2000 default: 2001 // FIXME: Arbitrarily pick the first declaration for the note. 2002 Corrected.setCorrectionDecl(ND); 2003 break; 2004 } 2005 } 2006 R.addDecl(ND); 2007 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2008 CXXRecordDecl *Record = nullptr; 2009 if (Corrected.getCorrectionSpecifier()) { 2010 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2011 Record = Ty->getAsCXXRecordDecl(); 2012 } 2013 if (!Record) 2014 Record = cast<CXXRecordDecl>( 2015 ND->getDeclContext()->getRedeclContext()); 2016 R.setNamingClass(Record); 2017 } 2018 2019 auto *UnderlyingND = ND->getUnderlyingDecl(); 2020 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2021 isa<FunctionTemplateDecl>(UnderlyingND); 2022 // FIXME: If we ended up with a typo for a type name or 2023 // Objective-C class name, we're in trouble because the parser 2024 // is in the wrong place to recover. Suggest the typo 2025 // correction, but don't make it a fix-it since we're not going 2026 // to recover well anyway. 2027 AcceptableWithoutRecovery = 2028 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2029 } else { 2030 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2031 // because we aren't able to recover. 2032 AcceptableWithoutRecovery = true; 2033 } 2034 2035 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2036 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2037 ? diag::note_implicit_param_decl 2038 : diag::note_previous_decl; 2039 if (SS.isEmpty()) 2040 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2041 PDiag(NoteID), AcceptableWithRecovery); 2042 else 2043 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2044 << Name << computeDeclContext(SS, false) 2045 << DroppedSpecifier << SS.getRange(), 2046 PDiag(NoteID), AcceptableWithRecovery); 2047 2048 // Tell the callee whether to try to recover. 2049 return !AcceptableWithRecovery; 2050 } 2051 } 2052 R.clear(); 2053 2054 // Emit a special diagnostic for failed member lookups. 2055 // FIXME: computing the declaration context might fail here (?) 2056 if (!SS.isEmpty()) { 2057 Diag(R.getNameLoc(), diag::err_no_member) 2058 << Name << computeDeclContext(SS, false) 2059 << SS.getRange(); 2060 return true; 2061 } 2062 2063 // Give up, we can't recover. 2064 Diag(R.getNameLoc(), diagnostic) << Name; 2065 return true; 2066 } 2067 2068 /// In Microsoft mode, if we are inside a template class whose parent class has 2069 /// dependent base classes, and we can't resolve an unqualified identifier, then 2070 /// assume the identifier is a member of a dependent base class. We can only 2071 /// recover successfully in static methods, instance methods, and other contexts 2072 /// where 'this' is available. This doesn't precisely match MSVC's 2073 /// instantiation model, but it's close enough. 2074 static Expr * 2075 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2076 DeclarationNameInfo &NameInfo, 2077 SourceLocation TemplateKWLoc, 2078 const TemplateArgumentListInfo *TemplateArgs) { 2079 // Only try to recover from lookup into dependent bases in static methods or 2080 // contexts where 'this' is available. 2081 QualType ThisType = S.getCurrentThisType(); 2082 const CXXRecordDecl *RD = nullptr; 2083 if (!ThisType.isNull()) 2084 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2085 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2086 RD = MD->getParent(); 2087 if (!RD || !RD->hasAnyDependentBases()) 2088 return nullptr; 2089 2090 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2091 // is available, suggest inserting 'this->' as a fixit. 2092 SourceLocation Loc = NameInfo.getLoc(); 2093 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2094 DB << NameInfo.getName() << RD; 2095 2096 if (!ThisType.isNull()) { 2097 DB << FixItHint::CreateInsertion(Loc, "this->"); 2098 return CXXDependentScopeMemberExpr::Create( 2099 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2100 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2101 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2102 } 2103 2104 // Synthesize a fake NNS that points to the derived class. This will 2105 // perform name lookup during template instantiation. 2106 CXXScopeSpec SS; 2107 auto *NNS = 2108 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2109 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2110 return DependentScopeDeclRefExpr::Create( 2111 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2112 TemplateArgs); 2113 } 2114 2115 ExprResult 2116 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2117 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2118 bool HasTrailingLParen, bool IsAddressOfOperand, 2119 std::unique_ptr<CorrectionCandidateCallback> CCC, 2120 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2121 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2122 "cannot be direct & operand and have a trailing lparen"); 2123 if (SS.isInvalid()) 2124 return ExprError(); 2125 2126 TemplateArgumentListInfo TemplateArgsBuffer; 2127 2128 // Decompose the UnqualifiedId into the following data. 2129 DeclarationNameInfo NameInfo; 2130 const TemplateArgumentListInfo *TemplateArgs; 2131 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2132 2133 DeclarationName Name = NameInfo.getName(); 2134 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2135 SourceLocation NameLoc = NameInfo.getLoc(); 2136 2137 // C++ [temp.dep.expr]p3: 2138 // An id-expression is type-dependent if it contains: 2139 // -- an identifier that was declared with a dependent type, 2140 // (note: handled after lookup) 2141 // -- a template-id that is dependent, 2142 // (note: handled in BuildTemplateIdExpr) 2143 // -- a conversion-function-id that specifies a dependent type, 2144 // -- a nested-name-specifier that contains a class-name that 2145 // names a dependent type. 2146 // Determine whether this is a member of an unknown specialization; 2147 // we need to handle these differently. 2148 bool DependentID = false; 2149 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2150 Name.getCXXNameType()->isDependentType()) { 2151 DependentID = true; 2152 } else if (SS.isSet()) { 2153 if (DeclContext *DC = computeDeclContext(SS, false)) { 2154 if (RequireCompleteDeclContext(SS, DC)) 2155 return ExprError(); 2156 } else { 2157 DependentID = true; 2158 } 2159 } 2160 2161 if (DependentID) 2162 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2163 IsAddressOfOperand, TemplateArgs); 2164 2165 // Perform the required lookup. 2166 LookupResult R(*this, NameInfo, 2167 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2168 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2169 if (TemplateArgs) { 2170 // Lookup the template name again to correctly establish the context in 2171 // which it was found. This is really unfortunate as we already did the 2172 // lookup to determine that it was a template name in the first place. If 2173 // this becomes a performance hit, we can work harder to preserve those 2174 // results until we get here but it's likely not worth it. 2175 bool MemberOfUnknownSpecialization; 2176 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2177 MemberOfUnknownSpecialization); 2178 2179 if (MemberOfUnknownSpecialization || 2180 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2181 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2182 IsAddressOfOperand, TemplateArgs); 2183 } else { 2184 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2185 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2186 2187 // If the result might be in a dependent base class, this is a dependent 2188 // id-expression. 2189 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2190 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2191 IsAddressOfOperand, TemplateArgs); 2192 2193 // If this reference is in an Objective-C method, then we need to do 2194 // some special Objective-C lookup, too. 2195 if (IvarLookupFollowUp) { 2196 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2197 if (E.isInvalid()) 2198 return ExprError(); 2199 2200 if (Expr *Ex = E.getAs<Expr>()) 2201 return Ex; 2202 } 2203 } 2204 2205 if (R.isAmbiguous()) 2206 return ExprError(); 2207 2208 // This could be an implicitly declared function reference (legal in C90, 2209 // extension in C99, forbidden in C++). 2210 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2211 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2212 if (D) R.addDecl(D); 2213 } 2214 2215 // Determine whether this name might be a candidate for 2216 // argument-dependent lookup. 2217 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2218 2219 if (R.empty() && !ADL) { 2220 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2221 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2222 TemplateKWLoc, TemplateArgs)) 2223 return E; 2224 } 2225 2226 // Don't diagnose an empty lookup for inline assembly. 2227 if (IsInlineAsmIdentifier) 2228 return ExprError(); 2229 2230 // If this name wasn't predeclared and if this is not a function 2231 // call, diagnose the problem. 2232 TypoExpr *TE = nullptr; 2233 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2234 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2235 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2236 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2237 "Typo correction callback misconfigured"); 2238 if (CCC) { 2239 // Make sure the callback knows what the typo being diagnosed is. 2240 CCC->setTypoName(II); 2241 if (SS.isValid()) 2242 CCC->setTypoNNS(SS.getScopeRep()); 2243 } 2244 if (DiagnoseEmptyLookup(S, SS, R, 2245 CCC ? std::move(CCC) : std::move(DefaultValidator), 2246 nullptr, None, &TE)) { 2247 if (TE && KeywordReplacement) { 2248 auto &State = getTypoExprState(TE); 2249 auto BestTC = State.Consumer->getNextCorrection(); 2250 if (BestTC.isKeyword()) { 2251 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2252 if (State.DiagHandler) 2253 State.DiagHandler(BestTC); 2254 KeywordReplacement->startToken(); 2255 KeywordReplacement->setKind(II->getTokenID()); 2256 KeywordReplacement->setIdentifierInfo(II); 2257 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2258 // Clean up the state associated with the TypoExpr, since it has 2259 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2260 clearDelayedTypo(TE); 2261 // Signal that a correction to a keyword was performed by returning a 2262 // valid-but-null ExprResult. 2263 return (Expr*)nullptr; 2264 } 2265 State.Consumer->resetCorrectionStream(); 2266 } 2267 return TE ? TE : ExprError(); 2268 } 2269 2270 assert(!R.empty() && 2271 "DiagnoseEmptyLookup returned false but added no results"); 2272 2273 // If we found an Objective-C instance variable, let 2274 // LookupInObjCMethod build the appropriate expression to 2275 // reference the ivar. 2276 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2277 R.clear(); 2278 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2279 // In a hopelessly buggy code, Objective-C instance variable 2280 // lookup fails and no expression will be built to reference it. 2281 if (!E.isInvalid() && !E.get()) 2282 return ExprError(); 2283 return E; 2284 } 2285 } 2286 2287 // This is guaranteed from this point on. 2288 assert(!R.empty() || ADL); 2289 2290 // Check whether this might be a C++ implicit instance member access. 2291 // C++ [class.mfct.non-static]p3: 2292 // When an id-expression that is not part of a class member access 2293 // syntax and not used to form a pointer to member is used in the 2294 // body of a non-static member function of class X, if name lookup 2295 // resolves the name in the id-expression to a non-static non-type 2296 // member of some class C, the id-expression is transformed into a 2297 // class member access expression using (*this) as the 2298 // postfix-expression to the left of the . operator. 2299 // 2300 // But we don't actually need to do this for '&' operands if R 2301 // resolved to a function or overloaded function set, because the 2302 // expression is ill-formed if it actually works out to be a 2303 // non-static member function: 2304 // 2305 // C++ [expr.ref]p4: 2306 // Otherwise, if E1.E2 refers to a non-static member function. . . 2307 // [t]he expression can be used only as the left-hand operand of a 2308 // member function call. 2309 // 2310 // There are other safeguards against such uses, but it's important 2311 // to get this right here so that we don't end up making a 2312 // spuriously dependent expression if we're inside a dependent 2313 // instance method. 2314 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2315 bool MightBeImplicitMember; 2316 if (!IsAddressOfOperand) 2317 MightBeImplicitMember = true; 2318 else if (!SS.isEmpty()) 2319 MightBeImplicitMember = false; 2320 else if (R.isOverloadedResult()) 2321 MightBeImplicitMember = false; 2322 else if (R.isUnresolvableResult()) 2323 MightBeImplicitMember = true; 2324 else 2325 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2326 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2327 isa<MSPropertyDecl>(R.getFoundDecl()); 2328 2329 if (MightBeImplicitMember) 2330 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2331 R, TemplateArgs, S); 2332 } 2333 2334 if (TemplateArgs || TemplateKWLoc.isValid()) { 2335 2336 // In C++1y, if this is a variable template id, then check it 2337 // in BuildTemplateIdExpr(). 2338 // The single lookup result must be a variable template declaration. 2339 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2340 Id.TemplateId->Kind == TNK_Var_template) { 2341 assert(R.getAsSingle<VarTemplateDecl>() && 2342 "There should only be one declaration found."); 2343 } 2344 2345 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2346 } 2347 2348 return BuildDeclarationNameExpr(SS, R, ADL); 2349 } 2350 2351 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2352 /// declaration name, generally during template instantiation. 2353 /// There's a large number of things which don't need to be done along 2354 /// this path. 2355 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2356 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2357 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2358 DeclContext *DC = computeDeclContext(SS, false); 2359 if (!DC) 2360 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2361 NameInfo, /*TemplateArgs=*/nullptr); 2362 2363 if (RequireCompleteDeclContext(SS, DC)) 2364 return ExprError(); 2365 2366 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2367 LookupQualifiedName(R, DC); 2368 2369 if (R.isAmbiguous()) 2370 return ExprError(); 2371 2372 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2373 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2374 NameInfo, /*TemplateArgs=*/nullptr); 2375 2376 if (R.empty()) { 2377 Diag(NameInfo.getLoc(), diag::err_no_member) 2378 << NameInfo.getName() << DC << SS.getRange(); 2379 return ExprError(); 2380 } 2381 2382 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2383 // Diagnose a missing typename if this resolved unambiguously to a type in 2384 // a dependent context. If we can recover with a type, downgrade this to 2385 // a warning in Microsoft compatibility mode. 2386 unsigned DiagID = diag::err_typename_missing; 2387 if (RecoveryTSI && getLangOpts().MSVCCompat) 2388 DiagID = diag::ext_typename_missing; 2389 SourceLocation Loc = SS.getBeginLoc(); 2390 auto D = Diag(Loc, DiagID); 2391 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2392 << SourceRange(Loc, NameInfo.getEndLoc()); 2393 2394 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2395 // context. 2396 if (!RecoveryTSI) 2397 return ExprError(); 2398 2399 // Only issue the fixit if we're prepared to recover. 2400 D << FixItHint::CreateInsertion(Loc, "typename "); 2401 2402 // Recover by pretending this was an elaborated type. 2403 QualType Ty = Context.getTypeDeclType(TD); 2404 TypeLocBuilder TLB; 2405 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2406 2407 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2408 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2409 QTL.setElaboratedKeywordLoc(SourceLocation()); 2410 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2411 2412 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2413 2414 return ExprEmpty(); 2415 } 2416 2417 // Defend against this resolving to an implicit member access. We usually 2418 // won't get here if this might be a legitimate a class member (we end up in 2419 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2420 // a pointer-to-member or in an unevaluated context in C++11. 2421 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2422 return BuildPossibleImplicitMemberExpr(SS, 2423 /*TemplateKWLoc=*/SourceLocation(), 2424 R, /*TemplateArgs=*/nullptr, S); 2425 2426 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2427 } 2428 2429 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2430 /// detected that we're currently inside an ObjC method. Perform some 2431 /// additional lookup. 2432 /// 2433 /// Ideally, most of this would be done by lookup, but there's 2434 /// actually quite a lot of extra work involved. 2435 /// 2436 /// Returns a null sentinel to indicate trivial success. 2437 ExprResult 2438 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2439 IdentifierInfo *II, bool AllowBuiltinCreation) { 2440 SourceLocation Loc = Lookup.getNameLoc(); 2441 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2442 2443 // Check for error condition which is already reported. 2444 if (!CurMethod) 2445 return ExprError(); 2446 2447 // There are two cases to handle here. 1) scoped lookup could have failed, 2448 // in which case we should look for an ivar. 2) scoped lookup could have 2449 // found a decl, but that decl is outside the current instance method (i.e. 2450 // a global variable). In these two cases, we do a lookup for an ivar with 2451 // this name, if the lookup sucedes, we replace it our current decl. 2452 2453 // If we're in a class method, we don't normally want to look for 2454 // ivars. But if we don't find anything else, and there's an 2455 // ivar, that's an error. 2456 bool IsClassMethod = CurMethod->isClassMethod(); 2457 2458 bool LookForIvars; 2459 if (Lookup.empty()) 2460 LookForIvars = true; 2461 else if (IsClassMethod) 2462 LookForIvars = false; 2463 else 2464 LookForIvars = (Lookup.isSingleResult() && 2465 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2466 ObjCInterfaceDecl *IFace = nullptr; 2467 if (LookForIvars) { 2468 IFace = CurMethod->getClassInterface(); 2469 ObjCInterfaceDecl *ClassDeclared; 2470 ObjCIvarDecl *IV = nullptr; 2471 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2472 // Diagnose using an ivar in a class method. 2473 if (IsClassMethod) 2474 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2475 << IV->getDeclName()); 2476 2477 // If we're referencing an invalid decl, just return this as a silent 2478 // error node. The error diagnostic was already emitted on the decl. 2479 if (IV->isInvalidDecl()) 2480 return ExprError(); 2481 2482 // Check if referencing a field with __attribute__((deprecated)). 2483 if (DiagnoseUseOfDecl(IV, Loc)) 2484 return ExprError(); 2485 2486 // Diagnose the use of an ivar outside of the declaring class. 2487 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2488 !declaresSameEntity(ClassDeclared, IFace) && 2489 !getLangOpts().DebuggerSupport) 2490 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2491 2492 // FIXME: This should use a new expr for a direct reference, don't 2493 // turn this into Self->ivar, just return a BareIVarExpr or something. 2494 IdentifierInfo &II = Context.Idents.get("self"); 2495 UnqualifiedId SelfName; 2496 SelfName.setIdentifier(&II, SourceLocation()); 2497 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2498 CXXScopeSpec SelfScopeSpec; 2499 SourceLocation TemplateKWLoc; 2500 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2501 SelfName, false, false); 2502 if (SelfExpr.isInvalid()) 2503 return ExprError(); 2504 2505 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2506 if (SelfExpr.isInvalid()) 2507 return ExprError(); 2508 2509 MarkAnyDeclReferenced(Loc, IV, true); 2510 2511 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2512 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2513 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2514 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2515 2516 ObjCIvarRefExpr *Result = new (Context) 2517 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2518 IV->getLocation(), SelfExpr.get(), true, true); 2519 2520 if (getLangOpts().ObjCAutoRefCount) { 2521 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2522 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2523 recordUseOfEvaluatedWeak(Result); 2524 } 2525 if (CurContext->isClosure()) 2526 Diag(Loc, diag::warn_implicitly_retains_self) 2527 << FixItHint::CreateInsertion(Loc, "self->"); 2528 } 2529 2530 return Result; 2531 } 2532 } else if (CurMethod->isInstanceMethod()) { 2533 // We should warn if a local variable hides an ivar. 2534 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2535 ObjCInterfaceDecl *ClassDeclared; 2536 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2537 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2538 declaresSameEntity(IFace, ClassDeclared)) 2539 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2540 } 2541 } 2542 } else if (Lookup.isSingleResult() && 2543 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2544 // If accessing a stand-alone ivar in a class method, this is an error. 2545 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2546 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2547 << IV->getDeclName()); 2548 } 2549 2550 if (Lookup.empty() && II && AllowBuiltinCreation) { 2551 // FIXME. Consolidate this with similar code in LookupName. 2552 if (unsigned BuiltinID = II->getBuiltinID()) { 2553 if (!(getLangOpts().CPlusPlus && 2554 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2555 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2556 S, Lookup.isForRedeclaration(), 2557 Lookup.getNameLoc()); 2558 if (D) Lookup.addDecl(D); 2559 } 2560 } 2561 } 2562 // Sentinel value saying that we didn't do anything special. 2563 return ExprResult((Expr *)nullptr); 2564 } 2565 2566 /// \brief Cast a base object to a member's actual type. 2567 /// 2568 /// Logically this happens in three phases: 2569 /// 2570 /// * First we cast from the base type to the naming class. 2571 /// The naming class is the class into which we were looking 2572 /// when we found the member; it's the qualifier type if a 2573 /// qualifier was provided, and otherwise it's the base type. 2574 /// 2575 /// * Next we cast from the naming class to the declaring class. 2576 /// If the member we found was brought into a class's scope by 2577 /// a using declaration, this is that class; otherwise it's 2578 /// the class declaring the member. 2579 /// 2580 /// * Finally we cast from the declaring class to the "true" 2581 /// declaring class of the member. This conversion does not 2582 /// obey access control. 2583 ExprResult 2584 Sema::PerformObjectMemberConversion(Expr *From, 2585 NestedNameSpecifier *Qualifier, 2586 NamedDecl *FoundDecl, 2587 NamedDecl *Member) { 2588 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2589 if (!RD) 2590 return From; 2591 2592 QualType DestRecordType; 2593 QualType DestType; 2594 QualType FromRecordType; 2595 QualType FromType = From->getType(); 2596 bool PointerConversions = false; 2597 if (isa<FieldDecl>(Member)) { 2598 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2599 2600 if (FromType->getAs<PointerType>()) { 2601 DestType = Context.getPointerType(DestRecordType); 2602 FromRecordType = FromType->getPointeeType(); 2603 PointerConversions = true; 2604 } else { 2605 DestType = DestRecordType; 2606 FromRecordType = FromType; 2607 } 2608 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2609 if (Method->isStatic()) 2610 return From; 2611 2612 DestType = Method->getThisType(Context); 2613 DestRecordType = DestType->getPointeeType(); 2614 2615 if (FromType->getAs<PointerType>()) { 2616 FromRecordType = FromType->getPointeeType(); 2617 PointerConversions = true; 2618 } else { 2619 FromRecordType = FromType; 2620 DestType = DestRecordType; 2621 } 2622 } else { 2623 // No conversion necessary. 2624 return From; 2625 } 2626 2627 if (DestType->isDependentType() || FromType->isDependentType()) 2628 return From; 2629 2630 // If the unqualified types are the same, no conversion is necessary. 2631 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2632 return From; 2633 2634 SourceRange FromRange = From->getSourceRange(); 2635 SourceLocation FromLoc = FromRange.getBegin(); 2636 2637 ExprValueKind VK = From->getValueKind(); 2638 2639 // C++ [class.member.lookup]p8: 2640 // [...] Ambiguities can often be resolved by qualifying a name with its 2641 // class name. 2642 // 2643 // If the member was a qualified name and the qualified referred to a 2644 // specific base subobject type, we'll cast to that intermediate type 2645 // first and then to the object in which the member is declared. That allows 2646 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2647 // 2648 // class Base { public: int x; }; 2649 // class Derived1 : public Base { }; 2650 // class Derived2 : public Base { }; 2651 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2652 // 2653 // void VeryDerived::f() { 2654 // x = 17; // error: ambiguous base subobjects 2655 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2656 // } 2657 if (Qualifier && Qualifier->getAsType()) { 2658 QualType QType = QualType(Qualifier->getAsType(), 0); 2659 assert(QType->isRecordType() && "lookup done with non-record type"); 2660 2661 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2662 2663 // In C++98, the qualifier type doesn't actually have to be a base 2664 // type of the object type, in which case we just ignore it. 2665 // Otherwise build the appropriate casts. 2666 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2667 CXXCastPath BasePath; 2668 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2669 FromLoc, FromRange, &BasePath)) 2670 return ExprError(); 2671 2672 if (PointerConversions) 2673 QType = Context.getPointerType(QType); 2674 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2675 VK, &BasePath).get(); 2676 2677 FromType = QType; 2678 FromRecordType = QRecordType; 2679 2680 // If the qualifier type was the same as the destination type, 2681 // we're done. 2682 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2683 return From; 2684 } 2685 } 2686 2687 bool IgnoreAccess = false; 2688 2689 // If we actually found the member through a using declaration, cast 2690 // down to the using declaration's type. 2691 // 2692 // Pointer equality is fine here because only one declaration of a 2693 // class ever has member declarations. 2694 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2695 assert(isa<UsingShadowDecl>(FoundDecl)); 2696 QualType URecordType = Context.getTypeDeclType( 2697 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2698 2699 // We only need to do this if the naming-class to declaring-class 2700 // conversion is non-trivial. 2701 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2702 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2703 CXXCastPath BasePath; 2704 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2705 FromLoc, FromRange, &BasePath)) 2706 return ExprError(); 2707 2708 QualType UType = URecordType; 2709 if (PointerConversions) 2710 UType = Context.getPointerType(UType); 2711 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2712 VK, &BasePath).get(); 2713 FromType = UType; 2714 FromRecordType = URecordType; 2715 } 2716 2717 // We don't do access control for the conversion from the 2718 // declaring class to the true declaring class. 2719 IgnoreAccess = true; 2720 } 2721 2722 CXXCastPath BasePath; 2723 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2724 FromLoc, FromRange, &BasePath, 2725 IgnoreAccess)) 2726 return ExprError(); 2727 2728 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2729 VK, &BasePath); 2730 } 2731 2732 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2733 const LookupResult &R, 2734 bool HasTrailingLParen) { 2735 // Only when used directly as the postfix-expression of a call. 2736 if (!HasTrailingLParen) 2737 return false; 2738 2739 // Never if a scope specifier was provided. 2740 if (SS.isSet()) 2741 return false; 2742 2743 // Only in C++ or ObjC++. 2744 if (!getLangOpts().CPlusPlus) 2745 return false; 2746 2747 // Turn off ADL when we find certain kinds of declarations during 2748 // normal lookup: 2749 for (NamedDecl *D : R) { 2750 // C++0x [basic.lookup.argdep]p3: 2751 // -- a declaration of a class member 2752 // Since using decls preserve this property, we check this on the 2753 // original decl. 2754 if (D->isCXXClassMember()) 2755 return false; 2756 2757 // C++0x [basic.lookup.argdep]p3: 2758 // -- a block-scope function declaration that is not a 2759 // using-declaration 2760 // NOTE: we also trigger this for function templates (in fact, we 2761 // don't check the decl type at all, since all other decl types 2762 // turn off ADL anyway). 2763 if (isa<UsingShadowDecl>(D)) 2764 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2765 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2766 return false; 2767 2768 // C++0x [basic.lookup.argdep]p3: 2769 // -- a declaration that is neither a function or a function 2770 // template 2771 // And also for builtin functions. 2772 if (isa<FunctionDecl>(D)) { 2773 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2774 2775 // But also builtin functions. 2776 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2777 return false; 2778 } else if (!isa<FunctionTemplateDecl>(D)) 2779 return false; 2780 } 2781 2782 return true; 2783 } 2784 2785 2786 /// Diagnoses obvious problems with the use of the given declaration 2787 /// as an expression. This is only actually called for lookups that 2788 /// were not overloaded, and it doesn't promise that the declaration 2789 /// will in fact be used. 2790 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2791 if (isa<TypedefNameDecl>(D)) { 2792 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2793 return true; 2794 } 2795 2796 if (isa<ObjCInterfaceDecl>(D)) { 2797 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2798 return true; 2799 } 2800 2801 if (isa<NamespaceDecl>(D)) { 2802 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2803 return true; 2804 } 2805 2806 return false; 2807 } 2808 2809 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2810 LookupResult &R, bool NeedsADL, 2811 bool AcceptInvalidDecl) { 2812 // If this is a single, fully-resolved result and we don't need ADL, 2813 // just build an ordinary singleton decl ref. 2814 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2815 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2816 R.getRepresentativeDecl(), nullptr, 2817 AcceptInvalidDecl); 2818 2819 // We only need to check the declaration if there's exactly one 2820 // result, because in the overloaded case the results can only be 2821 // functions and function templates. 2822 if (R.isSingleResult() && 2823 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2824 return ExprError(); 2825 2826 // Otherwise, just build an unresolved lookup expression. Suppress 2827 // any lookup-related diagnostics; we'll hash these out later, when 2828 // we've picked a target. 2829 R.suppressDiagnostics(); 2830 2831 UnresolvedLookupExpr *ULE 2832 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2833 SS.getWithLocInContext(Context), 2834 R.getLookupNameInfo(), 2835 NeedsADL, R.isOverloadedResult(), 2836 R.begin(), R.end()); 2837 2838 return ULE; 2839 } 2840 2841 /// \brief Complete semantic analysis for a reference to the given declaration. 2842 ExprResult Sema::BuildDeclarationNameExpr( 2843 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2844 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2845 bool AcceptInvalidDecl) { 2846 assert(D && "Cannot refer to a NULL declaration"); 2847 assert(!isa<FunctionTemplateDecl>(D) && 2848 "Cannot refer unambiguously to a function template"); 2849 2850 SourceLocation Loc = NameInfo.getLoc(); 2851 if (CheckDeclInExpr(*this, Loc, D)) 2852 return ExprError(); 2853 2854 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2855 // Specifically diagnose references to class templates that are missing 2856 // a template argument list. 2857 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2858 << Template << SS.getRange(); 2859 Diag(Template->getLocation(), diag::note_template_decl_here); 2860 return ExprError(); 2861 } 2862 2863 // Make sure that we're referring to a value. 2864 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2865 if (!VD) { 2866 Diag(Loc, diag::err_ref_non_value) 2867 << D << SS.getRange(); 2868 Diag(D->getLocation(), diag::note_declared_at); 2869 return ExprError(); 2870 } 2871 2872 // Check whether this declaration can be used. Note that we suppress 2873 // this check when we're going to perform argument-dependent lookup 2874 // on this function name, because this might not be the function 2875 // that overload resolution actually selects. 2876 if (DiagnoseUseOfDecl(VD, Loc)) 2877 return ExprError(); 2878 2879 // Only create DeclRefExpr's for valid Decl's. 2880 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2881 return ExprError(); 2882 2883 // Handle members of anonymous structs and unions. If we got here, 2884 // and the reference is to a class member indirect field, then this 2885 // must be the subject of a pointer-to-member expression. 2886 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2887 if (!indirectField->isCXXClassMember()) 2888 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2889 indirectField); 2890 2891 { 2892 QualType type = VD->getType(); 2893 ExprValueKind valueKind = VK_RValue; 2894 2895 switch (D->getKind()) { 2896 // Ignore all the non-ValueDecl kinds. 2897 #define ABSTRACT_DECL(kind) 2898 #define VALUE(type, base) 2899 #define DECL(type, base) \ 2900 case Decl::type: 2901 #include "clang/AST/DeclNodes.inc" 2902 llvm_unreachable("invalid value decl kind"); 2903 2904 // These shouldn't make it here. 2905 case Decl::ObjCAtDefsField: 2906 case Decl::ObjCIvar: 2907 llvm_unreachable("forming non-member reference to ivar?"); 2908 2909 // Enum constants are always r-values and never references. 2910 // Unresolved using declarations are dependent. 2911 case Decl::EnumConstant: 2912 case Decl::UnresolvedUsingValue: 2913 case Decl::OMPDeclareReduction: 2914 valueKind = VK_RValue; 2915 break; 2916 2917 // Fields and indirect fields that got here must be for 2918 // pointer-to-member expressions; we just call them l-values for 2919 // internal consistency, because this subexpression doesn't really 2920 // exist in the high-level semantics. 2921 case Decl::Field: 2922 case Decl::IndirectField: 2923 assert(getLangOpts().CPlusPlus && 2924 "building reference to field in C?"); 2925 2926 // These can't have reference type in well-formed programs, but 2927 // for internal consistency we do this anyway. 2928 type = type.getNonReferenceType(); 2929 valueKind = VK_LValue; 2930 break; 2931 2932 // Non-type template parameters are either l-values or r-values 2933 // depending on the type. 2934 case Decl::NonTypeTemplateParm: { 2935 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2936 type = reftype->getPointeeType(); 2937 valueKind = VK_LValue; // even if the parameter is an r-value reference 2938 break; 2939 } 2940 2941 // For non-references, we need to strip qualifiers just in case 2942 // the template parameter was declared as 'const int' or whatever. 2943 valueKind = VK_RValue; 2944 type = type.getUnqualifiedType(); 2945 break; 2946 } 2947 2948 case Decl::Var: 2949 case Decl::VarTemplateSpecialization: 2950 case Decl::VarTemplatePartialSpecialization: 2951 case Decl::Decomposition: 2952 case Decl::OMPCapturedExpr: 2953 // In C, "extern void blah;" is valid and is an r-value. 2954 if (!getLangOpts().CPlusPlus && 2955 !type.hasQualifiers() && 2956 type->isVoidType()) { 2957 valueKind = VK_RValue; 2958 break; 2959 } 2960 // fallthrough 2961 2962 case Decl::ImplicitParam: 2963 case Decl::ParmVar: { 2964 // These are always l-values. 2965 valueKind = VK_LValue; 2966 type = type.getNonReferenceType(); 2967 2968 // FIXME: Does the addition of const really only apply in 2969 // potentially-evaluated contexts? Since the variable isn't actually 2970 // captured in an unevaluated context, it seems that the answer is no. 2971 if (!isUnevaluatedContext()) { 2972 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2973 if (!CapturedType.isNull()) 2974 type = CapturedType; 2975 } 2976 2977 break; 2978 } 2979 2980 case Decl::Binding: { 2981 // These are always lvalues. 2982 valueKind = VK_LValue; 2983 type = type.getNonReferenceType(); 2984 // FIXME: Adjust cv-qualifiers for capture. 2985 break; 2986 } 2987 2988 case Decl::Function: { 2989 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2990 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2991 type = Context.BuiltinFnTy; 2992 valueKind = VK_RValue; 2993 break; 2994 } 2995 } 2996 2997 const FunctionType *fty = type->castAs<FunctionType>(); 2998 2999 // If we're referring to a function with an __unknown_anytype 3000 // result type, make the entire expression __unknown_anytype. 3001 if (fty->getReturnType() == Context.UnknownAnyTy) { 3002 type = Context.UnknownAnyTy; 3003 valueKind = VK_RValue; 3004 break; 3005 } 3006 3007 // Functions are l-values in C++. 3008 if (getLangOpts().CPlusPlus) { 3009 valueKind = VK_LValue; 3010 break; 3011 } 3012 3013 // C99 DR 316 says that, if a function type comes from a 3014 // function definition (without a prototype), that type is only 3015 // used for checking compatibility. Therefore, when referencing 3016 // the function, we pretend that we don't have the full function 3017 // type. 3018 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3019 isa<FunctionProtoType>(fty)) 3020 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3021 fty->getExtInfo()); 3022 3023 // Functions are r-values in C. 3024 valueKind = VK_RValue; 3025 break; 3026 } 3027 3028 case Decl::MSProperty: 3029 valueKind = VK_LValue; 3030 break; 3031 3032 case Decl::CXXMethod: 3033 // If we're referring to a method with an __unknown_anytype 3034 // result type, make the entire expression __unknown_anytype. 3035 // This should only be possible with a type written directly. 3036 if (const FunctionProtoType *proto 3037 = dyn_cast<FunctionProtoType>(VD->getType())) 3038 if (proto->getReturnType() == Context.UnknownAnyTy) { 3039 type = Context.UnknownAnyTy; 3040 valueKind = VK_RValue; 3041 break; 3042 } 3043 3044 // C++ methods are l-values if static, r-values if non-static. 3045 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3046 valueKind = VK_LValue; 3047 break; 3048 } 3049 // fallthrough 3050 3051 case Decl::CXXConversion: 3052 case Decl::CXXDestructor: 3053 case Decl::CXXConstructor: 3054 valueKind = VK_RValue; 3055 break; 3056 } 3057 3058 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3059 TemplateArgs); 3060 } 3061 } 3062 3063 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3064 SmallString<32> &Target) { 3065 Target.resize(CharByteWidth * (Source.size() + 1)); 3066 char *ResultPtr = &Target[0]; 3067 const UTF8 *ErrorPtr; 3068 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3069 (void)success; 3070 assert(success); 3071 Target.resize(ResultPtr - &Target[0]); 3072 } 3073 3074 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3075 PredefinedExpr::IdentType IT) { 3076 // Pick the current block, lambda, captured statement or function. 3077 Decl *currentDecl = nullptr; 3078 if (const BlockScopeInfo *BSI = getCurBlock()) 3079 currentDecl = BSI->TheDecl; 3080 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3081 currentDecl = LSI->CallOperator; 3082 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3083 currentDecl = CSI->TheCapturedDecl; 3084 else 3085 currentDecl = getCurFunctionOrMethodDecl(); 3086 3087 if (!currentDecl) { 3088 Diag(Loc, diag::ext_predef_outside_function); 3089 currentDecl = Context.getTranslationUnitDecl(); 3090 } 3091 3092 QualType ResTy; 3093 StringLiteral *SL = nullptr; 3094 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3095 ResTy = Context.DependentTy; 3096 else { 3097 // Pre-defined identifiers are of type char[x], where x is the length of 3098 // the string. 3099 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3100 unsigned Length = Str.length(); 3101 3102 llvm::APInt LengthI(32, Length + 1); 3103 if (IT == PredefinedExpr::LFunction) { 3104 ResTy = Context.WideCharTy.withConst(); 3105 SmallString<32> RawChars; 3106 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3107 Str, RawChars); 3108 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3109 /*IndexTypeQuals*/ 0); 3110 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3111 /*Pascal*/ false, ResTy, Loc); 3112 } else { 3113 ResTy = Context.CharTy.withConst(); 3114 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3115 /*IndexTypeQuals*/ 0); 3116 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3117 /*Pascal*/ false, ResTy, Loc); 3118 } 3119 } 3120 3121 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3122 } 3123 3124 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3125 PredefinedExpr::IdentType IT; 3126 3127 switch (Kind) { 3128 default: llvm_unreachable("Unknown simple primary expr!"); 3129 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3130 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3131 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3132 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3133 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3134 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3135 } 3136 3137 return BuildPredefinedExpr(Loc, IT); 3138 } 3139 3140 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3141 SmallString<16> CharBuffer; 3142 bool Invalid = false; 3143 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3144 if (Invalid) 3145 return ExprError(); 3146 3147 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3148 PP, Tok.getKind()); 3149 if (Literal.hadError()) 3150 return ExprError(); 3151 3152 QualType Ty; 3153 if (Literal.isWide()) 3154 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3155 else if (Literal.isUTF16()) 3156 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3157 else if (Literal.isUTF32()) 3158 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3159 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3160 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3161 else 3162 Ty = Context.CharTy; // 'x' -> char in C++ 3163 3164 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3165 if (Literal.isWide()) 3166 Kind = CharacterLiteral::Wide; 3167 else if (Literal.isUTF16()) 3168 Kind = CharacterLiteral::UTF16; 3169 else if (Literal.isUTF32()) 3170 Kind = CharacterLiteral::UTF32; 3171 else if (Literal.isUTF8()) 3172 Kind = CharacterLiteral::UTF8; 3173 3174 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3175 Tok.getLocation()); 3176 3177 if (Literal.getUDSuffix().empty()) 3178 return Lit; 3179 3180 // We're building a user-defined literal. 3181 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3182 SourceLocation UDSuffixLoc = 3183 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3184 3185 // Make sure we're allowed user-defined literals here. 3186 if (!UDLScope) 3187 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3188 3189 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3190 // operator "" X (ch) 3191 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3192 Lit, Tok.getLocation()); 3193 } 3194 3195 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3196 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3197 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3198 Context.IntTy, Loc); 3199 } 3200 3201 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3202 QualType Ty, SourceLocation Loc) { 3203 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3204 3205 using llvm::APFloat; 3206 APFloat Val(Format); 3207 3208 APFloat::opStatus result = Literal.GetFloatValue(Val); 3209 3210 // Overflow is always an error, but underflow is only an error if 3211 // we underflowed to zero (APFloat reports denormals as underflow). 3212 if ((result & APFloat::opOverflow) || 3213 ((result & APFloat::opUnderflow) && Val.isZero())) { 3214 unsigned diagnostic; 3215 SmallString<20> buffer; 3216 if (result & APFloat::opOverflow) { 3217 diagnostic = diag::warn_float_overflow; 3218 APFloat::getLargest(Format).toString(buffer); 3219 } else { 3220 diagnostic = diag::warn_float_underflow; 3221 APFloat::getSmallest(Format).toString(buffer); 3222 } 3223 3224 S.Diag(Loc, diagnostic) 3225 << Ty 3226 << StringRef(buffer.data(), buffer.size()); 3227 } 3228 3229 bool isExact = (result == APFloat::opOK); 3230 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3231 } 3232 3233 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3234 assert(E && "Invalid expression"); 3235 3236 if (E->isValueDependent()) 3237 return false; 3238 3239 QualType QT = E->getType(); 3240 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3241 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3242 return true; 3243 } 3244 3245 llvm::APSInt ValueAPS; 3246 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3247 3248 if (R.isInvalid()) 3249 return true; 3250 3251 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3252 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3253 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3254 << ValueAPS.toString(10) << ValueIsPositive; 3255 return true; 3256 } 3257 3258 return false; 3259 } 3260 3261 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3262 // Fast path for a single digit (which is quite common). A single digit 3263 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3264 if (Tok.getLength() == 1) { 3265 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3266 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3267 } 3268 3269 SmallString<128> SpellingBuffer; 3270 // NumericLiteralParser wants to overread by one character. Add padding to 3271 // the buffer in case the token is copied to the buffer. If getSpelling() 3272 // returns a StringRef to the memory buffer, it should have a null char at 3273 // the EOF, so it is also safe. 3274 SpellingBuffer.resize(Tok.getLength() + 1); 3275 3276 // Get the spelling of the token, which eliminates trigraphs, etc. 3277 bool Invalid = false; 3278 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3279 if (Invalid) 3280 return ExprError(); 3281 3282 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3283 if (Literal.hadError) 3284 return ExprError(); 3285 3286 if (Literal.hasUDSuffix()) { 3287 // We're building a user-defined literal. 3288 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3289 SourceLocation UDSuffixLoc = 3290 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3291 3292 // Make sure we're allowed user-defined literals here. 3293 if (!UDLScope) 3294 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3295 3296 QualType CookedTy; 3297 if (Literal.isFloatingLiteral()) { 3298 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3299 // long double, the literal is treated as a call of the form 3300 // operator "" X (f L) 3301 CookedTy = Context.LongDoubleTy; 3302 } else { 3303 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3304 // unsigned long long, the literal is treated as a call of the form 3305 // operator "" X (n ULL) 3306 CookedTy = Context.UnsignedLongLongTy; 3307 } 3308 3309 DeclarationName OpName = 3310 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3311 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3312 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3313 3314 SourceLocation TokLoc = Tok.getLocation(); 3315 3316 // Perform literal operator lookup to determine if we're building a raw 3317 // literal or a cooked one. 3318 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3319 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3320 /*AllowRaw*/true, /*AllowTemplate*/true, 3321 /*AllowStringTemplate*/false)) { 3322 case LOLR_Error: 3323 return ExprError(); 3324 3325 case LOLR_Cooked: { 3326 Expr *Lit; 3327 if (Literal.isFloatingLiteral()) { 3328 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3329 } else { 3330 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3331 if (Literal.GetIntegerValue(ResultVal)) 3332 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3333 << /* Unsigned */ 1; 3334 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3335 Tok.getLocation()); 3336 } 3337 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3338 } 3339 3340 case LOLR_Raw: { 3341 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3342 // literal is treated as a call of the form 3343 // operator "" X ("n") 3344 unsigned Length = Literal.getUDSuffixOffset(); 3345 QualType StrTy = Context.getConstantArrayType( 3346 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3347 ArrayType::Normal, 0); 3348 Expr *Lit = StringLiteral::Create( 3349 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3350 /*Pascal*/false, StrTy, &TokLoc, 1); 3351 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3352 } 3353 3354 case LOLR_Template: { 3355 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3356 // template), L is treated as a call fo the form 3357 // operator "" X <'c1', 'c2', ... 'ck'>() 3358 // where n is the source character sequence c1 c2 ... ck. 3359 TemplateArgumentListInfo ExplicitArgs; 3360 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3361 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3362 llvm::APSInt Value(CharBits, CharIsUnsigned); 3363 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3364 Value = TokSpelling[I]; 3365 TemplateArgument Arg(Context, Value, Context.CharTy); 3366 TemplateArgumentLocInfo ArgInfo; 3367 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3368 } 3369 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3370 &ExplicitArgs); 3371 } 3372 case LOLR_StringTemplate: 3373 llvm_unreachable("unexpected literal operator lookup result"); 3374 } 3375 } 3376 3377 Expr *Res; 3378 3379 if (Literal.isFloatingLiteral()) { 3380 QualType Ty; 3381 if (Literal.isHalf){ 3382 if (getOpenCLOptions().cl_khr_fp16) 3383 Ty = Context.HalfTy; 3384 else { 3385 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3386 return ExprError(); 3387 } 3388 } else if (Literal.isFloat) 3389 Ty = Context.FloatTy; 3390 else if (Literal.isLong) 3391 Ty = Context.LongDoubleTy; 3392 else if (Literal.isFloat128) 3393 Ty = Context.Float128Ty; 3394 else 3395 Ty = Context.DoubleTy; 3396 3397 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3398 3399 if (Ty == Context.DoubleTy) { 3400 if (getLangOpts().SinglePrecisionConstants) { 3401 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3402 } else if (getLangOpts().OpenCL && 3403 !((getLangOpts().OpenCLVersion >= 120) || 3404 getOpenCLOptions().cl_khr_fp64)) { 3405 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3406 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3407 } 3408 } 3409 } else if (!Literal.isIntegerLiteral()) { 3410 return ExprError(); 3411 } else { 3412 QualType Ty; 3413 3414 // 'long long' is a C99 or C++11 feature. 3415 if (!getLangOpts().C99 && Literal.isLongLong) { 3416 if (getLangOpts().CPlusPlus) 3417 Diag(Tok.getLocation(), 3418 getLangOpts().CPlusPlus11 ? 3419 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3420 else 3421 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3422 } 3423 3424 // Get the value in the widest-possible width. 3425 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3426 llvm::APInt ResultVal(MaxWidth, 0); 3427 3428 if (Literal.GetIntegerValue(ResultVal)) { 3429 // If this value didn't fit into uintmax_t, error and force to ull. 3430 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3431 << /* Unsigned */ 1; 3432 Ty = Context.UnsignedLongLongTy; 3433 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3434 "long long is not intmax_t?"); 3435 } else { 3436 // If this value fits into a ULL, try to figure out what else it fits into 3437 // according to the rules of C99 6.4.4.1p5. 3438 3439 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3440 // be an unsigned int. 3441 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3442 3443 // Check from smallest to largest, picking the smallest type we can. 3444 unsigned Width = 0; 3445 3446 // Microsoft specific integer suffixes are explicitly sized. 3447 if (Literal.MicrosoftInteger) { 3448 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3449 Width = 8; 3450 Ty = Context.CharTy; 3451 } else { 3452 Width = Literal.MicrosoftInteger; 3453 Ty = Context.getIntTypeForBitwidth(Width, 3454 /*Signed=*/!Literal.isUnsigned); 3455 } 3456 } 3457 3458 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3459 // Are int/unsigned possibilities? 3460 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3461 3462 // Does it fit in a unsigned int? 3463 if (ResultVal.isIntN(IntSize)) { 3464 // Does it fit in a signed int? 3465 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3466 Ty = Context.IntTy; 3467 else if (AllowUnsigned) 3468 Ty = Context.UnsignedIntTy; 3469 Width = IntSize; 3470 } 3471 } 3472 3473 // Are long/unsigned long possibilities? 3474 if (Ty.isNull() && !Literal.isLongLong) { 3475 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3476 3477 // Does it fit in a unsigned long? 3478 if (ResultVal.isIntN(LongSize)) { 3479 // Does it fit in a signed long? 3480 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3481 Ty = Context.LongTy; 3482 else if (AllowUnsigned) 3483 Ty = Context.UnsignedLongTy; 3484 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3485 // is compatible. 3486 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3487 const unsigned LongLongSize = 3488 Context.getTargetInfo().getLongLongWidth(); 3489 Diag(Tok.getLocation(), 3490 getLangOpts().CPlusPlus 3491 ? Literal.isLong 3492 ? diag::warn_old_implicitly_unsigned_long_cxx 3493 : /*C++98 UB*/ diag:: 3494 ext_old_implicitly_unsigned_long_cxx 3495 : diag::warn_old_implicitly_unsigned_long) 3496 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3497 : /*will be ill-formed*/ 1); 3498 Ty = Context.UnsignedLongTy; 3499 } 3500 Width = LongSize; 3501 } 3502 } 3503 3504 // Check long long if needed. 3505 if (Ty.isNull()) { 3506 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3507 3508 // Does it fit in a unsigned long long? 3509 if (ResultVal.isIntN(LongLongSize)) { 3510 // Does it fit in a signed long long? 3511 // To be compatible with MSVC, hex integer literals ending with the 3512 // LL or i64 suffix are always signed in Microsoft mode. 3513 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3514 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3515 Ty = Context.LongLongTy; 3516 else if (AllowUnsigned) 3517 Ty = Context.UnsignedLongLongTy; 3518 Width = LongLongSize; 3519 } 3520 } 3521 3522 // If we still couldn't decide a type, we probably have something that 3523 // does not fit in a signed long long, but has no U suffix. 3524 if (Ty.isNull()) { 3525 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3526 Ty = Context.UnsignedLongLongTy; 3527 Width = Context.getTargetInfo().getLongLongWidth(); 3528 } 3529 3530 if (ResultVal.getBitWidth() != Width) 3531 ResultVal = ResultVal.trunc(Width); 3532 } 3533 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3534 } 3535 3536 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3537 if (Literal.isImaginary) 3538 Res = new (Context) ImaginaryLiteral(Res, 3539 Context.getComplexType(Res->getType())); 3540 3541 return Res; 3542 } 3543 3544 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3545 assert(E && "ActOnParenExpr() missing expr"); 3546 return new (Context) ParenExpr(L, R, E); 3547 } 3548 3549 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3550 SourceLocation Loc, 3551 SourceRange ArgRange) { 3552 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3553 // scalar or vector data type argument..." 3554 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3555 // type (C99 6.2.5p18) or void. 3556 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3557 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3558 << T << ArgRange; 3559 return true; 3560 } 3561 3562 assert((T->isVoidType() || !T->isIncompleteType()) && 3563 "Scalar types should always be complete"); 3564 return false; 3565 } 3566 3567 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3568 SourceLocation Loc, 3569 SourceRange ArgRange, 3570 UnaryExprOrTypeTrait TraitKind) { 3571 // Invalid types must be hard errors for SFINAE in C++. 3572 if (S.LangOpts.CPlusPlus) 3573 return true; 3574 3575 // C99 6.5.3.4p1: 3576 if (T->isFunctionType() && 3577 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3578 // sizeof(function)/alignof(function) is allowed as an extension. 3579 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3580 << TraitKind << ArgRange; 3581 return false; 3582 } 3583 3584 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3585 // this is an error (OpenCL v1.1 s6.3.k) 3586 if (T->isVoidType()) { 3587 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3588 : diag::ext_sizeof_alignof_void_type; 3589 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3590 return false; 3591 } 3592 3593 return true; 3594 } 3595 3596 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3597 SourceLocation Loc, 3598 SourceRange ArgRange, 3599 UnaryExprOrTypeTrait TraitKind) { 3600 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3601 // runtime doesn't allow it. 3602 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3603 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3604 << T << (TraitKind == UETT_SizeOf) 3605 << ArgRange; 3606 return true; 3607 } 3608 3609 return false; 3610 } 3611 3612 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3613 /// pointer type is equal to T) and emit a warning if it is. 3614 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3615 Expr *E) { 3616 // Don't warn if the operation changed the type. 3617 if (T != E->getType()) 3618 return; 3619 3620 // Now look for array decays. 3621 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3622 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3623 return; 3624 3625 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3626 << ICE->getType() 3627 << ICE->getSubExpr()->getType(); 3628 } 3629 3630 /// \brief Check the constraints on expression operands to unary type expression 3631 /// and type traits. 3632 /// 3633 /// Completes any types necessary and validates the constraints on the operand 3634 /// expression. The logic mostly mirrors the type-based overload, but may modify 3635 /// the expression as it completes the type for that expression through template 3636 /// instantiation, etc. 3637 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3638 UnaryExprOrTypeTrait ExprKind) { 3639 QualType ExprTy = E->getType(); 3640 assert(!ExprTy->isReferenceType()); 3641 3642 if (ExprKind == UETT_VecStep) 3643 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3644 E->getSourceRange()); 3645 3646 // Whitelist some types as extensions 3647 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3648 E->getSourceRange(), ExprKind)) 3649 return false; 3650 3651 // 'alignof' applied to an expression only requires the base element type of 3652 // the expression to be complete. 'sizeof' requires the expression's type to 3653 // be complete (and will attempt to complete it if it's an array of unknown 3654 // bound). 3655 if (ExprKind == UETT_AlignOf) { 3656 if (RequireCompleteType(E->getExprLoc(), 3657 Context.getBaseElementType(E->getType()), 3658 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3659 E->getSourceRange())) 3660 return true; 3661 } else { 3662 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3663 ExprKind, E->getSourceRange())) 3664 return true; 3665 } 3666 3667 // Completing the expression's type may have changed it. 3668 ExprTy = E->getType(); 3669 assert(!ExprTy->isReferenceType()); 3670 3671 if (ExprTy->isFunctionType()) { 3672 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3673 << ExprKind << E->getSourceRange(); 3674 return true; 3675 } 3676 3677 // The operand for sizeof and alignof is in an unevaluated expression context, 3678 // so side effects could result in unintended consequences. 3679 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3680 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3681 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3682 3683 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3684 E->getSourceRange(), ExprKind)) 3685 return true; 3686 3687 if (ExprKind == UETT_SizeOf) { 3688 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3689 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3690 QualType OType = PVD->getOriginalType(); 3691 QualType Type = PVD->getType(); 3692 if (Type->isPointerType() && OType->isArrayType()) { 3693 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3694 << Type << OType; 3695 Diag(PVD->getLocation(), diag::note_declared_at); 3696 } 3697 } 3698 } 3699 3700 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3701 // decays into a pointer and returns an unintended result. This is most 3702 // likely a typo for "sizeof(array) op x". 3703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3704 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3705 BO->getLHS()); 3706 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3707 BO->getRHS()); 3708 } 3709 } 3710 3711 return false; 3712 } 3713 3714 /// \brief Check the constraints on operands to unary expression and type 3715 /// traits. 3716 /// 3717 /// This will complete any types necessary, and validate the various constraints 3718 /// on those operands. 3719 /// 3720 /// The UsualUnaryConversions() function is *not* called by this routine. 3721 /// C99 6.3.2.1p[2-4] all state: 3722 /// Except when it is the operand of the sizeof operator ... 3723 /// 3724 /// C++ [expr.sizeof]p4 3725 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3726 /// standard conversions are not applied to the operand of sizeof. 3727 /// 3728 /// This policy is followed for all of the unary trait expressions. 3729 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3730 SourceLocation OpLoc, 3731 SourceRange ExprRange, 3732 UnaryExprOrTypeTrait ExprKind) { 3733 if (ExprType->isDependentType()) 3734 return false; 3735 3736 // C++ [expr.sizeof]p2: 3737 // When applied to a reference or a reference type, the result 3738 // is the size of the referenced type. 3739 // C++11 [expr.alignof]p3: 3740 // When alignof is applied to a reference type, the result 3741 // shall be the alignment of the referenced type. 3742 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3743 ExprType = Ref->getPointeeType(); 3744 3745 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3746 // When alignof or _Alignof is applied to an array type, the result 3747 // is the alignment of the element type. 3748 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3749 ExprType = Context.getBaseElementType(ExprType); 3750 3751 if (ExprKind == UETT_VecStep) 3752 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3753 3754 // Whitelist some types as extensions 3755 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3756 ExprKind)) 3757 return false; 3758 3759 if (RequireCompleteType(OpLoc, ExprType, 3760 diag::err_sizeof_alignof_incomplete_type, 3761 ExprKind, ExprRange)) 3762 return true; 3763 3764 if (ExprType->isFunctionType()) { 3765 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3766 << ExprKind << ExprRange; 3767 return true; 3768 } 3769 3770 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3771 ExprKind)) 3772 return true; 3773 3774 return false; 3775 } 3776 3777 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3778 E = E->IgnoreParens(); 3779 3780 // Cannot know anything else if the expression is dependent. 3781 if (E->isTypeDependent()) 3782 return false; 3783 3784 if (E->getObjectKind() == OK_BitField) { 3785 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3786 << 1 << E->getSourceRange(); 3787 return true; 3788 } 3789 3790 ValueDecl *D = nullptr; 3791 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3792 D = DRE->getDecl(); 3793 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3794 D = ME->getMemberDecl(); 3795 } 3796 3797 // If it's a field, require the containing struct to have a 3798 // complete definition so that we can compute the layout. 3799 // 3800 // This can happen in C++11 onwards, either by naming the member 3801 // in a way that is not transformed into a member access expression 3802 // (in an unevaluated operand, for instance), or by naming the member 3803 // in a trailing-return-type. 3804 // 3805 // For the record, since __alignof__ on expressions is a GCC 3806 // extension, GCC seems to permit this but always gives the 3807 // nonsensical answer 0. 3808 // 3809 // We don't really need the layout here --- we could instead just 3810 // directly check for all the appropriate alignment-lowing 3811 // attributes --- but that would require duplicating a lot of 3812 // logic that just isn't worth duplicating for such a marginal 3813 // use-case. 3814 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3815 // Fast path this check, since we at least know the record has a 3816 // definition if we can find a member of it. 3817 if (!FD->getParent()->isCompleteDefinition()) { 3818 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3819 << E->getSourceRange(); 3820 return true; 3821 } 3822 3823 // Otherwise, if it's a field, and the field doesn't have 3824 // reference type, then it must have a complete type (or be a 3825 // flexible array member, which we explicitly want to 3826 // white-list anyway), which makes the following checks trivial. 3827 if (!FD->getType()->isReferenceType()) 3828 return false; 3829 } 3830 3831 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3832 } 3833 3834 bool Sema::CheckVecStepExpr(Expr *E) { 3835 E = E->IgnoreParens(); 3836 3837 // Cannot know anything else if the expression is dependent. 3838 if (E->isTypeDependent()) 3839 return false; 3840 3841 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3842 } 3843 3844 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3845 CapturingScopeInfo *CSI) { 3846 assert(T->isVariablyModifiedType()); 3847 assert(CSI != nullptr); 3848 3849 // We're going to walk down into the type and look for VLA expressions. 3850 do { 3851 const Type *Ty = T.getTypePtr(); 3852 switch (Ty->getTypeClass()) { 3853 #define TYPE(Class, Base) 3854 #define ABSTRACT_TYPE(Class, Base) 3855 #define NON_CANONICAL_TYPE(Class, Base) 3856 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3857 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3858 #include "clang/AST/TypeNodes.def" 3859 T = QualType(); 3860 break; 3861 // These types are never variably-modified. 3862 case Type::Builtin: 3863 case Type::Complex: 3864 case Type::Vector: 3865 case Type::ExtVector: 3866 case Type::Record: 3867 case Type::Enum: 3868 case Type::Elaborated: 3869 case Type::TemplateSpecialization: 3870 case Type::ObjCObject: 3871 case Type::ObjCInterface: 3872 case Type::ObjCObjectPointer: 3873 case Type::Pipe: 3874 llvm_unreachable("type class is never variably-modified!"); 3875 case Type::Adjusted: 3876 T = cast<AdjustedType>(Ty)->getOriginalType(); 3877 break; 3878 case Type::Decayed: 3879 T = cast<DecayedType>(Ty)->getPointeeType(); 3880 break; 3881 case Type::Pointer: 3882 T = cast<PointerType>(Ty)->getPointeeType(); 3883 break; 3884 case Type::BlockPointer: 3885 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3886 break; 3887 case Type::LValueReference: 3888 case Type::RValueReference: 3889 T = cast<ReferenceType>(Ty)->getPointeeType(); 3890 break; 3891 case Type::MemberPointer: 3892 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3893 break; 3894 case Type::ConstantArray: 3895 case Type::IncompleteArray: 3896 // Losing element qualification here is fine. 3897 T = cast<ArrayType>(Ty)->getElementType(); 3898 break; 3899 case Type::VariableArray: { 3900 // Losing element qualification here is fine. 3901 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3902 3903 // Unknown size indication requires no size computation. 3904 // Otherwise, evaluate and record it. 3905 if (auto Size = VAT->getSizeExpr()) { 3906 if (!CSI->isVLATypeCaptured(VAT)) { 3907 RecordDecl *CapRecord = nullptr; 3908 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3909 CapRecord = LSI->Lambda; 3910 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3911 CapRecord = CRSI->TheRecordDecl; 3912 } 3913 if (CapRecord) { 3914 auto ExprLoc = Size->getExprLoc(); 3915 auto SizeType = Context.getSizeType(); 3916 // Build the non-static data member. 3917 auto Field = 3918 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3919 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3920 /*BW*/ nullptr, /*Mutable*/ false, 3921 /*InitStyle*/ ICIS_NoInit); 3922 Field->setImplicit(true); 3923 Field->setAccess(AS_private); 3924 Field->setCapturedVLAType(VAT); 3925 CapRecord->addDecl(Field); 3926 3927 CSI->addVLATypeCapture(ExprLoc, SizeType); 3928 } 3929 } 3930 } 3931 T = VAT->getElementType(); 3932 break; 3933 } 3934 case Type::FunctionProto: 3935 case Type::FunctionNoProto: 3936 T = cast<FunctionType>(Ty)->getReturnType(); 3937 break; 3938 case Type::Paren: 3939 case Type::TypeOf: 3940 case Type::UnaryTransform: 3941 case Type::Attributed: 3942 case Type::SubstTemplateTypeParm: 3943 case Type::PackExpansion: 3944 // Keep walking after single level desugaring. 3945 T = T.getSingleStepDesugaredType(Context); 3946 break; 3947 case Type::Typedef: 3948 T = cast<TypedefType>(Ty)->desugar(); 3949 break; 3950 case Type::Decltype: 3951 T = cast<DecltypeType>(Ty)->desugar(); 3952 break; 3953 case Type::Auto: 3954 T = cast<AutoType>(Ty)->getDeducedType(); 3955 break; 3956 case Type::TypeOfExpr: 3957 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3958 break; 3959 case Type::Atomic: 3960 T = cast<AtomicType>(Ty)->getValueType(); 3961 break; 3962 } 3963 } while (!T.isNull() && T->isVariablyModifiedType()); 3964 } 3965 3966 /// \brief Build a sizeof or alignof expression given a type operand. 3967 ExprResult 3968 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3969 SourceLocation OpLoc, 3970 UnaryExprOrTypeTrait ExprKind, 3971 SourceRange R) { 3972 if (!TInfo) 3973 return ExprError(); 3974 3975 QualType T = TInfo->getType(); 3976 3977 if (!T->isDependentType() && 3978 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3979 return ExprError(); 3980 3981 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3982 if (auto *TT = T->getAs<TypedefType>()) { 3983 for (auto I = FunctionScopes.rbegin(), 3984 E = std::prev(FunctionScopes.rend()); 3985 I != E; ++I) { 3986 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3987 if (CSI == nullptr) 3988 break; 3989 DeclContext *DC = nullptr; 3990 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3991 DC = LSI->CallOperator; 3992 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3993 DC = CRSI->TheCapturedDecl; 3994 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3995 DC = BSI->TheDecl; 3996 if (DC) { 3997 if (DC->containsDecl(TT->getDecl())) 3998 break; 3999 captureVariablyModifiedType(Context, T, CSI); 4000 } 4001 } 4002 } 4003 } 4004 4005 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4006 return new (Context) UnaryExprOrTypeTraitExpr( 4007 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4008 } 4009 4010 /// \brief Build a sizeof or alignof expression given an expression 4011 /// operand. 4012 ExprResult 4013 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4014 UnaryExprOrTypeTrait ExprKind) { 4015 ExprResult PE = CheckPlaceholderExpr(E); 4016 if (PE.isInvalid()) 4017 return ExprError(); 4018 4019 E = PE.get(); 4020 4021 // Verify that the operand is valid. 4022 bool isInvalid = false; 4023 if (E->isTypeDependent()) { 4024 // Delay type-checking for type-dependent expressions. 4025 } else if (ExprKind == UETT_AlignOf) { 4026 isInvalid = CheckAlignOfExpr(*this, E); 4027 } else if (ExprKind == UETT_VecStep) { 4028 isInvalid = CheckVecStepExpr(E); 4029 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4030 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4031 isInvalid = true; 4032 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4033 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4034 isInvalid = true; 4035 } else { 4036 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4037 } 4038 4039 if (isInvalid) 4040 return ExprError(); 4041 4042 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4043 PE = TransformToPotentiallyEvaluated(E); 4044 if (PE.isInvalid()) return ExprError(); 4045 E = PE.get(); 4046 } 4047 4048 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4049 return new (Context) UnaryExprOrTypeTraitExpr( 4050 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4051 } 4052 4053 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4054 /// expr and the same for @c alignof and @c __alignof 4055 /// Note that the ArgRange is invalid if isType is false. 4056 ExprResult 4057 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4058 UnaryExprOrTypeTrait ExprKind, bool IsType, 4059 void *TyOrEx, SourceRange ArgRange) { 4060 // If error parsing type, ignore. 4061 if (!TyOrEx) return ExprError(); 4062 4063 if (IsType) { 4064 TypeSourceInfo *TInfo; 4065 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4066 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4067 } 4068 4069 Expr *ArgEx = (Expr *)TyOrEx; 4070 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4071 return Result; 4072 } 4073 4074 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4075 bool IsReal) { 4076 if (V.get()->isTypeDependent()) 4077 return S.Context.DependentTy; 4078 4079 // _Real and _Imag are only l-values for normal l-values. 4080 if (V.get()->getObjectKind() != OK_Ordinary) { 4081 V = S.DefaultLvalueConversion(V.get()); 4082 if (V.isInvalid()) 4083 return QualType(); 4084 } 4085 4086 // These operators return the element type of a complex type. 4087 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4088 return CT->getElementType(); 4089 4090 // Otherwise they pass through real integer and floating point types here. 4091 if (V.get()->getType()->isArithmeticType()) 4092 return V.get()->getType(); 4093 4094 // Test for placeholders. 4095 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4096 if (PR.isInvalid()) return QualType(); 4097 if (PR.get() != V.get()) { 4098 V = PR; 4099 return CheckRealImagOperand(S, V, Loc, IsReal); 4100 } 4101 4102 // Reject anything else. 4103 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4104 << (IsReal ? "__real" : "__imag"); 4105 return QualType(); 4106 } 4107 4108 4109 4110 ExprResult 4111 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4112 tok::TokenKind Kind, Expr *Input) { 4113 UnaryOperatorKind Opc; 4114 switch (Kind) { 4115 default: llvm_unreachable("Unknown unary op!"); 4116 case tok::plusplus: Opc = UO_PostInc; break; 4117 case tok::minusminus: Opc = UO_PostDec; break; 4118 } 4119 4120 // Since this might is a postfix expression, get rid of ParenListExprs. 4121 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4122 if (Result.isInvalid()) return ExprError(); 4123 Input = Result.get(); 4124 4125 return BuildUnaryOp(S, OpLoc, Opc, Input); 4126 } 4127 4128 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4129 /// 4130 /// \return true on error 4131 static bool checkArithmeticOnObjCPointer(Sema &S, 4132 SourceLocation opLoc, 4133 Expr *op) { 4134 assert(op->getType()->isObjCObjectPointerType()); 4135 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4136 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4137 return false; 4138 4139 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4140 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4141 << op->getSourceRange(); 4142 return true; 4143 } 4144 4145 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4146 auto *BaseNoParens = Base->IgnoreParens(); 4147 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4148 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4149 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4150 } 4151 4152 ExprResult 4153 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4154 Expr *idx, SourceLocation rbLoc) { 4155 if (base && !base->getType().isNull() && 4156 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4157 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4158 /*Length=*/nullptr, rbLoc); 4159 4160 // Since this might be a postfix expression, get rid of ParenListExprs. 4161 if (isa<ParenListExpr>(base)) { 4162 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4163 if (result.isInvalid()) return ExprError(); 4164 base = result.get(); 4165 } 4166 4167 // Handle any non-overload placeholder types in the base and index 4168 // expressions. We can't handle overloads here because the other 4169 // operand might be an overloadable type, in which case the overload 4170 // resolution for the operator overload should get the first crack 4171 // at the overload. 4172 bool IsMSPropertySubscript = false; 4173 if (base->getType()->isNonOverloadPlaceholderType()) { 4174 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4175 if (!IsMSPropertySubscript) { 4176 ExprResult result = CheckPlaceholderExpr(base); 4177 if (result.isInvalid()) 4178 return ExprError(); 4179 base = result.get(); 4180 } 4181 } 4182 if (idx->getType()->isNonOverloadPlaceholderType()) { 4183 ExprResult result = CheckPlaceholderExpr(idx); 4184 if (result.isInvalid()) return ExprError(); 4185 idx = result.get(); 4186 } 4187 4188 // Build an unanalyzed expression if either operand is type-dependent. 4189 if (getLangOpts().CPlusPlus && 4190 (base->isTypeDependent() || idx->isTypeDependent())) { 4191 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4192 VK_LValue, OK_Ordinary, rbLoc); 4193 } 4194 4195 // MSDN, property (C++) 4196 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4197 // This attribute can also be used in the declaration of an empty array in a 4198 // class or structure definition. For example: 4199 // __declspec(property(get=GetX, put=PutX)) int x[]; 4200 // The above statement indicates that x[] can be used with one or more array 4201 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4202 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4203 if (IsMSPropertySubscript) { 4204 // Build MS property subscript expression if base is MS property reference 4205 // or MS property subscript. 4206 return new (Context) MSPropertySubscriptExpr( 4207 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4208 } 4209 4210 // Use C++ overloaded-operator rules if either operand has record 4211 // type. The spec says to do this if either type is *overloadable*, 4212 // but enum types can't declare subscript operators or conversion 4213 // operators, so there's nothing interesting for overload resolution 4214 // to do if there aren't any record types involved. 4215 // 4216 // ObjC pointers have their own subscripting logic that is not tied 4217 // to overload resolution and so should not take this path. 4218 if (getLangOpts().CPlusPlus && 4219 (base->getType()->isRecordType() || 4220 (!base->getType()->isObjCObjectPointerType() && 4221 idx->getType()->isRecordType()))) { 4222 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4223 } 4224 4225 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4226 } 4227 4228 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4229 Expr *LowerBound, 4230 SourceLocation ColonLoc, Expr *Length, 4231 SourceLocation RBLoc) { 4232 if (Base->getType()->isPlaceholderType() && 4233 !Base->getType()->isSpecificPlaceholderType( 4234 BuiltinType::OMPArraySection)) { 4235 ExprResult Result = CheckPlaceholderExpr(Base); 4236 if (Result.isInvalid()) 4237 return ExprError(); 4238 Base = Result.get(); 4239 } 4240 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4241 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4242 if (Result.isInvalid()) 4243 return ExprError(); 4244 Result = DefaultLvalueConversion(Result.get()); 4245 if (Result.isInvalid()) 4246 return ExprError(); 4247 LowerBound = Result.get(); 4248 } 4249 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4250 ExprResult Result = CheckPlaceholderExpr(Length); 4251 if (Result.isInvalid()) 4252 return ExprError(); 4253 Result = DefaultLvalueConversion(Result.get()); 4254 if (Result.isInvalid()) 4255 return ExprError(); 4256 Length = Result.get(); 4257 } 4258 4259 // Build an unanalyzed expression if either operand is type-dependent. 4260 if (Base->isTypeDependent() || 4261 (LowerBound && 4262 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4263 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4264 return new (Context) 4265 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4266 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4267 } 4268 4269 // Perform default conversions. 4270 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4271 QualType ResultTy; 4272 if (OriginalTy->isAnyPointerType()) { 4273 ResultTy = OriginalTy->getPointeeType(); 4274 } else if (OriginalTy->isArrayType()) { 4275 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4276 } else { 4277 return ExprError( 4278 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4279 << Base->getSourceRange()); 4280 } 4281 // C99 6.5.2.1p1 4282 if (LowerBound) { 4283 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4284 LowerBound); 4285 if (Res.isInvalid()) 4286 return ExprError(Diag(LowerBound->getExprLoc(), 4287 diag::err_omp_typecheck_section_not_integer) 4288 << 0 << LowerBound->getSourceRange()); 4289 LowerBound = Res.get(); 4290 4291 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4292 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4293 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4294 << 0 << LowerBound->getSourceRange(); 4295 } 4296 if (Length) { 4297 auto Res = 4298 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4299 if (Res.isInvalid()) 4300 return ExprError(Diag(Length->getExprLoc(), 4301 diag::err_omp_typecheck_section_not_integer) 4302 << 1 << Length->getSourceRange()); 4303 Length = Res.get(); 4304 4305 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4306 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4307 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4308 << 1 << Length->getSourceRange(); 4309 } 4310 4311 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4312 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4313 // type. Note that functions are not objects, and that (in C99 parlance) 4314 // incomplete types are not object types. 4315 if (ResultTy->isFunctionType()) { 4316 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4317 << ResultTy << Base->getSourceRange(); 4318 return ExprError(); 4319 } 4320 4321 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4322 diag::err_omp_section_incomplete_type, Base)) 4323 return ExprError(); 4324 4325 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4326 llvm::APSInt LowerBoundValue; 4327 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4328 // OpenMP 4.5, [2.4 Array Sections] 4329 // The array section must be a subset of the original array. 4330 if (LowerBoundValue.isNegative()) { 4331 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4332 << LowerBound->getSourceRange(); 4333 return ExprError(); 4334 } 4335 } 4336 } 4337 4338 if (Length) { 4339 llvm::APSInt LengthValue; 4340 if (Length->EvaluateAsInt(LengthValue, Context)) { 4341 // OpenMP 4.5, [2.4 Array Sections] 4342 // The length must evaluate to non-negative integers. 4343 if (LengthValue.isNegative()) { 4344 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4345 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4346 << Length->getSourceRange(); 4347 return ExprError(); 4348 } 4349 } 4350 } else if (ColonLoc.isValid() && 4351 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4352 !OriginalTy->isVariableArrayType()))) { 4353 // OpenMP 4.5, [2.4 Array Sections] 4354 // When the size of the array dimension is not known, the length must be 4355 // specified explicitly. 4356 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4357 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4358 return ExprError(); 4359 } 4360 4361 if (!Base->getType()->isSpecificPlaceholderType( 4362 BuiltinType::OMPArraySection)) { 4363 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4364 if (Result.isInvalid()) 4365 return ExprError(); 4366 Base = Result.get(); 4367 } 4368 return new (Context) 4369 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4370 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4371 } 4372 4373 ExprResult 4374 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4375 Expr *Idx, SourceLocation RLoc) { 4376 Expr *LHSExp = Base; 4377 Expr *RHSExp = Idx; 4378 4379 // Perform default conversions. 4380 if (!LHSExp->getType()->getAs<VectorType>()) { 4381 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4382 if (Result.isInvalid()) 4383 return ExprError(); 4384 LHSExp = Result.get(); 4385 } 4386 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4387 if (Result.isInvalid()) 4388 return ExprError(); 4389 RHSExp = Result.get(); 4390 4391 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4392 ExprValueKind VK = VK_LValue; 4393 ExprObjectKind OK = OK_Ordinary; 4394 4395 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4396 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4397 // in the subscript position. As a result, we need to derive the array base 4398 // and index from the expression types. 4399 Expr *BaseExpr, *IndexExpr; 4400 QualType ResultType; 4401 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4402 BaseExpr = LHSExp; 4403 IndexExpr = RHSExp; 4404 ResultType = Context.DependentTy; 4405 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4406 BaseExpr = LHSExp; 4407 IndexExpr = RHSExp; 4408 ResultType = PTy->getPointeeType(); 4409 } else if (const ObjCObjectPointerType *PTy = 4410 LHSTy->getAs<ObjCObjectPointerType>()) { 4411 BaseExpr = LHSExp; 4412 IndexExpr = RHSExp; 4413 4414 // Use custom logic if this should be the pseudo-object subscript 4415 // expression. 4416 if (!LangOpts.isSubscriptPointerArithmetic()) 4417 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4418 nullptr); 4419 4420 ResultType = PTy->getPointeeType(); 4421 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4422 // Handle the uncommon case of "123[Ptr]". 4423 BaseExpr = RHSExp; 4424 IndexExpr = LHSExp; 4425 ResultType = PTy->getPointeeType(); 4426 } else if (const ObjCObjectPointerType *PTy = 4427 RHSTy->getAs<ObjCObjectPointerType>()) { 4428 // Handle the uncommon case of "123[Ptr]". 4429 BaseExpr = RHSExp; 4430 IndexExpr = LHSExp; 4431 ResultType = PTy->getPointeeType(); 4432 if (!LangOpts.isSubscriptPointerArithmetic()) { 4433 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4434 << ResultType << BaseExpr->getSourceRange(); 4435 return ExprError(); 4436 } 4437 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4438 BaseExpr = LHSExp; // vectors: V[123] 4439 IndexExpr = RHSExp; 4440 VK = LHSExp->getValueKind(); 4441 if (VK != VK_RValue) 4442 OK = OK_VectorComponent; 4443 4444 // FIXME: need to deal with const... 4445 ResultType = VTy->getElementType(); 4446 } else if (LHSTy->isArrayType()) { 4447 // If we see an array that wasn't promoted by 4448 // DefaultFunctionArrayLvalueConversion, it must be an array that 4449 // wasn't promoted because of the C90 rule that doesn't 4450 // allow promoting non-lvalue arrays. Warn, then 4451 // force the promotion here. 4452 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4453 LHSExp->getSourceRange(); 4454 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4455 CK_ArrayToPointerDecay).get(); 4456 LHSTy = LHSExp->getType(); 4457 4458 BaseExpr = LHSExp; 4459 IndexExpr = RHSExp; 4460 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4461 } else if (RHSTy->isArrayType()) { 4462 // Same as previous, except for 123[f().a] case 4463 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4464 RHSExp->getSourceRange(); 4465 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4466 CK_ArrayToPointerDecay).get(); 4467 RHSTy = RHSExp->getType(); 4468 4469 BaseExpr = RHSExp; 4470 IndexExpr = LHSExp; 4471 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4472 } else { 4473 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4474 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4475 } 4476 // C99 6.5.2.1p1 4477 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4478 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4479 << IndexExpr->getSourceRange()); 4480 4481 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4482 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4483 && !IndexExpr->isTypeDependent()) 4484 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4485 4486 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4487 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4488 // type. Note that Functions are not objects, and that (in C99 parlance) 4489 // incomplete types are not object types. 4490 if (ResultType->isFunctionType()) { 4491 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4492 << ResultType << BaseExpr->getSourceRange(); 4493 return ExprError(); 4494 } 4495 4496 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4497 // GNU extension: subscripting on pointer to void 4498 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4499 << BaseExpr->getSourceRange(); 4500 4501 // C forbids expressions of unqualified void type from being l-values. 4502 // See IsCForbiddenLValueType. 4503 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4504 } else if (!ResultType->isDependentType() && 4505 RequireCompleteType(LLoc, ResultType, 4506 diag::err_subscript_incomplete_type, BaseExpr)) 4507 return ExprError(); 4508 4509 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4510 !ResultType.isCForbiddenLValueType()); 4511 4512 return new (Context) 4513 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4514 } 4515 4516 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4517 FunctionDecl *FD, 4518 ParmVarDecl *Param) { 4519 if (Param->hasUnparsedDefaultArg()) { 4520 Diag(CallLoc, 4521 diag::err_use_of_default_argument_to_function_declared_later) << 4522 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4523 Diag(UnparsedDefaultArgLocs[Param], 4524 diag::note_default_argument_declared_here); 4525 return ExprError(); 4526 } 4527 4528 if (Param->hasUninstantiatedDefaultArg()) { 4529 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4530 4531 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4532 Param); 4533 4534 // Instantiate the expression. 4535 MultiLevelTemplateArgumentList MutiLevelArgList 4536 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4537 4538 InstantiatingTemplate Inst(*this, CallLoc, Param, 4539 MutiLevelArgList.getInnermost()); 4540 if (Inst.isInvalid()) 4541 return ExprError(); 4542 4543 ExprResult Result; 4544 { 4545 // C++ [dcl.fct.default]p5: 4546 // The names in the [default argument] expression are bound, and 4547 // the semantic constraints are checked, at the point where the 4548 // default argument expression appears. 4549 ContextRAII SavedContext(*this, FD); 4550 LocalInstantiationScope Local(*this); 4551 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4552 } 4553 if (Result.isInvalid()) 4554 return ExprError(); 4555 4556 // Check the expression as an initializer for the parameter. 4557 InitializedEntity Entity 4558 = InitializedEntity::InitializeParameter(Context, Param); 4559 InitializationKind Kind 4560 = InitializationKind::CreateCopy(Param->getLocation(), 4561 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4562 Expr *ResultE = Result.getAs<Expr>(); 4563 4564 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4565 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4566 if (Result.isInvalid()) 4567 return ExprError(); 4568 4569 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4570 Param->getOuterLocStart()); 4571 if (Result.isInvalid()) 4572 return ExprError(); 4573 4574 // Remember the instantiated default argument. 4575 Param->setDefaultArg(Result.getAs<Expr>()); 4576 if (ASTMutationListener *L = getASTMutationListener()) { 4577 L->DefaultArgumentInstantiated(Param); 4578 } 4579 } 4580 4581 // If the default argument expression is not set yet, we are building it now. 4582 if (!Param->hasInit()) { 4583 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4584 Param->setInvalidDecl(); 4585 return ExprError(); 4586 } 4587 4588 // If the default expression creates temporaries, we need to 4589 // push them to the current stack of expression temporaries so they'll 4590 // be properly destroyed. 4591 // FIXME: We should really be rebuilding the default argument with new 4592 // bound temporaries; see the comment in PR5810. 4593 // We don't need to do that with block decls, though, because 4594 // blocks in default argument expression can never capture anything. 4595 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4596 // Set the "needs cleanups" bit regardless of whether there are 4597 // any explicit objects. 4598 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4599 4600 // Append all the objects to the cleanup list. Right now, this 4601 // should always be a no-op, because blocks in default argument 4602 // expressions should never be able to capture anything. 4603 assert(!Init->getNumObjects() && 4604 "default argument expression has capturing blocks?"); 4605 } 4606 4607 // We already type-checked the argument, so we know it works. 4608 // Just mark all of the declarations in this potentially-evaluated expression 4609 // as being "referenced". 4610 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4611 /*SkipLocalVariables=*/true); 4612 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4613 } 4614 4615 4616 Sema::VariadicCallType 4617 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4618 Expr *Fn) { 4619 if (Proto && Proto->isVariadic()) { 4620 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4621 return VariadicConstructor; 4622 else if (Fn && Fn->getType()->isBlockPointerType()) 4623 return VariadicBlock; 4624 else if (FDecl) { 4625 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4626 if (Method->isInstance()) 4627 return VariadicMethod; 4628 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4629 return VariadicMethod; 4630 return VariadicFunction; 4631 } 4632 return VariadicDoesNotApply; 4633 } 4634 4635 namespace { 4636 class FunctionCallCCC : public FunctionCallFilterCCC { 4637 public: 4638 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4639 unsigned NumArgs, MemberExpr *ME) 4640 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4641 FunctionName(FuncName) {} 4642 4643 bool ValidateCandidate(const TypoCorrection &candidate) override { 4644 if (!candidate.getCorrectionSpecifier() || 4645 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4646 return false; 4647 } 4648 4649 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4650 } 4651 4652 private: 4653 const IdentifierInfo *const FunctionName; 4654 }; 4655 } 4656 4657 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4658 FunctionDecl *FDecl, 4659 ArrayRef<Expr *> Args) { 4660 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4661 DeclarationName FuncName = FDecl->getDeclName(); 4662 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4663 4664 if (TypoCorrection Corrected = S.CorrectTypo( 4665 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4666 S.getScopeForContext(S.CurContext), nullptr, 4667 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4668 Args.size(), ME), 4669 Sema::CTK_ErrorRecovery)) { 4670 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4671 if (Corrected.isOverloaded()) { 4672 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4673 OverloadCandidateSet::iterator Best; 4674 for (NamedDecl *CD : Corrected) { 4675 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4676 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4677 OCS); 4678 } 4679 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4680 case OR_Success: 4681 ND = Best->FoundDecl; 4682 Corrected.setCorrectionDecl(ND); 4683 break; 4684 default: 4685 break; 4686 } 4687 } 4688 ND = ND->getUnderlyingDecl(); 4689 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4690 return Corrected; 4691 } 4692 } 4693 return TypoCorrection(); 4694 } 4695 4696 /// ConvertArgumentsForCall - Converts the arguments specified in 4697 /// Args/NumArgs to the parameter types of the function FDecl with 4698 /// function prototype Proto. Call is the call expression itself, and 4699 /// Fn is the function expression. For a C++ member function, this 4700 /// routine does not attempt to convert the object argument. Returns 4701 /// true if the call is ill-formed. 4702 bool 4703 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4704 FunctionDecl *FDecl, 4705 const FunctionProtoType *Proto, 4706 ArrayRef<Expr *> Args, 4707 SourceLocation RParenLoc, 4708 bool IsExecConfig) { 4709 // Bail out early if calling a builtin with custom typechecking. 4710 if (FDecl) 4711 if (unsigned ID = FDecl->getBuiltinID()) 4712 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4713 return false; 4714 4715 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4716 // assignment, to the types of the corresponding parameter, ... 4717 unsigned NumParams = Proto->getNumParams(); 4718 bool Invalid = false; 4719 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4720 unsigned FnKind = Fn->getType()->isBlockPointerType() 4721 ? 1 /* block */ 4722 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4723 : 0 /* function */); 4724 4725 // If too few arguments are available (and we don't have default 4726 // arguments for the remaining parameters), don't make the call. 4727 if (Args.size() < NumParams) { 4728 if (Args.size() < MinArgs) { 4729 TypoCorrection TC; 4730 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4731 unsigned diag_id = 4732 MinArgs == NumParams && !Proto->isVariadic() 4733 ? diag::err_typecheck_call_too_few_args_suggest 4734 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4735 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4736 << static_cast<unsigned>(Args.size()) 4737 << TC.getCorrectionRange()); 4738 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4739 Diag(RParenLoc, 4740 MinArgs == NumParams && !Proto->isVariadic() 4741 ? diag::err_typecheck_call_too_few_args_one 4742 : diag::err_typecheck_call_too_few_args_at_least_one) 4743 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4744 else 4745 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4746 ? diag::err_typecheck_call_too_few_args 4747 : diag::err_typecheck_call_too_few_args_at_least) 4748 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4749 << Fn->getSourceRange(); 4750 4751 // Emit the location of the prototype. 4752 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4753 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4754 << FDecl; 4755 4756 return true; 4757 } 4758 Call->setNumArgs(Context, NumParams); 4759 } 4760 4761 // If too many are passed and not variadic, error on the extras and drop 4762 // them. 4763 if (Args.size() > NumParams) { 4764 if (!Proto->isVariadic()) { 4765 TypoCorrection TC; 4766 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4767 unsigned diag_id = 4768 MinArgs == NumParams && !Proto->isVariadic() 4769 ? diag::err_typecheck_call_too_many_args_suggest 4770 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4771 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4772 << static_cast<unsigned>(Args.size()) 4773 << TC.getCorrectionRange()); 4774 } else if (NumParams == 1 && FDecl && 4775 FDecl->getParamDecl(0)->getDeclName()) 4776 Diag(Args[NumParams]->getLocStart(), 4777 MinArgs == NumParams 4778 ? diag::err_typecheck_call_too_many_args_one 4779 : diag::err_typecheck_call_too_many_args_at_most_one) 4780 << FnKind << FDecl->getParamDecl(0) 4781 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4782 << SourceRange(Args[NumParams]->getLocStart(), 4783 Args.back()->getLocEnd()); 4784 else 4785 Diag(Args[NumParams]->getLocStart(), 4786 MinArgs == NumParams 4787 ? diag::err_typecheck_call_too_many_args 4788 : diag::err_typecheck_call_too_many_args_at_most) 4789 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4790 << Fn->getSourceRange() 4791 << SourceRange(Args[NumParams]->getLocStart(), 4792 Args.back()->getLocEnd()); 4793 4794 // Emit the location of the prototype. 4795 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4796 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4797 << FDecl; 4798 4799 // This deletes the extra arguments. 4800 Call->setNumArgs(Context, NumParams); 4801 return true; 4802 } 4803 } 4804 SmallVector<Expr *, 8> AllArgs; 4805 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4806 4807 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4808 Proto, 0, Args, AllArgs, CallType); 4809 if (Invalid) 4810 return true; 4811 unsigned TotalNumArgs = AllArgs.size(); 4812 for (unsigned i = 0; i < TotalNumArgs; ++i) 4813 Call->setArg(i, AllArgs[i]); 4814 4815 return false; 4816 } 4817 4818 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4819 const FunctionProtoType *Proto, 4820 unsigned FirstParam, ArrayRef<Expr *> Args, 4821 SmallVectorImpl<Expr *> &AllArgs, 4822 VariadicCallType CallType, bool AllowExplicit, 4823 bool IsListInitialization) { 4824 unsigned NumParams = Proto->getNumParams(); 4825 bool Invalid = false; 4826 size_t ArgIx = 0; 4827 // Continue to check argument types (even if we have too few/many args). 4828 for (unsigned i = FirstParam; i < NumParams; i++) { 4829 QualType ProtoArgType = Proto->getParamType(i); 4830 4831 Expr *Arg; 4832 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4833 if (ArgIx < Args.size()) { 4834 Arg = Args[ArgIx++]; 4835 4836 if (RequireCompleteType(Arg->getLocStart(), 4837 ProtoArgType, 4838 diag::err_call_incomplete_argument, Arg)) 4839 return true; 4840 4841 // Strip the unbridged-cast placeholder expression off, if applicable. 4842 bool CFAudited = false; 4843 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4844 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4845 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4846 Arg = stripARCUnbridgedCast(Arg); 4847 else if (getLangOpts().ObjCAutoRefCount && 4848 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4849 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4850 CFAudited = true; 4851 4852 InitializedEntity Entity = 4853 Param ? InitializedEntity::InitializeParameter(Context, Param, 4854 ProtoArgType) 4855 : InitializedEntity::InitializeParameter( 4856 Context, ProtoArgType, Proto->isParamConsumed(i)); 4857 4858 // Remember that parameter belongs to a CF audited API. 4859 if (CFAudited) 4860 Entity.setParameterCFAudited(); 4861 4862 ExprResult ArgE = PerformCopyInitialization( 4863 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4864 if (ArgE.isInvalid()) 4865 return true; 4866 4867 Arg = ArgE.getAs<Expr>(); 4868 } else { 4869 assert(Param && "can't use default arguments without a known callee"); 4870 4871 ExprResult ArgExpr = 4872 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4873 if (ArgExpr.isInvalid()) 4874 return true; 4875 4876 Arg = ArgExpr.getAs<Expr>(); 4877 } 4878 4879 // Check for array bounds violations for each argument to the call. This 4880 // check only triggers warnings when the argument isn't a more complex Expr 4881 // with its own checking, such as a BinaryOperator. 4882 CheckArrayAccess(Arg); 4883 4884 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4885 CheckStaticArrayArgument(CallLoc, Param, Arg); 4886 4887 AllArgs.push_back(Arg); 4888 } 4889 4890 // If this is a variadic call, handle args passed through "...". 4891 if (CallType != VariadicDoesNotApply) { 4892 // Assume that extern "C" functions with variadic arguments that 4893 // return __unknown_anytype aren't *really* variadic. 4894 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4895 FDecl->isExternC()) { 4896 for (Expr *A : Args.slice(ArgIx)) { 4897 QualType paramType; // ignored 4898 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4899 Invalid |= arg.isInvalid(); 4900 AllArgs.push_back(arg.get()); 4901 } 4902 4903 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4904 } else { 4905 for (Expr *A : Args.slice(ArgIx)) { 4906 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4907 Invalid |= Arg.isInvalid(); 4908 AllArgs.push_back(Arg.get()); 4909 } 4910 } 4911 4912 // Check for array bounds violations. 4913 for (Expr *A : Args.slice(ArgIx)) 4914 CheckArrayAccess(A); 4915 } 4916 return Invalid; 4917 } 4918 4919 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4920 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4921 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4922 TL = DTL.getOriginalLoc(); 4923 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4924 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4925 << ATL.getLocalSourceRange(); 4926 } 4927 4928 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4929 /// array parameter, check that it is non-null, and that if it is formed by 4930 /// array-to-pointer decay, the underlying array is sufficiently large. 4931 /// 4932 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4933 /// array type derivation, then for each call to the function, the value of the 4934 /// corresponding actual argument shall provide access to the first element of 4935 /// an array with at least as many elements as specified by the size expression. 4936 void 4937 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4938 ParmVarDecl *Param, 4939 const Expr *ArgExpr) { 4940 // Static array parameters are not supported in C++. 4941 if (!Param || getLangOpts().CPlusPlus) 4942 return; 4943 4944 QualType OrigTy = Param->getOriginalType(); 4945 4946 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4947 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4948 return; 4949 4950 if (ArgExpr->isNullPointerConstant(Context, 4951 Expr::NPC_NeverValueDependent)) { 4952 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4953 DiagnoseCalleeStaticArrayParam(*this, Param); 4954 return; 4955 } 4956 4957 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4958 if (!CAT) 4959 return; 4960 4961 const ConstantArrayType *ArgCAT = 4962 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4963 if (!ArgCAT) 4964 return; 4965 4966 if (ArgCAT->getSize().ult(CAT->getSize())) { 4967 Diag(CallLoc, diag::warn_static_array_too_small) 4968 << ArgExpr->getSourceRange() 4969 << (unsigned) ArgCAT->getSize().getZExtValue() 4970 << (unsigned) CAT->getSize().getZExtValue(); 4971 DiagnoseCalleeStaticArrayParam(*this, Param); 4972 } 4973 } 4974 4975 /// Given a function expression of unknown-any type, try to rebuild it 4976 /// to have a function type. 4977 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4978 4979 /// Is the given type a placeholder that we need to lower out 4980 /// immediately during argument processing? 4981 static bool isPlaceholderToRemoveAsArg(QualType type) { 4982 // Placeholders are never sugared. 4983 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4984 if (!placeholder) return false; 4985 4986 switch (placeholder->getKind()) { 4987 // Ignore all the non-placeholder types. 4988 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4989 case BuiltinType::Id: 4990 #include "clang/Basic/OpenCLImageTypes.def" 4991 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4992 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4993 #include "clang/AST/BuiltinTypes.def" 4994 return false; 4995 4996 // We cannot lower out overload sets; they might validly be resolved 4997 // by the call machinery. 4998 case BuiltinType::Overload: 4999 return false; 5000 5001 // Unbridged casts in ARC can be handled in some call positions and 5002 // should be left in place. 5003 case BuiltinType::ARCUnbridgedCast: 5004 return false; 5005 5006 // Pseudo-objects should be converted as soon as possible. 5007 case BuiltinType::PseudoObject: 5008 return true; 5009 5010 // The debugger mode could theoretically but currently does not try 5011 // to resolve unknown-typed arguments based on known parameter types. 5012 case BuiltinType::UnknownAny: 5013 return true; 5014 5015 // These are always invalid as call arguments and should be reported. 5016 case BuiltinType::BoundMember: 5017 case BuiltinType::BuiltinFn: 5018 case BuiltinType::OMPArraySection: 5019 return true; 5020 5021 } 5022 llvm_unreachable("bad builtin type kind"); 5023 } 5024 5025 /// Check an argument list for placeholders that we won't try to 5026 /// handle later. 5027 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5028 // Apply this processing to all the arguments at once instead of 5029 // dying at the first failure. 5030 bool hasInvalid = false; 5031 for (size_t i = 0, e = args.size(); i != e; i++) { 5032 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5033 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5034 if (result.isInvalid()) hasInvalid = true; 5035 else args[i] = result.get(); 5036 } else if (hasInvalid) { 5037 (void)S.CorrectDelayedTyposInExpr(args[i]); 5038 } 5039 } 5040 return hasInvalid; 5041 } 5042 5043 /// If a builtin function has a pointer argument with no explicit address 5044 /// space, then it should be able to accept a pointer to any address 5045 /// space as input. In order to do this, we need to replace the 5046 /// standard builtin declaration with one that uses the same address space 5047 /// as the call. 5048 /// 5049 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5050 /// it does not contain any pointer arguments without 5051 /// an address space qualifer. Otherwise the rewritten 5052 /// FunctionDecl is returned. 5053 /// TODO: Handle pointer return types. 5054 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5055 const FunctionDecl *FDecl, 5056 MultiExprArg ArgExprs) { 5057 5058 QualType DeclType = FDecl->getType(); 5059 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5060 5061 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5062 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5063 return nullptr; 5064 5065 bool NeedsNewDecl = false; 5066 unsigned i = 0; 5067 SmallVector<QualType, 8> OverloadParams; 5068 5069 for (QualType ParamType : FT->param_types()) { 5070 5071 // Convert array arguments to pointer to simplify type lookup. 5072 ExprResult ArgRes = 5073 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5074 if (ArgRes.isInvalid()) 5075 return nullptr; 5076 Expr *Arg = ArgRes.get(); 5077 QualType ArgType = Arg->getType(); 5078 if (!ParamType->isPointerType() || 5079 ParamType.getQualifiers().hasAddressSpace() || 5080 !ArgType->isPointerType() || 5081 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5082 OverloadParams.push_back(ParamType); 5083 continue; 5084 } 5085 5086 NeedsNewDecl = true; 5087 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5088 5089 QualType PointeeType = ParamType->getPointeeType(); 5090 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5091 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5092 } 5093 5094 if (!NeedsNewDecl) 5095 return nullptr; 5096 5097 FunctionProtoType::ExtProtoInfo EPI; 5098 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5099 OverloadParams, EPI); 5100 DeclContext *Parent = Context.getTranslationUnitDecl(); 5101 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5102 FDecl->getLocation(), 5103 FDecl->getLocation(), 5104 FDecl->getIdentifier(), 5105 OverloadTy, 5106 /*TInfo=*/nullptr, 5107 SC_Extern, false, 5108 /*hasPrototype=*/true); 5109 SmallVector<ParmVarDecl*, 16> Params; 5110 FT = cast<FunctionProtoType>(OverloadTy); 5111 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5112 QualType ParamType = FT->getParamType(i); 5113 ParmVarDecl *Parm = 5114 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5115 SourceLocation(), nullptr, ParamType, 5116 /*TInfo=*/nullptr, SC_None, nullptr); 5117 Parm->setScopeInfo(0, i); 5118 Params.push_back(Parm); 5119 } 5120 OverloadDecl->setParams(Params); 5121 return OverloadDecl; 5122 } 5123 5124 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5125 std::size_t NumArgs) { 5126 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5127 /*PartialOverloading=*/false)) 5128 return Callee->isVariadic(); 5129 return Callee->getMinRequiredArguments() <= NumArgs; 5130 } 5131 5132 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5133 /// This provides the location of the left/right parens and a list of comma 5134 /// locations. 5135 ExprResult 5136 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5137 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5138 Expr *ExecConfig, bool IsExecConfig) { 5139 // Since this might be a postfix expression, get rid of ParenListExprs. 5140 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 5141 if (Result.isInvalid()) return ExprError(); 5142 Fn = Result.get(); 5143 5144 if (checkArgsForPlaceholders(*this, ArgExprs)) 5145 return ExprError(); 5146 5147 if (getLangOpts().CPlusPlus) { 5148 // If this is a pseudo-destructor expression, build the call immediately. 5149 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5150 if (!ArgExprs.empty()) { 5151 // Pseudo-destructor calls should not have any arguments. 5152 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5153 << FixItHint::CreateRemoval( 5154 SourceRange(ArgExprs.front()->getLocStart(), 5155 ArgExprs.back()->getLocEnd())); 5156 } 5157 5158 return new (Context) 5159 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5160 } 5161 if (Fn->getType() == Context.PseudoObjectTy) { 5162 ExprResult result = CheckPlaceholderExpr(Fn); 5163 if (result.isInvalid()) return ExprError(); 5164 Fn = result.get(); 5165 } 5166 5167 // Determine whether this is a dependent call inside a C++ template, 5168 // in which case we won't do any semantic analysis now. 5169 bool Dependent = false; 5170 if (Fn->isTypeDependent()) 5171 Dependent = true; 5172 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5173 Dependent = true; 5174 5175 if (Dependent) { 5176 if (ExecConfig) { 5177 return new (Context) CUDAKernelCallExpr( 5178 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5179 Context.DependentTy, VK_RValue, RParenLoc); 5180 } else { 5181 return new (Context) CallExpr( 5182 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5183 } 5184 } 5185 5186 // Determine whether this is a call to an object (C++ [over.call.object]). 5187 if (Fn->getType()->isRecordType()) 5188 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 5189 RParenLoc); 5190 5191 if (Fn->getType() == Context.UnknownAnyTy) { 5192 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5193 if (result.isInvalid()) return ExprError(); 5194 Fn = result.get(); 5195 } 5196 5197 if (Fn->getType() == Context.BoundMemberTy) { 5198 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5199 } 5200 } 5201 5202 // Check for overloaded calls. This can happen even in C due to extensions. 5203 if (Fn->getType() == Context.OverloadTy) { 5204 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5205 5206 // We aren't supposed to apply this logic for if there's an '&' involved. 5207 if (!find.HasFormOfMemberPointer) { 5208 OverloadExpr *ovl = find.Expression; 5209 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5210 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 5211 RParenLoc, ExecConfig, 5212 /*AllowTypoCorrection=*/true, 5213 find.IsAddressOfOperand); 5214 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5215 } 5216 } 5217 5218 // If we're directly calling a function, get the appropriate declaration. 5219 if (Fn->getType() == Context.UnknownAnyTy) { 5220 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5221 if (result.isInvalid()) return ExprError(); 5222 Fn = result.get(); 5223 } 5224 5225 Expr *NakedFn = Fn->IgnoreParens(); 5226 5227 bool CallingNDeclIndirectly = false; 5228 NamedDecl *NDecl = nullptr; 5229 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5230 if (UnOp->getOpcode() == UO_AddrOf) { 5231 CallingNDeclIndirectly = true; 5232 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5233 } 5234 } 5235 5236 if (isa<DeclRefExpr>(NakedFn)) { 5237 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5238 5239 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5240 if (FDecl && FDecl->getBuiltinID()) { 5241 // Rewrite the function decl for this builtin by replacing parameters 5242 // with no explicit address space with the address space of the arguments 5243 // in ArgExprs. 5244 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5245 NDecl = FDecl; 5246 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 5247 SourceLocation(), FDecl, false, 5248 SourceLocation(), FDecl->getType(), 5249 Fn->getValueKind(), FDecl); 5250 } 5251 } 5252 } else if (isa<MemberExpr>(NakedFn)) 5253 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5254 5255 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5256 if (CallingNDeclIndirectly && 5257 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5258 Fn->getLocStart())) 5259 return ExprError(); 5260 5261 // CheckEnableIf assumes that the we're passing in a sane number of args for 5262 // FD, but that doesn't always hold true here. This is because, in some 5263 // cases, we'll emit a diag about an ill-formed function call, but then 5264 // we'll continue on as if the function call wasn't ill-formed. So, if the 5265 // number of args looks incorrect, don't do enable_if checks; we should've 5266 // already emitted an error about the bad call. 5267 if (FD->hasAttr<EnableIfAttr>() && 5268 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5269 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5270 Diag(Fn->getLocStart(), 5271 isa<CXXMethodDecl>(FD) ? 5272 diag::err_ovl_no_viable_member_function_in_call : 5273 diag::err_ovl_no_viable_function_in_call) 5274 << FD << FD->getSourceRange(); 5275 Diag(FD->getLocation(), 5276 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5277 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5278 } 5279 } 5280 } 5281 5282 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5283 ExecConfig, IsExecConfig); 5284 } 5285 5286 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5287 /// 5288 /// __builtin_astype( value, dst type ) 5289 /// 5290 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5291 SourceLocation BuiltinLoc, 5292 SourceLocation RParenLoc) { 5293 ExprValueKind VK = VK_RValue; 5294 ExprObjectKind OK = OK_Ordinary; 5295 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5296 QualType SrcTy = E->getType(); 5297 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5298 return ExprError(Diag(BuiltinLoc, 5299 diag::err_invalid_astype_of_different_size) 5300 << DstTy 5301 << SrcTy 5302 << E->getSourceRange()); 5303 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5304 } 5305 5306 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5307 /// provided arguments. 5308 /// 5309 /// __builtin_convertvector( value, dst type ) 5310 /// 5311 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5312 SourceLocation BuiltinLoc, 5313 SourceLocation RParenLoc) { 5314 TypeSourceInfo *TInfo; 5315 GetTypeFromParser(ParsedDestTy, &TInfo); 5316 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5317 } 5318 5319 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5320 /// i.e. an expression not of \p OverloadTy. The expression should 5321 /// unary-convert to an expression of function-pointer or 5322 /// block-pointer type. 5323 /// 5324 /// \param NDecl the declaration being called, if available 5325 ExprResult 5326 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5327 SourceLocation LParenLoc, 5328 ArrayRef<Expr *> Args, 5329 SourceLocation RParenLoc, 5330 Expr *Config, bool IsExecConfig) { 5331 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5332 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5333 5334 // Functions with 'interrupt' attribute cannot be called directly. 5335 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5336 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5337 return ExprError(); 5338 } 5339 5340 // Promote the function operand. 5341 // We special-case function promotion here because we only allow promoting 5342 // builtin functions to function pointers in the callee of a call. 5343 ExprResult Result; 5344 if (BuiltinID && 5345 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5346 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5347 CK_BuiltinFnToFnPtr).get(); 5348 } else { 5349 Result = CallExprUnaryConversions(Fn); 5350 } 5351 if (Result.isInvalid()) 5352 return ExprError(); 5353 Fn = Result.get(); 5354 5355 // Make the call expr early, before semantic checks. This guarantees cleanup 5356 // of arguments and function on error. 5357 CallExpr *TheCall; 5358 if (Config) 5359 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5360 cast<CallExpr>(Config), Args, 5361 Context.BoolTy, VK_RValue, 5362 RParenLoc); 5363 else 5364 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5365 VK_RValue, RParenLoc); 5366 5367 if (!getLangOpts().CPlusPlus) { 5368 // C cannot always handle TypoExpr nodes in builtin calls and direct 5369 // function calls as their argument checking don't necessarily handle 5370 // dependent types properly, so make sure any TypoExprs have been 5371 // dealt with. 5372 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5373 if (!Result.isUsable()) return ExprError(); 5374 TheCall = dyn_cast<CallExpr>(Result.get()); 5375 if (!TheCall) return Result; 5376 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5377 } 5378 5379 // Bail out early if calling a builtin with custom typechecking. 5380 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5381 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5382 5383 retry: 5384 const FunctionType *FuncT; 5385 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5386 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5387 // have type pointer to function". 5388 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5389 if (!FuncT) 5390 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5391 << Fn->getType() << Fn->getSourceRange()); 5392 } else if (const BlockPointerType *BPT = 5393 Fn->getType()->getAs<BlockPointerType>()) { 5394 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5395 } else { 5396 // Handle calls to expressions of unknown-any type. 5397 if (Fn->getType() == Context.UnknownAnyTy) { 5398 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5399 if (rewrite.isInvalid()) return ExprError(); 5400 Fn = rewrite.get(); 5401 TheCall->setCallee(Fn); 5402 goto retry; 5403 } 5404 5405 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5406 << Fn->getType() << Fn->getSourceRange()); 5407 } 5408 5409 if (getLangOpts().CUDA) { 5410 if (Config) { 5411 // CUDA: Kernel calls must be to global functions 5412 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5413 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5414 << FDecl->getName() << Fn->getSourceRange()); 5415 5416 // CUDA: Kernel function must have 'void' return type 5417 if (!FuncT->getReturnType()->isVoidType()) 5418 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5419 << Fn->getType() << Fn->getSourceRange()); 5420 } else { 5421 // CUDA: Calls to global functions must be configured 5422 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5423 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5424 << FDecl->getName() << Fn->getSourceRange()); 5425 } 5426 } 5427 5428 // Check for a valid return type 5429 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5430 FDecl)) 5431 return ExprError(); 5432 5433 // We know the result type of the call, set it. 5434 TheCall->setType(FuncT->getCallResultType(Context)); 5435 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5436 5437 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5438 if (Proto) { 5439 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5440 IsExecConfig)) 5441 return ExprError(); 5442 } else { 5443 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5444 5445 if (FDecl) { 5446 // Check if we have too few/too many template arguments, based 5447 // on our knowledge of the function definition. 5448 const FunctionDecl *Def = nullptr; 5449 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5450 Proto = Def->getType()->getAs<FunctionProtoType>(); 5451 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5452 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5453 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5454 } 5455 5456 // If the function we're calling isn't a function prototype, but we have 5457 // a function prototype from a prior declaratiom, use that prototype. 5458 if (!FDecl->hasPrototype()) 5459 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5460 } 5461 5462 // Promote the arguments (C99 6.5.2.2p6). 5463 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5464 Expr *Arg = Args[i]; 5465 5466 if (Proto && i < Proto->getNumParams()) { 5467 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5468 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5469 ExprResult ArgE = 5470 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5471 if (ArgE.isInvalid()) 5472 return true; 5473 5474 Arg = ArgE.getAs<Expr>(); 5475 5476 } else { 5477 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5478 5479 if (ArgE.isInvalid()) 5480 return true; 5481 5482 Arg = ArgE.getAs<Expr>(); 5483 } 5484 5485 if (RequireCompleteType(Arg->getLocStart(), 5486 Arg->getType(), 5487 diag::err_call_incomplete_argument, Arg)) 5488 return ExprError(); 5489 5490 TheCall->setArg(i, Arg); 5491 } 5492 } 5493 5494 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5495 if (!Method->isStatic()) 5496 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5497 << Fn->getSourceRange()); 5498 5499 // Check for sentinels 5500 if (NDecl) 5501 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5502 5503 // Do special checking on direct calls to functions. 5504 if (FDecl) { 5505 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5506 return ExprError(); 5507 5508 if (BuiltinID) 5509 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5510 } else if (NDecl) { 5511 if (CheckPointerCall(NDecl, TheCall, Proto)) 5512 return ExprError(); 5513 } else { 5514 if (CheckOtherCall(TheCall, Proto)) 5515 return ExprError(); 5516 } 5517 5518 return MaybeBindToTemporary(TheCall); 5519 } 5520 5521 ExprResult 5522 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5523 SourceLocation RParenLoc, Expr *InitExpr) { 5524 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5525 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5526 5527 TypeSourceInfo *TInfo; 5528 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5529 if (!TInfo) 5530 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5531 5532 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5533 } 5534 5535 ExprResult 5536 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5537 SourceLocation RParenLoc, Expr *LiteralExpr) { 5538 QualType literalType = TInfo->getType(); 5539 5540 if (literalType->isArrayType()) { 5541 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5542 diag::err_illegal_decl_array_incomplete_type, 5543 SourceRange(LParenLoc, 5544 LiteralExpr->getSourceRange().getEnd()))) 5545 return ExprError(); 5546 if (literalType->isVariableArrayType()) 5547 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5548 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5549 } else if (!literalType->isDependentType() && 5550 RequireCompleteType(LParenLoc, literalType, 5551 diag::err_typecheck_decl_incomplete_type, 5552 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5553 return ExprError(); 5554 5555 InitializedEntity Entity 5556 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5557 InitializationKind Kind 5558 = InitializationKind::CreateCStyleCast(LParenLoc, 5559 SourceRange(LParenLoc, RParenLoc), 5560 /*InitList=*/true); 5561 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5562 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5563 &literalType); 5564 if (Result.isInvalid()) 5565 return ExprError(); 5566 LiteralExpr = Result.get(); 5567 5568 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5569 if (isFileScope && 5570 !LiteralExpr->isTypeDependent() && 5571 !LiteralExpr->isValueDependent() && 5572 !literalType->isDependentType()) { // 6.5.2.5p3 5573 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5574 return ExprError(); 5575 } 5576 5577 // In C, compound literals are l-values for some reason. 5578 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5579 5580 return MaybeBindToTemporary( 5581 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5582 VK, LiteralExpr, isFileScope)); 5583 } 5584 5585 ExprResult 5586 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5587 SourceLocation RBraceLoc) { 5588 // Immediately handle non-overload placeholders. Overloads can be 5589 // resolved contextually, but everything else here can't. 5590 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5591 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5592 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5593 5594 // Ignore failures; dropping the entire initializer list because 5595 // of one failure would be terrible for indexing/etc. 5596 if (result.isInvalid()) continue; 5597 5598 InitArgList[I] = result.get(); 5599 } 5600 } 5601 5602 // Semantic analysis for initializers is done by ActOnDeclarator() and 5603 // CheckInitializer() - it requires knowledge of the object being intialized. 5604 5605 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5606 RBraceLoc); 5607 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5608 return E; 5609 } 5610 5611 /// Do an explicit extend of the given block pointer if we're in ARC. 5612 void Sema::maybeExtendBlockObject(ExprResult &E) { 5613 assert(E.get()->getType()->isBlockPointerType()); 5614 assert(E.get()->isRValue()); 5615 5616 // Only do this in an r-value context. 5617 if (!getLangOpts().ObjCAutoRefCount) return; 5618 5619 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5620 CK_ARCExtendBlockObject, E.get(), 5621 /*base path*/ nullptr, VK_RValue); 5622 Cleanup.setExprNeedsCleanups(true); 5623 } 5624 5625 /// Prepare a conversion of the given expression to an ObjC object 5626 /// pointer type. 5627 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5628 QualType type = E.get()->getType(); 5629 if (type->isObjCObjectPointerType()) { 5630 return CK_BitCast; 5631 } else if (type->isBlockPointerType()) { 5632 maybeExtendBlockObject(E); 5633 return CK_BlockPointerToObjCPointerCast; 5634 } else { 5635 assert(type->isPointerType()); 5636 return CK_CPointerToObjCPointerCast; 5637 } 5638 } 5639 5640 /// Prepares for a scalar cast, performing all the necessary stages 5641 /// except the final cast and returning the kind required. 5642 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5643 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5644 // Also, callers should have filtered out the invalid cases with 5645 // pointers. Everything else should be possible. 5646 5647 QualType SrcTy = Src.get()->getType(); 5648 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5649 return CK_NoOp; 5650 5651 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5652 case Type::STK_MemberPointer: 5653 llvm_unreachable("member pointer type in C"); 5654 5655 case Type::STK_CPointer: 5656 case Type::STK_BlockPointer: 5657 case Type::STK_ObjCObjectPointer: 5658 switch (DestTy->getScalarTypeKind()) { 5659 case Type::STK_CPointer: { 5660 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5661 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5662 if (SrcAS != DestAS) 5663 return CK_AddressSpaceConversion; 5664 return CK_BitCast; 5665 } 5666 case Type::STK_BlockPointer: 5667 return (SrcKind == Type::STK_BlockPointer 5668 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5669 case Type::STK_ObjCObjectPointer: 5670 if (SrcKind == Type::STK_ObjCObjectPointer) 5671 return CK_BitCast; 5672 if (SrcKind == Type::STK_CPointer) 5673 return CK_CPointerToObjCPointerCast; 5674 maybeExtendBlockObject(Src); 5675 return CK_BlockPointerToObjCPointerCast; 5676 case Type::STK_Bool: 5677 return CK_PointerToBoolean; 5678 case Type::STK_Integral: 5679 return CK_PointerToIntegral; 5680 case Type::STK_Floating: 5681 case Type::STK_FloatingComplex: 5682 case Type::STK_IntegralComplex: 5683 case Type::STK_MemberPointer: 5684 llvm_unreachable("illegal cast from pointer"); 5685 } 5686 llvm_unreachable("Should have returned before this"); 5687 5688 case Type::STK_Bool: // casting from bool is like casting from an integer 5689 case Type::STK_Integral: 5690 switch (DestTy->getScalarTypeKind()) { 5691 case Type::STK_CPointer: 5692 case Type::STK_ObjCObjectPointer: 5693 case Type::STK_BlockPointer: 5694 if (Src.get()->isNullPointerConstant(Context, 5695 Expr::NPC_ValueDependentIsNull)) 5696 return CK_NullToPointer; 5697 return CK_IntegralToPointer; 5698 case Type::STK_Bool: 5699 return CK_IntegralToBoolean; 5700 case Type::STK_Integral: 5701 return CK_IntegralCast; 5702 case Type::STK_Floating: 5703 return CK_IntegralToFloating; 5704 case Type::STK_IntegralComplex: 5705 Src = ImpCastExprToType(Src.get(), 5706 DestTy->castAs<ComplexType>()->getElementType(), 5707 CK_IntegralCast); 5708 return CK_IntegralRealToComplex; 5709 case Type::STK_FloatingComplex: 5710 Src = ImpCastExprToType(Src.get(), 5711 DestTy->castAs<ComplexType>()->getElementType(), 5712 CK_IntegralToFloating); 5713 return CK_FloatingRealToComplex; 5714 case Type::STK_MemberPointer: 5715 llvm_unreachable("member pointer type in C"); 5716 } 5717 llvm_unreachable("Should have returned before this"); 5718 5719 case Type::STK_Floating: 5720 switch (DestTy->getScalarTypeKind()) { 5721 case Type::STK_Floating: 5722 return CK_FloatingCast; 5723 case Type::STK_Bool: 5724 return CK_FloatingToBoolean; 5725 case Type::STK_Integral: 5726 return CK_FloatingToIntegral; 5727 case Type::STK_FloatingComplex: 5728 Src = ImpCastExprToType(Src.get(), 5729 DestTy->castAs<ComplexType>()->getElementType(), 5730 CK_FloatingCast); 5731 return CK_FloatingRealToComplex; 5732 case Type::STK_IntegralComplex: 5733 Src = ImpCastExprToType(Src.get(), 5734 DestTy->castAs<ComplexType>()->getElementType(), 5735 CK_FloatingToIntegral); 5736 return CK_IntegralRealToComplex; 5737 case Type::STK_CPointer: 5738 case Type::STK_ObjCObjectPointer: 5739 case Type::STK_BlockPointer: 5740 llvm_unreachable("valid float->pointer cast?"); 5741 case Type::STK_MemberPointer: 5742 llvm_unreachable("member pointer type in C"); 5743 } 5744 llvm_unreachable("Should have returned before this"); 5745 5746 case Type::STK_FloatingComplex: 5747 switch (DestTy->getScalarTypeKind()) { 5748 case Type::STK_FloatingComplex: 5749 return CK_FloatingComplexCast; 5750 case Type::STK_IntegralComplex: 5751 return CK_FloatingComplexToIntegralComplex; 5752 case Type::STK_Floating: { 5753 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5754 if (Context.hasSameType(ET, DestTy)) 5755 return CK_FloatingComplexToReal; 5756 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5757 return CK_FloatingCast; 5758 } 5759 case Type::STK_Bool: 5760 return CK_FloatingComplexToBoolean; 5761 case Type::STK_Integral: 5762 Src = ImpCastExprToType(Src.get(), 5763 SrcTy->castAs<ComplexType>()->getElementType(), 5764 CK_FloatingComplexToReal); 5765 return CK_FloatingToIntegral; 5766 case Type::STK_CPointer: 5767 case Type::STK_ObjCObjectPointer: 5768 case Type::STK_BlockPointer: 5769 llvm_unreachable("valid complex float->pointer cast?"); 5770 case Type::STK_MemberPointer: 5771 llvm_unreachable("member pointer type in C"); 5772 } 5773 llvm_unreachable("Should have returned before this"); 5774 5775 case Type::STK_IntegralComplex: 5776 switch (DestTy->getScalarTypeKind()) { 5777 case Type::STK_FloatingComplex: 5778 return CK_IntegralComplexToFloatingComplex; 5779 case Type::STK_IntegralComplex: 5780 return CK_IntegralComplexCast; 5781 case Type::STK_Integral: { 5782 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5783 if (Context.hasSameType(ET, DestTy)) 5784 return CK_IntegralComplexToReal; 5785 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5786 return CK_IntegralCast; 5787 } 5788 case Type::STK_Bool: 5789 return CK_IntegralComplexToBoolean; 5790 case Type::STK_Floating: 5791 Src = ImpCastExprToType(Src.get(), 5792 SrcTy->castAs<ComplexType>()->getElementType(), 5793 CK_IntegralComplexToReal); 5794 return CK_IntegralToFloating; 5795 case Type::STK_CPointer: 5796 case Type::STK_ObjCObjectPointer: 5797 case Type::STK_BlockPointer: 5798 llvm_unreachable("valid complex int->pointer cast?"); 5799 case Type::STK_MemberPointer: 5800 llvm_unreachable("member pointer type in C"); 5801 } 5802 llvm_unreachable("Should have returned before this"); 5803 } 5804 5805 llvm_unreachable("Unhandled scalar cast"); 5806 } 5807 5808 static bool breakDownVectorType(QualType type, uint64_t &len, 5809 QualType &eltType) { 5810 // Vectors are simple. 5811 if (const VectorType *vecType = type->getAs<VectorType>()) { 5812 len = vecType->getNumElements(); 5813 eltType = vecType->getElementType(); 5814 assert(eltType->isScalarType()); 5815 return true; 5816 } 5817 5818 // We allow lax conversion to and from non-vector types, but only if 5819 // they're real types (i.e. non-complex, non-pointer scalar types). 5820 if (!type->isRealType()) return false; 5821 5822 len = 1; 5823 eltType = type; 5824 return true; 5825 } 5826 5827 /// Are the two types lax-compatible vector types? That is, given 5828 /// that one of them is a vector, do they have equal storage sizes, 5829 /// where the storage size is the number of elements times the element 5830 /// size? 5831 /// 5832 /// This will also return false if either of the types is neither a 5833 /// vector nor a real type. 5834 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5835 assert(destTy->isVectorType() || srcTy->isVectorType()); 5836 5837 // Disallow lax conversions between scalars and ExtVectors (these 5838 // conversions are allowed for other vector types because common headers 5839 // depend on them). Most scalar OP ExtVector cases are handled by the 5840 // splat path anyway, which does what we want (convert, not bitcast). 5841 // What this rules out for ExtVectors is crazy things like char4*float. 5842 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5843 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5844 5845 uint64_t srcLen, destLen; 5846 QualType srcEltTy, destEltTy; 5847 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5848 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5849 5850 // ASTContext::getTypeSize will return the size rounded up to a 5851 // power of 2, so instead of using that, we need to use the raw 5852 // element size multiplied by the element count. 5853 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5854 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5855 5856 return (srcLen * srcEltSize == destLen * destEltSize); 5857 } 5858 5859 /// Is this a legal conversion between two types, one of which is 5860 /// known to be a vector type? 5861 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5862 assert(destTy->isVectorType() || srcTy->isVectorType()); 5863 5864 if (!Context.getLangOpts().LaxVectorConversions) 5865 return false; 5866 return areLaxCompatibleVectorTypes(srcTy, destTy); 5867 } 5868 5869 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5870 CastKind &Kind) { 5871 assert(VectorTy->isVectorType() && "Not a vector type!"); 5872 5873 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5874 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5875 return Diag(R.getBegin(), 5876 Ty->isVectorType() ? 5877 diag::err_invalid_conversion_between_vectors : 5878 diag::err_invalid_conversion_between_vector_and_integer) 5879 << VectorTy << Ty << R; 5880 } else 5881 return Diag(R.getBegin(), 5882 diag::err_invalid_conversion_between_vector_and_scalar) 5883 << VectorTy << Ty << R; 5884 5885 Kind = CK_BitCast; 5886 return false; 5887 } 5888 5889 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5890 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5891 5892 if (DestElemTy == SplattedExpr->getType()) 5893 return SplattedExpr; 5894 5895 assert(DestElemTy->isFloatingType() || 5896 DestElemTy->isIntegralOrEnumerationType()); 5897 5898 CastKind CK; 5899 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5900 // OpenCL requires that we convert `true` boolean expressions to -1, but 5901 // only when splatting vectors. 5902 if (DestElemTy->isFloatingType()) { 5903 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5904 // in two steps: boolean to signed integral, then to floating. 5905 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5906 CK_BooleanToSignedIntegral); 5907 SplattedExpr = CastExprRes.get(); 5908 CK = CK_IntegralToFloating; 5909 } else { 5910 CK = CK_BooleanToSignedIntegral; 5911 } 5912 } else { 5913 ExprResult CastExprRes = SplattedExpr; 5914 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5915 if (CastExprRes.isInvalid()) 5916 return ExprError(); 5917 SplattedExpr = CastExprRes.get(); 5918 } 5919 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5920 } 5921 5922 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5923 Expr *CastExpr, CastKind &Kind) { 5924 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5925 5926 QualType SrcTy = CastExpr->getType(); 5927 5928 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5929 // an ExtVectorType. 5930 // In OpenCL, casts between vectors of different types are not allowed. 5931 // (See OpenCL 6.2). 5932 if (SrcTy->isVectorType()) { 5933 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5934 || (getLangOpts().OpenCL && 5935 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5936 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5937 << DestTy << SrcTy << R; 5938 return ExprError(); 5939 } 5940 Kind = CK_BitCast; 5941 return CastExpr; 5942 } 5943 5944 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5945 // conversion will take place first from scalar to elt type, and then 5946 // splat from elt type to vector. 5947 if (SrcTy->isPointerType()) 5948 return Diag(R.getBegin(), 5949 diag::err_invalid_conversion_between_vector_and_scalar) 5950 << DestTy << SrcTy << R; 5951 5952 Kind = CK_VectorSplat; 5953 return prepareVectorSplat(DestTy, CastExpr); 5954 } 5955 5956 ExprResult 5957 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5958 Declarator &D, ParsedType &Ty, 5959 SourceLocation RParenLoc, Expr *CastExpr) { 5960 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5961 "ActOnCastExpr(): missing type or expr"); 5962 5963 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5964 if (D.isInvalidType()) 5965 return ExprError(); 5966 5967 if (getLangOpts().CPlusPlus) { 5968 // Check that there are no default arguments (C++ only). 5969 CheckExtraCXXDefaultArguments(D); 5970 } else { 5971 // Make sure any TypoExprs have been dealt with. 5972 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5973 if (!Res.isUsable()) 5974 return ExprError(); 5975 CastExpr = Res.get(); 5976 } 5977 5978 checkUnusedDeclAttributes(D); 5979 5980 QualType castType = castTInfo->getType(); 5981 Ty = CreateParsedType(castType, castTInfo); 5982 5983 bool isVectorLiteral = false; 5984 5985 // Check for an altivec or OpenCL literal, 5986 // i.e. all the elements are integer constants. 5987 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5988 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5989 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5990 && castType->isVectorType() && (PE || PLE)) { 5991 if (PLE && PLE->getNumExprs() == 0) { 5992 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5993 return ExprError(); 5994 } 5995 if (PE || PLE->getNumExprs() == 1) { 5996 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5997 if (!E->getType()->isVectorType()) 5998 isVectorLiteral = true; 5999 } 6000 else 6001 isVectorLiteral = true; 6002 } 6003 6004 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6005 // then handle it as such. 6006 if (isVectorLiteral) 6007 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6008 6009 // If the Expr being casted is a ParenListExpr, handle it specially. 6010 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6011 // sequence of BinOp comma operators. 6012 if (isa<ParenListExpr>(CastExpr)) { 6013 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6014 if (Result.isInvalid()) return ExprError(); 6015 CastExpr = Result.get(); 6016 } 6017 6018 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6019 !getSourceManager().isInSystemMacro(LParenLoc)) 6020 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6021 6022 CheckTollFreeBridgeCast(castType, CastExpr); 6023 6024 CheckObjCBridgeRelatedCast(castType, CastExpr); 6025 6026 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6027 6028 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6029 } 6030 6031 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6032 SourceLocation RParenLoc, Expr *E, 6033 TypeSourceInfo *TInfo) { 6034 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6035 "Expected paren or paren list expression"); 6036 6037 Expr **exprs; 6038 unsigned numExprs; 6039 Expr *subExpr; 6040 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6041 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6042 LiteralLParenLoc = PE->getLParenLoc(); 6043 LiteralRParenLoc = PE->getRParenLoc(); 6044 exprs = PE->getExprs(); 6045 numExprs = PE->getNumExprs(); 6046 } else { // isa<ParenExpr> by assertion at function entrance 6047 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6048 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6049 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6050 exprs = &subExpr; 6051 numExprs = 1; 6052 } 6053 6054 QualType Ty = TInfo->getType(); 6055 assert(Ty->isVectorType() && "Expected vector type"); 6056 6057 SmallVector<Expr *, 8> initExprs; 6058 const VectorType *VTy = Ty->getAs<VectorType>(); 6059 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6060 6061 // '(...)' form of vector initialization in AltiVec: the number of 6062 // initializers must be one or must match the size of the vector. 6063 // If a single value is specified in the initializer then it will be 6064 // replicated to all the components of the vector 6065 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6066 // The number of initializers must be one or must match the size of the 6067 // vector. If a single value is specified in the initializer then it will 6068 // be replicated to all the components of the vector 6069 if (numExprs == 1) { 6070 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6071 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6072 if (Literal.isInvalid()) 6073 return ExprError(); 6074 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6075 PrepareScalarCast(Literal, ElemTy)); 6076 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6077 } 6078 else if (numExprs < numElems) { 6079 Diag(E->getExprLoc(), 6080 diag::err_incorrect_number_of_vector_initializers); 6081 return ExprError(); 6082 } 6083 else 6084 initExprs.append(exprs, exprs + numExprs); 6085 } 6086 else { 6087 // For OpenCL, when the number of initializers is a single value, 6088 // it will be replicated to all components of the vector. 6089 if (getLangOpts().OpenCL && 6090 VTy->getVectorKind() == VectorType::GenericVector && 6091 numExprs == 1) { 6092 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6093 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6094 if (Literal.isInvalid()) 6095 return ExprError(); 6096 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6097 PrepareScalarCast(Literal, ElemTy)); 6098 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6099 } 6100 6101 initExprs.append(exprs, exprs + numExprs); 6102 } 6103 // FIXME: This means that pretty-printing the final AST will produce curly 6104 // braces instead of the original commas. 6105 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6106 initExprs, LiteralRParenLoc); 6107 initE->setType(Ty); 6108 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6109 } 6110 6111 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6112 /// the ParenListExpr into a sequence of comma binary operators. 6113 ExprResult 6114 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6115 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6116 if (!E) 6117 return OrigExpr; 6118 6119 ExprResult Result(E->getExpr(0)); 6120 6121 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6122 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6123 E->getExpr(i)); 6124 6125 if (Result.isInvalid()) return ExprError(); 6126 6127 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6128 } 6129 6130 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6131 SourceLocation R, 6132 MultiExprArg Val) { 6133 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6134 return expr; 6135 } 6136 6137 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6138 /// constant and the other is not a pointer. Returns true if a diagnostic is 6139 /// emitted. 6140 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6141 SourceLocation QuestionLoc) { 6142 Expr *NullExpr = LHSExpr; 6143 Expr *NonPointerExpr = RHSExpr; 6144 Expr::NullPointerConstantKind NullKind = 6145 NullExpr->isNullPointerConstant(Context, 6146 Expr::NPC_ValueDependentIsNotNull); 6147 6148 if (NullKind == Expr::NPCK_NotNull) { 6149 NullExpr = RHSExpr; 6150 NonPointerExpr = LHSExpr; 6151 NullKind = 6152 NullExpr->isNullPointerConstant(Context, 6153 Expr::NPC_ValueDependentIsNotNull); 6154 } 6155 6156 if (NullKind == Expr::NPCK_NotNull) 6157 return false; 6158 6159 if (NullKind == Expr::NPCK_ZeroExpression) 6160 return false; 6161 6162 if (NullKind == Expr::NPCK_ZeroLiteral) { 6163 // In this case, check to make sure that we got here from a "NULL" 6164 // string in the source code. 6165 NullExpr = NullExpr->IgnoreParenImpCasts(); 6166 SourceLocation loc = NullExpr->getExprLoc(); 6167 if (!findMacroSpelling(loc, "NULL")) 6168 return false; 6169 } 6170 6171 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6172 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6173 << NonPointerExpr->getType() << DiagType 6174 << NonPointerExpr->getSourceRange(); 6175 return true; 6176 } 6177 6178 /// \brief Return false if the condition expression is valid, true otherwise. 6179 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6180 QualType CondTy = Cond->getType(); 6181 6182 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6183 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6184 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6185 << CondTy << Cond->getSourceRange(); 6186 return true; 6187 } 6188 6189 // C99 6.5.15p2 6190 if (CondTy->isScalarType()) return false; 6191 6192 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6193 << CondTy << Cond->getSourceRange(); 6194 return true; 6195 } 6196 6197 /// \brief Handle when one or both operands are void type. 6198 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6199 ExprResult &RHS) { 6200 Expr *LHSExpr = LHS.get(); 6201 Expr *RHSExpr = RHS.get(); 6202 6203 if (!LHSExpr->getType()->isVoidType()) 6204 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6205 << RHSExpr->getSourceRange(); 6206 if (!RHSExpr->getType()->isVoidType()) 6207 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6208 << LHSExpr->getSourceRange(); 6209 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6210 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6211 return S.Context.VoidTy; 6212 } 6213 6214 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6215 /// true otherwise. 6216 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6217 QualType PointerTy) { 6218 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6219 !NullExpr.get()->isNullPointerConstant(S.Context, 6220 Expr::NPC_ValueDependentIsNull)) 6221 return true; 6222 6223 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6224 return false; 6225 } 6226 6227 /// \brief Checks compatibility between two pointers and return the resulting 6228 /// type. 6229 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6230 ExprResult &RHS, 6231 SourceLocation Loc) { 6232 QualType LHSTy = LHS.get()->getType(); 6233 QualType RHSTy = RHS.get()->getType(); 6234 6235 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6236 // Two identical pointers types are always compatible. 6237 return LHSTy; 6238 } 6239 6240 QualType lhptee, rhptee; 6241 6242 // Get the pointee types. 6243 bool IsBlockPointer = false; 6244 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6245 lhptee = LHSBTy->getPointeeType(); 6246 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6247 IsBlockPointer = true; 6248 } else { 6249 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6250 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6251 } 6252 6253 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6254 // differently qualified versions of compatible types, the result type is 6255 // a pointer to an appropriately qualified version of the composite 6256 // type. 6257 6258 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6259 // clause doesn't make sense for our extensions. E.g. address space 2 should 6260 // be incompatible with address space 3: they may live on different devices or 6261 // anything. 6262 Qualifiers lhQual = lhptee.getQualifiers(); 6263 Qualifiers rhQual = rhptee.getQualifiers(); 6264 6265 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6266 lhQual.removeCVRQualifiers(); 6267 rhQual.removeCVRQualifiers(); 6268 6269 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6270 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6271 6272 // For OpenCL: 6273 // 1. If LHS and RHS types match exactly and: 6274 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6275 // (b) AS overlap => generate addrspacecast 6276 // (c) AS don't overlap => give an error 6277 // 2. if LHS and RHS types don't match: 6278 // (a) AS match => use standard C rules, generate bitcast 6279 // (b) AS overlap => generate addrspacecast instead of bitcast 6280 // (c) AS don't overlap => give an error 6281 6282 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6283 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6284 6285 // OpenCL cases 1c, 2a, 2b, and 2c. 6286 if (CompositeTy.isNull()) { 6287 // In this situation, we assume void* type. No especially good 6288 // reason, but this is what gcc does, and we do have to pick 6289 // to get a consistent AST. 6290 QualType incompatTy; 6291 if (S.getLangOpts().OpenCL) { 6292 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6293 // spaces is disallowed. 6294 unsigned ResultAddrSpace; 6295 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6296 // Cases 2a and 2b. 6297 ResultAddrSpace = lhQual.getAddressSpace(); 6298 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6299 // Cases 2a and 2b. 6300 ResultAddrSpace = rhQual.getAddressSpace(); 6301 } else { 6302 // Cases 1c and 2c. 6303 S.Diag(Loc, 6304 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6305 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6306 << RHS.get()->getSourceRange(); 6307 return QualType(); 6308 } 6309 6310 // Continue handling cases 2a and 2b. 6311 incompatTy = S.Context.getPointerType( 6312 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6313 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6314 (lhQual.getAddressSpace() != ResultAddrSpace) 6315 ? CK_AddressSpaceConversion /* 2b */ 6316 : CK_BitCast /* 2a */); 6317 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6318 (rhQual.getAddressSpace() != ResultAddrSpace) 6319 ? CK_AddressSpaceConversion /* 2b */ 6320 : CK_BitCast /* 2a */); 6321 } else { 6322 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6323 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6324 << RHS.get()->getSourceRange(); 6325 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6326 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6327 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6328 } 6329 return incompatTy; 6330 } 6331 6332 // The pointer types are compatible. 6333 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6334 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6335 if (IsBlockPointer) 6336 ResultTy = S.Context.getBlockPointerType(ResultTy); 6337 else { 6338 // Cases 1a and 1b for OpenCL. 6339 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6340 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6341 ? CK_BitCast /* 1a */ 6342 : CK_AddressSpaceConversion /* 1b */; 6343 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6344 ? CK_BitCast /* 1a */ 6345 : CK_AddressSpaceConversion /* 1b */; 6346 ResultTy = S.Context.getPointerType(ResultTy); 6347 } 6348 6349 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6350 // if the target type does not change. 6351 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6352 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6353 return ResultTy; 6354 } 6355 6356 /// \brief Return the resulting type when the operands are both block pointers. 6357 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6358 ExprResult &LHS, 6359 ExprResult &RHS, 6360 SourceLocation Loc) { 6361 QualType LHSTy = LHS.get()->getType(); 6362 QualType RHSTy = RHS.get()->getType(); 6363 6364 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6365 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6366 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6367 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6368 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6369 return destType; 6370 } 6371 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6372 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6373 << RHS.get()->getSourceRange(); 6374 return QualType(); 6375 } 6376 6377 // We have 2 block pointer types. 6378 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6379 } 6380 6381 /// \brief Return the resulting type when the operands are both pointers. 6382 static QualType 6383 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6384 ExprResult &RHS, 6385 SourceLocation Loc) { 6386 // get the pointer types 6387 QualType LHSTy = LHS.get()->getType(); 6388 QualType RHSTy = RHS.get()->getType(); 6389 6390 // get the "pointed to" types 6391 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6392 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6393 6394 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6395 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6396 // Figure out necessary qualifiers (C99 6.5.15p6) 6397 QualType destPointee 6398 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6399 QualType destType = S.Context.getPointerType(destPointee); 6400 // Add qualifiers if necessary. 6401 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6402 // Promote to void*. 6403 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6404 return destType; 6405 } 6406 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6407 QualType destPointee 6408 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6409 QualType destType = S.Context.getPointerType(destPointee); 6410 // Add qualifiers if necessary. 6411 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6412 // Promote to void*. 6413 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6414 return destType; 6415 } 6416 6417 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6418 } 6419 6420 /// \brief Return false if the first expression is not an integer and the second 6421 /// expression is not a pointer, true otherwise. 6422 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6423 Expr* PointerExpr, SourceLocation Loc, 6424 bool IsIntFirstExpr) { 6425 if (!PointerExpr->getType()->isPointerType() || 6426 !Int.get()->getType()->isIntegerType()) 6427 return false; 6428 6429 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6430 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6431 6432 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6433 << Expr1->getType() << Expr2->getType() 6434 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6435 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6436 CK_IntegralToPointer); 6437 return true; 6438 } 6439 6440 /// \brief Simple conversion between integer and floating point types. 6441 /// 6442 /// Used when handling the OpenCL conditional operator where the 6443 /// condition is a vector while the other operands are scalar. 6444 /// 6445 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6446 /// types are either integer or floating type. Between the two 6447 /// operands, the type with the higher rank is defined as the "result 6448 /// type". The other operand needs to be promoted to the same type. No 6449 /// other type promotion is allowed. We cannot use 6450 /// UsualArithmeticConversions() for this purpose, since it always 6451 /// promotes promotable types. 6452 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6453 ExprResult &RHS, 6454 SourceLocation QuestionLoc) { 6455 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6456 if (LHS.isInvalid()) 6457 return QualType(); 6458 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6459 if (RHS.isInvalid()) 6460 return QualType(); 6461 6462 // For conversion purposes, we ignore any qualifiers. 6463 // For example, "const float" and "float" are equivalent. 6464 QualType LHSType = 6465 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6466 QualType RHSType = 6467 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6468 6469 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6470 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6471 << LHSType << LHS.get()->getSourceRange(); 6472 return QualType(); 6473 } 6474 6475 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6476 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6477 << RHSType << RHS.get()->getSourceRange(); 6478 return QualType(); 6479 } 6480 6481 // If both types are identical, no conversion is needed. 6482 if (LHSType == RHSType) 6483 return LHSType; 6484 6485 // Now handle "real" floating types (i.e. float, double, long double). 6486 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6487 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6488 /*IsCompAssign = */ false); 6489 6490 // Finally, we have two differing integer types. 6491 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6492 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6493 } 6494 6495 /// \brief Convert scalar operands to a vector that matches the 6496 /// condition in length. 6497 /// 6498 /// Used when handling the OpenCL conditional operator where the 6499 /// condition is a vector while the other operands are scalar. 6500 /// 6501 /// We first compute the "result type" for the scalar operands 6502 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6503 /// into a vector of that type where the length matches the condition 6504 /// vector type. s6.11.6 requires that the element types of the result 6505 /// and the condition must have the same number of bits. 6506 static QualType 6507 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6508 QualType CondTy, SourceLocation QuestionLoc) { 6509 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6510 if (ResTy.isNull()) return QualType(); 6511 6512 const VectorType *CV = CondTy->getAs<VectorType>(); 6513 assert(CV); 6514 6515 // Determine the vector result type 6516 unsigned NumElements = CV->getNumElements(); 6517 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6518 6519 // Ensure that all types have the same number of bits 6520 if (S.Context.getTypeSize(CV->getElementType()) 6521 != S.Context.getTypeSize(ResTy)) { 6522 // Since VectorTy is created internally, it does not pretty print 6523 // with an OpenCL name. Instead, we just print a description. 6524 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6525 SmallString<64> Str; 6526 llvm::raw_svector_ostream OS(Str); 6527 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6528 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6529 << CondTy << OS.str(); 6530 return QualType(); 6531 } 6532 6533 // Convert operands to the vector result type 6534 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6535 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6536 6537 return VectorTy; 6538 } 6539 6540 /// \brief Return false if this is a valid OpenCL condition vector 6541 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6542 SourceLocation QuestionLoc) { 6543 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6544 // integral type. 6545 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6546 assert(CondTy); 6547 QualType EleTy = CondTy->getElementType(); 6548 if (EleTy->isIntegerType()) return false; 6549 6550 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6551 << Cond->getType() << Cond->getSourceRange(); 6552 return true; 6553 } 6554 6555 /// \brief Return false if the vector condition type and the vector 6556 /// result type are compatible. 6557 /// 6558 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6559 /// number of elements, and their element types have the same number 6560 /// of bits. 6561 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6562 SourceLocation QuestionLoc) { 6563 const VectorType *CV = CondTy->getAs<VectorType>(); 6564 const VectorType *RV = VecResTy->getAs<VectorType>(); 6565 assert(CV && RV); 6566 6567 if (CV->getNumElements() != RV->getNumElements()) { 6568 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6569 << CondTy << VecResTy; 6570 return true; 6571 } 6572 6573 QualType CVE = CV->getElementType(); 6574 QualType RVE = RV->getElementType(); 6575 6576 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6577 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6578 << CondTy << VecResTy; 6579 return true; 6580 } 6581 6582 return false; 6583 } 6584 6585 /// \brief Return the resulting type for the conditional operator in 6586 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6587 /// s6.3.i) when the condition is a vector type. 6588 static QualType 6589 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6590 ExprResult &LHS, ExprResult &RHS, 6591 SourceLocation QuestionLoc) { 6592 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6593 if (Cond.isInvalid()) 6594 return QualType(); 6595 QualType CondTy = Cond.get()->getType(); 6596 6597 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6598 return QualType(); 6599 6600 // If either operand is a vector then find the vector type of the 6601 // result as specified in OpenCL v1.1 s6.3.i. 6602 if (LHS.get()->getType()->isVectorType() || 6603 RHS.get()->getType()->isVectorType()) { 6604 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6605 /*isCompAssign*/false, 6606 /*AllowBothBool*/true, 6607 /*AllowBoolConversions*/false); 6608 if (VecResTy.isNull()) return QualType(); 6609 // The result type must match the condition type as specified in 6610 // OpenCL v1.1 s6.11.6. 6611 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6612 return QualType(); 6613 return VecResTy; 6614 } 6615 6616 // Both operands are scalar. 6617 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6618 } 6619 6620 /// \brief Return true if the Expr is block type 6621 static bool checkBlockType(Sema &S, const Expr *E) { 6622 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6623 QualType Ty = CE->getCallee()->getType(); 6624 if (Ty->isBlockPointerType()) { 6625 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6626 return true; 6627 } 6628 } 6629 return false; 6630 } 6631 6632 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6633 /// In that case, LHS = cond. 6634 /// C99 6.5.15 6635 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6636 ExprResult &RHS, ExprValueKind &VK, 6637 ExprObjectKind &OK, 6638 SourceLocation QuestionLoc) { 6639 6640 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6641 if (!LHSResult.isUsable()) return QualType(); 6642 LHS = LHSResult; 6643 6644 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6645 if (!RHSResult.isUsable()) return QualType(); 6646 RHS = RHSResult; 6647 6648 // C++ is sufficiently different to merit its own checker. 6649 if (getLangOpts().CPlusPlus) 6650 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6651 6652 VK = VK_RValue; 6653 OK = OK_Ordinary; 6654 6655 // The OpenCL operator with a vector condition is sufficiently 6656 // different to merit its own checker. 6657 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6658 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6659 6660 // First, check the condition. 6661 Cond = UsualUnaryConversions(Cond.get()); 6662 if (Cond.isInvalid()) 6663 return QualType(); 6664 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6665 return QualType(); 6666 6667 // Now check the two expressions. 6668 if (LHS.get()->getType()->isVectorType() || 6669 RHS.get()->getType()->isVectorType()) 6670 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6671 /*AllowBothBool*/true, 6672 /*AllowBoolConversions*/false); 6673 6674 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6675 if (LHS.isInvalid() || RHS.isInvalid()) 6676 return QualType(); 6677 6678 QualType LHSTy = LHS.get()->getType(); 6679 QualType RHSTy = RHS.get()->getType(); 6680 6681 // Diagnose attempts to convert between __float128 and long double where 6682 // such conversions currently can't be handled. 6683 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6684 Diag(QuestionLoc, 6685 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6686 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6687 return QualType(); 6688 } 6689 6690 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6691 // selection operator (?:). 6692 if (getLangOpts().OpenCL && 6693 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6694 return QualType(); 6695 } 6696 6697 // If both operands have arithmetic type, do the usual arithmetic conversions 6698 // to find a common type: C99 6.5.15p3,5. 6699 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6700 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6701 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6702 6703 return ResTy; 6704 } 6705 6706 // If both operands are the same structure or union type, the result is that 6707 // type. 6708 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6709 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6710 if (LHSRT->getDecl() == RHSRT->getDecl()) 6711 // "If both the operands have structure or union type, the result has 6712 // that type." This implies that CV qualifiers are dropped. 6713 return LHSTy.getUnqualifiedType(); 6714 // FIXME: Type of conditional expression must be complete in C mode. 6715 } 6716 6717 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6718 // The following || allows only one side to be void (a GCC-ism). 6719 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6720 return checkConditionalVoidType(*this, LHS, RHS); 6721 } 6722 6723 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6724 // the type of the other operand." 6725 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6726 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6727 6728 // All objective-c pointer type analysis is done here. 6729 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6730 QuestionLoc); 6731 if (LHS.isInvalid() || RHS.isInvalid()) 6732 return QualType(); 6733 if (!compositeType.isNull()) 6734 return compositeType; 6735 6736 6737 // Handle block pointer types. 6738 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6739 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6740 QuestionLoc); 6741 6742 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6743 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6744 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6745 QuestionLoc); 6746 6747 // GCC compatibility: soften pointer/integer mismatch. Note that 6748 // null pointers have been filtered out by this point. 6749 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6750 /*isIntFirstExpr=*/true)) 6751 return RHSTy; 6752 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6753 /*isIntFirstExpr=*/false)) 6754 return LHSTy; 6755 6756 // Emit a better diagnostic if one of the expressions is a null pointer 6757 // constant and the other is not a pointer type. In this case, the user most 6758 // likely forgot to take the address of the other expression. 6759 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6760 return QualType(); 6761 6762 // Otherwise, the operands are not compatible. 6763 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6764 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6765 << RHS.get()->getSourceRange(); 6766 return QualType(); 6767 } 6768 6769 /// FindCompositeObjCPointerType - Helper method to find composite type of 6770 /// two objective-c pointer types of the two input expressions. 6771 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6772 SourceLocation QuestionLoc) { 6773 QualType LHSTy = LHS.get()->getType(); 6774 QualType RHSTy = RHS.get()->getType(); 6775 6776 // Handle things like Class and struct objc_class*. Here we case the result 6777 // to the pseudo-builtin, because that will be implicitly cast back to the 6778 // redefinition type if an attempt is made to access its fields. 6779 if (LHSTy->isObjCClassType() && 6780 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6781 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6782 return LHSTy; 6783 } 6784 if (RHSTy->isObjCClassType() && 6785 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6786 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6787 return RHSTy; 6788 } 6789 // And the same for struct objc_object* / id 6790 if (LHSTy->isObjCIdType() && 6791 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6792 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6793 return LHSTy; 6794 } 6795 if (RHSTy->isObjCIdType() && 6796 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6797 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6798 return RHSTy; 6799 } 6800 // And the same for struct objc_selector* / SEL 6801 if (Context.isObjCSelType(LHSTy) && 6802 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6803 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6804 return LHSTy; 6805 } 6806 if (Context.isObjCSelType(RHSTy) && 6807 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6808 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6809 return RHSTy; 6810 } 6811 // Check constraints for Objective-C object pointers types. 6812 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6813 6814 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6815 // Two identical object pointer types are always compatible. 6816 return LHSTy; 6817 } 6818 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6819 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6820 QualType compositeType = LHSTy; 6821 6822 // If both operands are interfaces and either operand can be 6823 // assigned to the other, use that type as the composite 6824 // type. This allows 6825 // xxx ? (A*) a : (B*) b 6826 // where B is a subclass of A. 6827 // 6828 // Additionally, as for assignment, if either type is 'id' 6829 // allow silent coercion. Finally, if the types are 6830 // incompatible then make sure to use 'id' as the composite 6831 // type so the result is acceptable for sending messages to. 6832 6833 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6834 // It could return the composite type. 6835 if (!(compositeType = 6836 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6837 // Nothing more to do. 6838 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6839 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6840 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6841 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6842 } else if ((LHSTy->isObjCQualifiedIdType() || 6843 RHSTy->isObjCQualifiedIdType()) && 6844 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6845 // Need to handle "id<xx>" explicitly. 6846 // GCC allows qualified id and any Objective-C type to devolve to 6847 // id. Currently localizing to here until clear this should be 6848 // part of ObjCQualifiedIdTypesAreCompatible. 6849 compositeType = Context.getObjCIdType(); 6850 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6851 compositeType = Context.getObjCIdType(); 6852 } else { 6853 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6854 << LHSTy << RHSTy 6855 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6856 QualType incompatTy = Context.getObjCIdType(); 6857 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6858 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6859 return incompatTy; 6860 } 6861 // The object pointer types are compatible. 6862 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6863 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6864 return compositeType; 6865 } 6866 // Check Objective-C object pointer types and 'void *' 6867 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6868 if (getLangOpts().ObjCAutoRefCount) { 6869 // ARC forbids the implicit conversion of object pointers to 'void *', 6870 // so these types are not compatible. 6871 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6872 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6873 LHS = RHS = true; 6874 return QualType(); 6875 } 6876 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6877 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6878 QualType destPointee 6879 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6880 QualType destType = Context.getPointerType(destPointee); 6881 // Add qualifiers if necessary. 6882 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6883 // Promote to void*. 6884 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6885 return destType; 6886 } 6887 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6888 if (getLangOpts().ObjCAutoRefCount) { 6889 // ARC forbids the implicit conversion of object pointers to 'void *', 6890 // so these types are not compatible. 6891 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6893 LHS = RHS = true; 6894 return QualType(); 6895 } 6896 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6897 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6898 QualType destPointee 6899 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6900 QualType destType = Context.getPointerType(destPointee); 6901 // Add qualifiers if necessary. 6902 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6903 // Promote to void*. 6904 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6905 return destType; 6906 } 6907 return QualType(); 6908 } 6909 6910 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6911 /// ParenRange in parentheses. 6912 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6913 const PartialDiagnostic &Note, 6914 SourceRange ParenRange) { 6915 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6916 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6917 EndLoc.isValid()) { 6918 Self.Diag(Loc, Note) 6919 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6920 << FixItHint::CreateInsertion(EndLoc, ")"); 6921 } else { 6922 // We can't display the parentheses, so just show the bare note. 6923 Self.Diag(Loc, Note) << ParenRange; 6924 } 6925 } 6926 6927 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6928 return BinaryOperator::isAdditiveOp(Opc) || 6929 BinaryOperator::isMultiplicativeOp(Opc) || 6930 BinaryOperator::isShiftOp(Opc); 6931 } 6932 6933 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6934 /// expression, either using a built-in or overloaded operator, 6935 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6936 /// expression. 6937 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6938 Expr **RHSExprs) { 6939 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6940 E = E->IgnoreImpCasts(); 6941 E = E->IgnoreConversionOperator(); 6942 E = E->IgnoreImpCasts(); 6943 6944 // Built-in binary operator. 6945 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6946 if (IsArithmeticOp(OP->getOpcode())) { 6947 *Opcode = OP->getOpcode(); 6948 *RHSExprs = OP->getRHS(); 6949 return true; 6950 } 6951 } 6952 6953 // Overloaded operator. 6954 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6955 if (Call->getNumArgs() != 2) 6956 return false; 6957 6958 // Make sure this is really a binary operator that is safe to pass into 6959 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6960 OverloadedOperatorKind OO = Call->getOperator(); 6961 if (OO < OO_Plus || OO > OO_Arrow || 6962 OO == OO_PlusPlus || OO == OO_MinusMinus) 6963 return false; 6964 6965 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6966 if (IsArithmeticOp(OpKind)) { 6967 *Opcode = OpKind; 6968 *RHSExprs = Call->getArg(1); 6969 return true; 6970 } 6971 } 6972 6973 return false; 6974 } 6975 6976 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6977 /// or is a logical expression such as (x==y) which has int type, but is 6978 /// commonly interpreted as boolean. 6979 static bool ExprLooksBoolean(Expr *E) { 6980 E = E->IgnoreParenImpCasts(); 6981 6982 if (E->getType()->isBooleanType()) 6983 return true; 6984 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6985 return OP->isComparisonOp() || OP->isLogicalOp(); 6986 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6987 return OP->getOpcode() == UO_LNot; 6988 if (E->getType()->isPointerType()) 6989 return true; 6990 6991 return false; 6992 } 6993 6994 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6995 /// and binary operator are mixed in a way that suggests the programmer assumed 6996 /// the conditional operator has higher precedence, for example: 6997 /// "int x = a + someBinaryCondition ? 1 : 2". 6998 static void DiagnoseConditionalPrecedence(Sema &Self, 6999 SourceLocation OpLoc, 7000 Expr *Condition, 7001 Expr *LHSExpr, 7002 Expr *RHSExpr) { 7003 BinaryOperatorKind CondOpcode; 7004 Expr *CondRHS; 7005 7006 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7007 return; 7008 if (!ExprLooksBoolean(CondRHS)) 7009 return; 7010 7011 // The condition is an arithmetic binary expression, with a right- 7012 // hand side that looks boolean, so warn. 7013 7014 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7015 << Condition->getSourceRange() 7016 << BinaryOperator::getOpcodeStr(CondOpcode); 7017 7018 SuggestParentheses(Self, OpLoc, 7019 Self.PDiag(diag::note_precedence_silence) 7020 << BinaryOperator::getOpcodeStr(CondOpcode), 7021 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7022 7023 SuggestParentheses(Self, OpLoc, 7024 Self.PDiag(diag::note_precedence_conditional_first), 7025 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7026 } 7027 7028 /// Compute the nullability of a conditional expression. 7029 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7030 QualType LHSTy, QualType RHSTy, 7031 ASTContext &Ctx) { 7032 if (!ResTy->isAnyPointerType()) 7033 return ResTy; 7034 7035 auto GetNullability = [&Ctx](QualType Ty) { 7036 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7037 if (Kind) 7038 return *Kind; 7039 return NullabilityKind::Unspecified; 7040 }; 7041 7042 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7043 NullabilityKind MergedKind; 7044 7045 // Compute nullability of a binary conditional expression. 7046 if (IsBin) { 7047 if (LHSKind == NullabilityKind::NonNull) 7048 MergedKind = NullabilityKind::NonNull; 7049 else 7050 MergedKind = RHSKind; 7051 // Compute nullability of a normal conditional expression. 7052 } else { 7053 if (LHSKind == NullabilityKind::Nullable || 7054 RHSKind == NullabilityKind::Nullable) 7055 MergedKind = NullabilityKind::Nullable; 7056 else if (LHSKind == NullabilityKind::NonNull) 7057 MergedKind = RHSKind; 7058 else if (RHSKind == NullabilityKind::NonNull) 7059 MergedKind = LHSKind; 7060 else 7061 MergedKind = NullabilityKind::Unspecified; 7062 } 7063 7064 // Return if ResTy already has the correct nullability. 7065 if (GetNullability(ResTy) == MergedKind) 7066 return ResTy; 7067 7068 // Strip all nullability from ResTy. 7069 while (ResTy->getNullability(Ctx)) 7070 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7071 7072 // Create a new AttributedType with the new nullability kind. 7073 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7074 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7075 } 7076 7077 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7078 /// in the case of a the GNU conditional expr extension. 7079 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7080 SourceLocation ColonLoc, 7081 Expr *CondExpr, Expr *LHSExpr, 7082 Expr *RHSExpr) { 7083 if (!getLangOpts().CPlusPlus) { 7084 // C cannot handle TypoExpr nodes in the condition because it 7085 // doesn't handle dependent types properly, so make sure any TypoExprs have 7086 // been dealt with before checking the operands. 7087 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7088 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7089 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7090 7091 if (!CondResult.isUsable()) 7092 return ExprError(); 7093 7094 if (LHSExpr) { 7095 if (!LHSResult.isUsable()) 7096 return ExprError(); 7097 } 7098 7099 if (!RHSResult.isUsable()) 7100 return ExprError(); 7101 7102 CondExpr = CondResult.get(); 7103 LHSExpr = LHSResult.get(); 7104 RHSExpr = RHSResult.get(); 7105 } 7106 7107 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7108 // was the condition. 7109 OpaqueValueExpr *opaqueValue = nullptr; 7110 Expr *commonExpr = nullptr; 7111 if (!LHSExpr) { 7112 commonExpr = CondExpr; 7113 // Lower out placeholder types first. This is important so that we don't 7114 // try to capture a placeholder. This happens in few cases in C++; such 7115 // as Objective-C++'s dictionary subscripting syntax. 7116 if (commonExpr->hasPlaceholderType()) { 7117 ExprResult result = CheckPlaceholderExpr(commonExpr); 7118 if (!result.isUsable()) return ExprError(); 7119 commonExpr = result.get(); 7120 } 7121 // We usually want to apply unary conversions *before* saving, except 7122 // in the special case of a C++ l-value conditional. 7123 if (!(getLangOpts().CPlusPlus 7124 && !commonExpr->isTypeDependent() 7125 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7126 && commonExpr->isGLValue() 7127 && commonExpr->isOrdinaryOrBitFieldObject() 7128 && RHSExpr->isOrdinaryOrBitFieldObject() 7129 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7130 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7131 if (commonRes.isInvalid()) 7132 return ExprError(); 7133 commonExpr = commonRes.get(); 7134 } 7135 7136 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7137 commonExpr->getType(), 7138 commonExpr->getValueKind(), 7139 commonExpr->getObjectKind(), 7140 commonExpr); 7141 LHSExpr = CondExpr = opaqueValue; 7142 } 7143 7144 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7145 ExprValueKind VK = VK_RValue; 7146 ExprObjectKind OK = OK_Ordinary; 7147 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7148 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7149 VK, OK, QuestionLoc); 7150 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7151 RHS.isInvalid()) 7152 return ExprError(); 7153 7154 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7155 RHS.get()); 7156 7157 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7158 7159 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7160 Context); 7161 7162 if (!commonExpr) 7163 return new (Context) 7164 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7165 RHS.get(), result, VK, OK); 7166 7167 return new (Context) BinaryConditionalOperator( 7168 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7169 ColonLoc, result, VK, OK); 7170 } 7171 7172 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7173 // being closely modeled after the C99 spec:-). The odd characteristic of this 7174 // routine is it effectively iqnores the qualifiers on the top level pointee. 7175 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7176 // FIXME: add a couple examples in this comment. 7177 static Sema::AssignConvertType 7178 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7179 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7180 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7181 7182 // get the "pointed to" type (ignoring qualifiers at the top level) 7183 const Type *lhptee, *rhptee; 7184 Qualifiers lhq, rhq; 7185 std::tie(lhptee, lhq) = 7186 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7187 std::tie(rhptee, rhq) = 7188 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7189 7190 Sema::AssignConvertType ConvTy = Sema::Compatible; 7191 7192 // C99 6.5.16.1p1: This following citation is common to constraints 7193 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7194 // qualifiers of the type *pointed to* by the right; 7195 7196 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7197 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7198 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7199 // Ignore lifetime for further calculation. 7200 lhq.removeObjCLifetime(); 7201 rhq.removeObjCLifetime(); 7202 } 7203 7204 if (!lhq.compatiblyIncludes(rhq)) { 7205 // Treat address-space mismatches as fatal. TODO: address subspaces 7206 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7207 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7208 7209 // It's okay to add or remove GC or lifetime qualifiers when converting to 7210 // and from void*. 7211 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7212 .compatiblyIncludes( 7213 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7214 && (lhptee->isVoidType() || rhptee->isVoidType())) 7215 ; // keep old 7216 7217 // Treat lifetime mismatches as fatal. 7218 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7219 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7220 7221 // For GCC/MS compatibility, other qualifier mismatches are treated 7222 // as still compatible in C. 7223 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7224 } 7225 7226 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7227 // incomplete type and the other is a pointer to a qualified or unqualified 7228 // version of void... 7229 if (lhptee->isVoidType()) { 7230 if (rhptee->isIncompleteOrObjectType()) 7231 return ConvTy; 7232 7233 // As an extension, we allow cast to/from void* to function pointer. 7234 assert(rhptee->isFunctionType()); 7235 return Sema::FunctionVoidPointer; 7236 } 7237 7238 if (rhptee->isVoidType()) { 7239 if (lhptee->isIncompleteOrObjectType()) 7240 return ConvTy; 7241 7242 // As an extension, we allow cast to/from void* to function pointer. 7243 assert(lhptee->isFunctionType()); 7244 return Sema::FunctionVoidPointer; 7245 } 7246 7247 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7248 // unqualified versions of compatible types, ... 7249 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7250 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7251 // Check if the pointee types are compatible ignoring the sign. 7252 // We explicitly check for char so that we catch "char" vs 7253 // "unsigned char" on systems where "char" is unsigned. 7254 if (lhptee->isCharType()) 7255 ltrans = S.Context.UnsignedCharTy; 7256 else if (lhptee->hasSignedIntegerRepresentation()) 7257 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7258 7259 if (rhptee->isCharType()) 7260 rtrans = S.Context.UnsignedCharTy; 7261 else if (rhptee->hasSignedIntegerRepresentation()) 7262 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7263 7264 if (ltrans == rtrans) { 7265 // Types are compatible ignoring the sign. Qualifier incompatibility 7266 // takes priority over sign incompatibility because the sign 7267 // warning can be disabled. 7268 if (ConvTy != Sema::Compatible) 7269 return ConvTy; 7270 7271 return Sema::IncompatiblePointerSign; 7272 } 7273 7274 // If we are a multi-level pointer, it's possible that our issue is simply 7275 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7276 // the eventual target type is the same and the pointers have the same 7277 // level of indirection, this must be the issue. 7278 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7279 do { 7280 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7281 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7282 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7283 7284 if (lhptee == rhptee) 7285 return Sema::IncompatibleNestedPointerQualifiers; 7286 } 7287 7288 // General pointer incompatibility takes priority over qualifiers. 7289 return Sema::IncompatiblePointer; 7290 } 7291 if (!S.getLangOpts().CPlusPlus && 7292 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7293 return Sema::IncompatiblePointer; 7294 return ConvTy; 7295 } 7296 7297 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7298 /// block pointer types are compatible or whether a block and normal pointer 7299 /// are compatible. It is more restrict than comparing two function pointer 7300 // types. 7301 static Sema::AssignConvertType 7302 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7303 QualType RHSType) { 7304 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7305 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7306 7307 QualType lhptee, rhptee; 7308 7309 // get the "pointed to" type (ignoring qualifiers at the top level) 7310 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7311 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7312 7313 // In C++, the types have to match exactly. 7314 if (S.getLangOpts().CPlusPlus) 7315 return Sema::IncompatibleBlockPointer; 7316 7317 Sema::AssignConvertType ConvTy = Sema::Compatible; 7318 7319 // For blocks we enforce that qualifiers are identical. 7320 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7321 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7322 7323 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7324 return Sema::IncompatibleBlockPointer; 7325 7326 return ConvTy; 7327 } 7328 7329 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7330 /// for assignment compatibility. 7331 static Sema::AssignConvertType 7332 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7333 QualType RHSType) { 7334 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7335 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7336 7337 if (LHSType->isObjCBuiltinType()) { 7338 // Class is not compatible with ObjC object pointers. 7339 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7340 !RHSType->isObjCQualifiedClassType()) 7341 return Sema::IncompatiblePointer; 7342 return Sema::Compatible; 7343 } 7344 if (RHSType->isObjCBuiltinType()) { 7345 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7346 !LHSType->isObjCQualifiedClassType()) 7347 return Sema::IncompatiblePointer; 7348 return Sema::Compatible; 7349 } 7350 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7351 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7352 7353 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7354 // make an exception for id<P> 7355 !LHSType->isObjCQualifiedIdType()) 7356 return Sema::CompatiblePointerDiscardsQualifiers; 7357 7358 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7359 return Sema::Compatible; 7360 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7361 return Sema::IncompatibleObjCQualifiedId; 7362 return Sema::IncompatiblePointer; 7363 } 7364 7365 Sema::AssignConvertType 7366 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7367 QualType LHSType, QualType RHSType) { 7368 // Fake up an opaque expression. We don't actually care about what 7369 // cast operations are required, so if CheckAssignmentConstraints 7370 // adds casts to this they'll be wasted, but fortunately that doesn't 7371 // usually happen on valid code. 7372 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7373 ExprResult RHSPtr = &RHSExpr; 7374 CastKind K = CK_Invalid; 7375 7376 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7377 } 7378 7379 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7380 /// has code to accommodate several GCC extensions when type checking 7381 /// pointers. Here are some objectionable examples that GCC considers warnings: 7382 /// 7383 /// int a, *pint; 7384 /// short *pshort; 7385 /// struct foo *pfoo; 7386 /// 7387 /// pint = pshort; // warning: assignment from incompatible pointer type 7388 /// a = pint; // warning: assignment makes integer from pointer without a cast 7389 /// pint = a; // warning: assignment makes pointer from integer without a cast 7390 /// pint = pfoo; // warning: assignment from incompatible pointer type 7391 /// 7392 /// As a result, the code for dealing with pointers is more complex than the 7393 /// C99 spec dictates. 7394 /// 7395 /// Sets 'Kind' for any result kind except Incompatible. 7396 Sema::AssignConvertType 7397 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7398 CastKind &Kind, bool ConvertRHS) { 7399 QualType RHSType = RHS.get()->getType(); 7400 QualType OrigLHSType = LHSType; 7401 7402 // Get canonical types. We're not formatting these types, just comparing 7403 // them. 7404 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7405 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7406 7407 // Common case: no conversion required. 7408 if (LHSType == RHSType) { 7409 Kind = CK_NoOp; 7410 return Compatible; 7411 } 7412 7413 // If we have an atomic type, try a non-atomic assignment, then just add an 7414 // atomic qualification step. 7415 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7416 Sema::AssignConvertType result = 7417 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7418 if (result != Compatible) 7419 return result; 7420 if (Kind != CK_NoOp && ConvertRHS) 7421 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7422 Kind = CK_NonAtomicToAtomic; 7423 return Compatible; 7424 } 7425 7426 // If the left-hand side is a reference type, then we are in a 7427 // (rare!) case where we've allowed the use of references in C, 7428 // e.g., as a parameter type in a built-in function. In this case, 7429 // just make sure that the type referenced is compatible with the 7430 // right-hand side type. The caller is responsible for adjusting 7431 // LHSType so that the resulting expression does not have reference 7432 // type. 7433 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7434 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7435 Kind = CK_LValueBitCast; 7436 return Compatible; 7437 } 7438 return Incompatible; 7439 } 7440 7441 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7442 // to the same ExtVector type. 7443 if (LHSType->isExtVectorType()) { 7444 if (RHSType->isExtVectorType()) 7445 return Incompatible; 7446 if (RHSType->isArithmeticType()) { 7447 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7448 if (ConvertRHS) 7449 RHS = prepareVectorSplat(LHSType, RHS.get()); 7450 Kind = CK_VectorSplat; 7451 return Compatible; 7452 } 7453 } 7454 7455 // Conversions to or from vector type. 7456 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7457 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7458 // Allow assignments of an AltiVec vector type to an equivalent GCC 7459 // vector type and vice versa 7460 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7461 Kind = CK_BitCast; 7462 return Compatible; 7463 } 7464 7465 // If we are allowing lax vector conversions, and LHS and RHS are both 7466 // vectors, the total size only needs to be the same. This is a bitcast; 7467 // no bits are changed but the result type is different. 7468 if (isLaxVectorConversion(RHSType, LHSType)) { 7469 Kind = CK_BitCast; 7470 return IncompatibleVectors; 7471 } 7472 } 7473 7474 // When the RHS comes from another lax conversion (e.g. binops between 7475 // scalars and vectors) the result is canonicalized as a vector. When the 7476 // LHS is also a vector, the lax is allowed by the condition above. Handle 7477 // the case where LHS is a scalar. 7478 if (LHSType->isScalarType()) { 7479 const VectorType *VecType = RHSType->getAs<VectorType>(); 7480 if (VecType && VecType->getNumElements() == 1 && 7481 isLaxVectorConversion(RHSType, LHSType)) { 7482 ExprResult *VecExpr = &RHS; 7483 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7484 Kind = CK_BitCast; 7485 return Compatible; 7486 } 7487 } 7488 7489 return Incompatible; 7490 } 7491 7492 // Diagnose attempts to convert between __float128 and long double where 7493 // such conversions currently can't be handled. 7494 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7495 return Incompatible; 7496 7497 // Arithmetic conversions. 7498 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7499 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7500 if (ConvertRHS) 7501 Kind = PrepareScalarCast(RHS, LHSType); 7502 return Compatible; 7503 } 7504 7505 // Conversions to normal pointers. 7506 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7507 // U* -> T* 7508 if (isa<PointerType>(RHSType)) { 7509 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7510 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7511 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7512 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7513 } 7514 7515 // int -> T* 7516 if (RHSType->isIntegerType()) { 7517 Kind = CK_IntegralToPointer; // FIXME: null? 7518 return IntToPointer; 7519 } 7520 7521 // C pointers are not compatible with ObjC object pointers, 7522 // with two exceptions: 7523 if (isa<ObjCObjectPointerType>(RHSType)) { 7524 // - conversions to void* 7525 if (LHSPointer->getPointeeType()->isVoidType()) { 7526 Kind = CK_BitCast; 7527 return Compatible; 7528 } 7529 7530 // - conversions from 'Class' to the redefinition type 7531 if (RHSType->isObjCClassType() && 7532 Context.hasSameType(LHSType, 7533 Context.getObjCClassRedefinitionType())) { 7534 Kind = CK_BitCast; 7535 return Compatible; 7536 } 7537 7538 Kind = CK_BitCast; 7539 return IncompatiblePointer; 7540 } 7541 7542 // U^ -> void* 7543 if (RHSType->getAs<BlockPointerType>()) { 7544 if (LHSPointer->getPointeeType()->isVoidType()) { 7545 Kind = CK_BitCast; 7546 return Compatible; 7547 } 7548 } 7549 7550 return Incompatible; 7551 } 7552 7553 // Conversions to block pointers. 7554 if (isa<BlockPointerType>(LHSType)) { 7555 // U^ -> T^ 7556 if (RHSType->isBlockPointerType()) { 7557 Kind = CK_BitCast; 7558 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7559 } 7560 7561 // int or null -> T^ 7562 if (RHSType->isIntegerType()) { 7563 Kind = CK_IntegralToPointer; // FIXME: null 7564 return IntToBlockPointer; 7565 } 7566 7567 // id -> T^ 7568 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7569 Kind = CK_AnyPointerToBlockPointerCast; 7570 return Compatible; 7571 } 7572 7573 // void* -> T^ 7574 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7575 if (RHSPT->getPointeeType()->isVoidType()) { 7576 Kind = CK_AnyPointerToBlockPointerCast; 7577 return Compatible; 7578 } 7579 7580 return Incompatible; 7581 } 7582 7583 // Conversions to Objective-C pointers. 7584 if (isa<ObjCObjectPointerType>(LHSType)) { 7585 // A* -> B* 7586 if (RHSType->isObjCObjectPointerType()) { 7587 Kind = CK_BitCast; 7588 Sema::AssignConvertType result = 7589 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7590 if (getLangOpts().ObjCAutoRefCount && 7591 result == Compatible && 7592 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7593 result = IncompatibleObjCWeakRef; 7594 return result; 7595 } 7596 7597 // int or null -> A* 7598 if (RHSType->isIntegerType()) { 7599 Kind = CK_IntegralToPointer; // FIXME: null 7600 return IntToPointer; 7601 } 7602 7603 // In general, C pointers are not compatible with ObjC object pointers, 7604 // with two exceptions: 7605 if (isa<PointerType>(RHSType)) { 7606 Kind = CK_CPointerToObjCPointerCast; 7607 7608 // - conversions from 'void*' 7609 if (RHSType->isVoidPointerType()) { 7610 return Compatible; 7611 } 7612 7613 // - conversions to 'Class' from its redefinition type 7614 if (LHSType->isObjCClassType() && 7615 Context.hasSameType(RHSType, 7616 Context.getObjCClassRedefinitionType())) { 7617 return Compatible; 7618 } 7619 7620 return IncompatiblePointer; 7621 } 7622 7623 // Only under strict condition T^ is compatible with an Objective-C pointer. 7624 if (RHSType->isBlockPointerType() && 7625 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7626 if (ConvertRHS) 7627 maybeExtendBlockObject(RHS); 7628 Kind = CK_BlockPointerToObjCPointerCast; 7629 return Compatible; 7630 } 7631 7632 return Incompatible; 7633 } 7634 7635 // Conversions from pointers that are not covered by the above. 7636 if (isa<PointerType>(RHSType)) { 7637 // T* -> _Bool 7638 if (LHSType == Context.BoolTy) { 7639 Kind = CK_PointerToBoolean; 7640 return Compatible; 7641 } 7642 7643 // T* -> int 7644 if (LHSType->isIntegerType()) { 7645 Kind = CK_PointerToIntegral; 7646 return PointerToInt; 7647 } 7648 7649 return Incompatible; 7650 } 7651 7652 // Conversions from Objective-C pointers that are not covered by the above. 7653 if (isa<ObjCObjectPointerType>(RHSType)) { 7654 // T* -> _Bool 7655 if (LHSType == Context.BoolTy) { 7656 Kind = CK_PointerToBoolean; 7657 return Compatible; 7658 } 7659 7660 // T* -> int 7661 if (LHSType->isIntegerType()) { 7662 Kind = CK_PointerToIntegral; 7663 return PointerToInt; 7664 } 7665 7666 return Incompatible; 7667 } 7668 7669 // struct A -> struct B 7670 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7671 if (Context.typesAreCompatible(LHSType, RHSType)) { 7672 Kind = CK_NoOp; 7673 return Compatible; 7674 } 7675 } 7676 7677 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7678 Kind = CK_IntToOCLSampler; 7679 return Compatible; 7680 } 7681 7682 return Incompatible; 7683 } 7684 7685 /// \brief Constructs a transparent union from an expression that is 7686 /// used to initialize the transparent union. 7687 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7688 ExprResult &EResult, QualType UnionType, 7689 FieldDecl *Field) { 7690 // Build an initializer list that designates the appropriate member 7691 // of the transparent union. 7692 Expr *E = EResult.get(); 7693 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7694 E, SourceLocation()); 7695 Initializer->setType(UnionType); 7696 Initializer->setInitializedFieldInUnion(Field); 7697 7698 // Build a compound literal constructing a value of the transparent 7699 // union type from this initializer list. 7700 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7701 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7702 VK_RValue, Initializer, false); 7703 } 7704 7705 Sema::AssignConvertType 7706 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7707 ExprResult &RHS) { 7708 QualType RHSType = RHS.get()->getType(); 7709 7710 // If the ArgType is a Union type, we want to handle a potential 7711 // transparent_union GCC extension. 7712 const RecordType *UT = ArgType->getAsUnionType(); 7713 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7714 return Incompatible; 7715 7716 // The field to initialize within the transparent union. 7717 RecordDecl *UD = UT->getDecl(); 7718 FieldDecl *InitField = nullptr; 7719 // It's compatible if the expression matches any of the fields. 7720 for (auto *it : UD->fields()) { 7721 if (it->getType()->isPointerType()) { 7722 // If the transparent union contains a pointer type, we allow: 7723 // 1) void pointer 7724 // 2) null pointer constant 7725 if (RHSType->isPointerType()) 7726 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7727 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7728 InitField = it; 7729 break; 7730 } 7731 7732 if (RHS.get()->isNullPointerConstant(Context, 7733 Expr::NPC_ValueDependentIsNull)) { 7734 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7735 CK_NullToPointer); 7736 InitField = it; 7737 break; 7738 } 7739 } 7740 7741 CastKind Kind = CK_Invalid; 7742 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7743 == Compatible) { 7744 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7745 InitField = it; 7746 break; 7747 } 7748 } 7749 7750 if (!InitField) 7751 return Incompatible; 7752 7753 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7754 return Compatible; 7755 } 7756 7757 Sema::AssignConvertType 7758 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7759 bool Diagnose, 7760 bool DiagnoseCFAudited, 7761 bool ConvertRHS) { 7762 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7763 // we can't avoid *all* modifications at the moment, so we need some somewhere 7764 // to put the updated value. 7765 ExprResult LocalRHS = CallerRHS; 7766 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7767 7768 if (getLangOpts().CPlusPlus) { 7769 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7770 // C++ 5.17p3: If the left operand is not of class type, the 7771 // expression is implicitly converted (C++ 4) to the 7772 // cv-unqualified type of the left operand. 7773 ExprResult Res; 7774 if (Diagnose) { 7775 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7776 AA_Assigning); 7777 } else { 7778 ImplicitConversionSequence ICS = 7779 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7780 /*SuppressUserConversions=*/false, 7781 /*AllowExplicit=*/false, 7782 /*InOverloadResolution=*/false, 7783 /*CStyle=*/false, 7784 /*AllowObjCWritebackConversion=*/false); 7785 if (ICS.isFailure()) 7786 return Incompatible; 7787 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7788 ICS, AA_Assigning); 7789 } 7790 if (Res.isInvalid()) 7791 return Incompatible; 7792 Sema::AssignConvertType result = Compatible; 7793 if (getLangOpts().ObjCAutoRefCount && 7794 !CheckObjCARCUnavailableWeakConversion(LHSType, 7795 RHS.get()->getType())) 7796 result = IncompatibleObjCWeakRef; 7797 RHS = Res; 7798 return result; 7799 } 7800 7801 // FIXME: Currently, we fall through and treat C++ classes like C 7802 // structures. 7803 // FIXME: We also fall through for atomics; not sure what should 7804 // happen there, though. 7805 } else if (RHS.get()->getType() == Context.OverloadTy) { 7806 // As a set of extensions to C, we support overloading on functions. These 7807 // functions need to be resolved here. 7808 DeclAccessPair DAP; 7809 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7810 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7811 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7812 else 7813 return Incompatible; 7814 } 7815 7816 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7817 // a null pointer constant. 7818 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7819 LHSType->isBlockPointerType()) && 7820 RHS.get()->isNullPointerConstant(Context, 7821 Expr::NPC_ValueDependentIsNull)) { 7822 if (Diagnose || ConvertRHS) { 7823 CastKind Kind; 7824 CXXCastPath Path; 7825 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7826 /*IgnoreBaseAccess=*/false, Diagnose); 7827 if (ConvertRHS) 7828 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7829 } 7830 return Compatible; 7831 } 7832 7833 // This check seems unnatural, however it is necessary to ensure the proper 7834 // conversion of functions/arrays. If the conversion were done for all 7835 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7836 // expressions that suppress this implicit conversion (&, sizeof). 7837 // 7838 // Suppress this for references: C++ 8.5.3p5. 7839 if (!LHSType->isReferenceType()) { 7840 // FIXME: We potentially allocate here even if ConvertRHS is false. 7841 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7842 if (RHS.isInvalid()) 7843 return Incompatible; 7844 } 7845 7846 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7847 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7848 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7849 if (PDecl && !PDecl->hasDefinition()) { 7850 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7851 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7852 } 7853 } 7854 7855 CastKind Kind = CK_Invalid; 7856 Sema::AssignConvertType result = 7857 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7858 7859 // C99 6.5.16.1p2: The value of the right operand is converted to the 7860 // type of the assignment expression. 7861 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7862 // so that we can use references in built-in functions even in C. 7863 // The getNonReferenceType() call makes sure that the resulting expression 7864 // does not have reference type. 7865 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7866 QualType Ty = LHSType.getNonLValueExprType(Context); 7867 Expr *E = RHS.get(); 7868 7869 // Check for various Objective-C errors. If we are not reporting 7870 // diagnostics and just checking for errors, e.g., during overload 7871 // resolution, return Incompatible to indicate the failure. 7872 if (getLangOpts().ObjCAutoRefCount && 7873 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7874 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7875 if (!Diagnose) 7876 return Incompatible; 7877 } 7878 if (getLangOpts().ObjC1 && 7879 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7880 E->getType(), E, Diagnose) || 7881 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7882 if (!Diagnose) 7883 return Incompatible; 7884 // Replace the expression with a corrected version and continue so we 7885 // can find further errors. 7886 RHS = E; 7887 return Compatible; 7888 } 7889 7890 if (ConvertRHS) 7891 RHS = ImpCastExprToType(E, Ty, Kind); 7892 } 7893 return result; 7894 } 7895 7896 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7897 ExprResult &RHS) { 7898 Diag(Loc, diag::err_typecheck_invalid_operands) 7899 << LHS.get()->getType() << RHS.get()->getType() 7900 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7901 return QualType(); 7902 } 7903 7904 /// Try to convert a value of non-vector type to a vector type by converting 7905 /// the type to the element type of the vector and then performing a splat. 7906 /// If the language is OpenCL, we only use conversions that promote scalar 7907 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7908 /// for float->int. 7909 /// 7910 /// \param scalar - if non-null, actually perform the conversions 7911 /// \return true if the operation fails (but without diagnosing the failure) 7912 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7913 QualType scalarTy, 7914 QualType vectorEltTy, 7915 QualType vectorTy) { 7916 // The conversion to apply to the scalar before splatting it, 7917 // if necessary. 7918 CastKind scalarCast = CK_Invalid; 7919 7920 if (vectorEltTy->isIntegralType(S.Context)) { 7921 if (!scalarTy->isIntegralType(S.Context)) 7922 return true; 7923 if (S.getLangOpts().OpenCL && 7924 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7925 return true; 7926 scalarCast = CK_IntegralCast; 7927 } else if (vectorEltTy->isRealFloatingType()) { 7928 if (scalarTy->isRealFloatingType()) { 7929 if (S.getLangOpts().OpenCL && 7930 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7931 return true; 7932 scalarCast = CK_FloatingCast; 7933 } 7934 else if (scalarTy->isIntegralType(S.Context)) 7935 scalarCast = CK_IntegralToFloating; 7936 else 7937 return true; 7938 } else { 7939 return true; 7940 } 7941 7942 // Adjust scalar if desired. 7943 if (scalar) { 7944 if (scalarCast != CK_Invalid) 7945 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7946 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7947 } 7948 return false; 7949 } 7950 7951 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7952 SourceLocation Loc, bool IsCompAssign, 7953 bool AllowBothBool, 7954 bool AllowBoolConversions) { 7955 if (!IsCompAssign) { 7956 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7957 if (LHS.isInvalid()) 7958 return QualType(); 7959 } 7960 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7961 if (RHS.isInvalid()) 7962 return QualType(); 7963 7964 // For conversion purposes, we ignore any qualifiers. 7965 // For example, "const float" and "float" are equivalent. 7966 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7967 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7968 7969 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7970 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7971 assert(LHSVecType || RHSVecType); 7972 7973 // AltiVec-style "vector bool op vector bool" combinations are allowed 7974 // for some operators but not others. 7975 if (!AllowBothBool && 7976 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7977 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7978 return InvalidOperands(Loc, LHS, RHS); 7979 7980 // If the vector types are identical, return. 7981 if (Context.hasSameType(LHSType, RHSType)) 7982 return LHSType; 7983 7984 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7985 if (LHSVecType && RHSVecType && 7986 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7987 if (isa<ExtVectorType>(LHSVecType)) { 7988 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7989 return LHSType; 7990 } 7991 7992 if (!IsCompAssign) 7993 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7994 return RHSType; 7995 } 7996 7997 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7998 // can be mixed, with the result being the non-bool type. The non-bool 7999 // operand must have integer element type. 8000 if (AllowBoolConversions && LHSVecType && RHSVecType && 8001 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8002 (Context.getTypeSize(LHSVecType->getElementType()) == 8003 Context.getTypeSize(RHSVecType->getElementType()))) { 8004 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8005 LHSVecType->getElementType()->isIntegerType() && 8006 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8007 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8008 return LHSType; 8009 } 8010 if (!IsCompAssign && 8011 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8012 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8013 RHSVecType->getElementType()->isIntegerType()) { 8014 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8015 return RHSType; 8016 } 8017 } 8018 8019 // If there's an ext-vector type and a scalar, try to convert the scalar to 8020 // the vector element type and splat. 8021 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8022 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8023 LHSVecType->getElementType(), LHSType)) 8024 return LHSType; 8025 } 8026 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8027 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8028 LHSType, RHSVecType->getElementType(), 8029 RHSType)) 8030 return RHSType; 8031 } 8032 8033 // If we're allowing lax vector conversions, only the total (data) size needs 8034 // to be the same. If one of the types is scalar, the result is always the 8035 // vector type. Don't allow this if the scalar operand is an lvalue. 8036 QualType VecType = LHSVecType ? LHSType : RHSType; 8037 QualType ScalarType = LHSVecType ? RHSType : LHSType; 8038 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS; 8039 if (isLaxVectorConversion(ScalarType, VecType) && 8040 !ScalarExpr->get()->isLValue()) { 8041 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast); 8042 return VecType; 8043 } 8044 8045 // Okay, the expression is invalid. 8046 8047 // If there's a non-vector, non-real operand, diagnose that. 8048 if ((!RHSVecType && !RHSType->isRealType()) || 8049 (!LHSVecType && !LHSType->isRealType())) { 8050 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8051 << LHSType << RHSType 8052 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8053 return QualType(); 8054 } 8055 8056 // OpenCL V1.1 6.2.6.p1: 8057 // If the operands are of more than one vector type, then an error shall 8058 // occur. Implicit conversions between vector types are not permitted, per 8059 // section 6.2.1. 8060 if (getLangOpts().OpenCL && 8061 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8062 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8063 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8064 << RHSType; 8065 return QualType(); 8066 } 8067 8068 // Otherwise, use the generic diagnostic. 8069 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8070 << LHSType << RHSType 8071 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8072 return QualType(); 8073 } 8074 8075 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8076 // expression. These are mainly cases where the null pointer is used as an 8077 // integer instead of a pointer. 8078 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8079 SourceLocation Loc, bool IsCompare) { 8080 // The canonical way to check for a GNU null is with isNullPointerConstant, 8081 // but we use a bit of a hack here for speed; this is a relatively 8082 // hot path, and isNullPointerConstant is slow. 8083 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8084 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8085 8086 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8087 8088 // Avoid analyzing cases where the result will either be invalid (and 8089 // diagnosed as such) or entirely valid and not something to warn about. 8090 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8091 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8092 return; 8093 8094 // Comparison operations would not make sense with a null pointer no matter 8095 // what the other expression is. 8096 if (!IsCompare) { 8097 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8098 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8099 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8100 return; 8101 } 8102 8103 // The rest of the operations only make sense with a null pointer 8104 // if the other expression is a pointer. 8105 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8106 NonNullType->canDecayToPointerType()) 8107 return; 8108 8109 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8110 << LHSNull /* LHS is NULL */ << NonNullType 8111 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8112 } 8113 8114 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8115 ExprResult &RHS, 8116 SourceLocation Loc, bool IsDiv) { 8117 // Check for division/remainder by zero. 8118 llvm::APSInt RHSValue; 8119 if (!RHS.get()->isValueDependent() && 8120 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8121 S.DiagRuntimeBehavior(Loc, RHS.get(), 8122 S.PDiag(diag::warn_remainder_division_by_zero) 8123 << IsDiv << RHS.get()->getSourceRange()); 8124 } 8125 8126 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8127 SourceLocation Loc, 8128 bool IsCompAssign, bool IsDiv) { 8129 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8130 8131 if (LHS.get()->getType()->isVectorType() || 8132 RHS.get()->getType()->isVectorType()) 8133 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8134 /*AllowBothBool*/getLangOpts().AltiVec, 8135 /*AllowBoolConversions*/false); 8136 8137 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8138 if (LHS.isInvalid() || RHS.isInvalid()) 8139 return QualType(); 8140 8141 8142 if (compType.isNull() || !compType->isArithmeticType()) 8143 return InvalidOperands(Loc, LHS, RHS); 8144 if (IsDiv) 8145 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8146 return compType; 8147 } 8148 8149 QualType Sema::CheckRemainderOperands( 8150 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8151 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8152 8153 if (LHS.get()->getType()->isVectorType() || 8154 RHS.get()->getType()->isVectorType()) { 8155 if (LHS.get()->getType()->hasIntegerRepresentation() && 8156 RHS.get()->getType()->hasIntegerRepresentation()) 8157 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8158 /*AllowBothBool*/getLangOpts().AltiVec, 8159 /*AllowBoolConversions*/false); 8160 return InvalidOperands(Loc, LHS, RHS); 8161 } 8162 8163 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8164 if (LHS.isInvalid() || RHS.isInvalid()) 8165 return QualType(); 8166 8167 if (compType.isNull() || !compType->isIntegerType()) 8168 return InvalidOperands(Loc, LHS, RHS); 8169 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8170 return compType; 8171 } 8172 8173 /// \brief Diagnose invalid arithmetic on two void pointers. 8174 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8175 Expr *LHSExpr, Expr *RHSExpr) { 8176 S.Diag(Loc, S.getLangOpts().CPlusPlus 8177 ? diag::err_typecheck_pointer_arith_void_type 8178 : diag::ext_gnu_void_ptr) 8179 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8180 << RHSExpr->getSourceRange(); 8181 } 8182 8183 /// \brief Diagnose invalid arithmetic on a void pointer. 8184 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8185 Expr *Pointer) { 8186 S.Diag(Loc, S.getLangOpts().CPlusPlus 8187 ? diag::err_typecheck_pointer_arith_void_type 8188 : diag::ext_gnu_void_ptr) 8189 << 0 /* one pointer */ << Pointer->getSourceRange(); 8190 } 8191 8192 /// \brief Diagnose invalid arithmetic on two function pointers. 8193 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8194 Expr *LHS, Expr *RHS) { 8195 assert(LHS->getType()->isAnyPointerType()); 8196 assert(RHS->getType()->isAnyPointerType()); 8197 S.Diag(Loc, S.getLangOpts().CPlusPlus 8198 ? diag::err_typecheck_pointer_arith_function_type 8199 : diag::ext_gnu_ptr_func_arith) 8200 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8201 // We only show the second type if it differs from the first. 8202 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8203 RHS->getType()) 8204 << RHS->getType()->getPointeeType() 8205 << LHS->getSourceRange() << RHS->getSourceRange(); 8206 } 8207 8208 /// \brief Diagnose invalid arithmetic on a function pointer. 8209 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8210 Expr *Pointer) { 8211 assert(Pointer->getType()->isAnyPointerType()); 8212 S.Diag(Loc, S.getLangOpts().CPlusPlus 8213 ? diag::err_typecheck_pointer_arith_function_type 8214 : diag::ext_gnu_ptr_func_arith) 8215 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8216 << 0 /* one pointer, so only one type */ 8217 << Pointer->getSourceRange(); 8218 } 8219 8220 /// \brief Emit error if Operand is incomplete pointer type 8221 /// 8222 /// \returns True if pointer has incomplete type 8223 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8224 Expr *Operand) { 8225 QualType ResType = Operand->getType(); 8226 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8227 ResType = ResAtomicType->getValueType(); 8228 8229 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8230 QualType PointeeTy = ResType->getPointeeType(); 8231 return S.RequireCompleteType(Loc, PointeeTy, 8232 diag::err_typecheck_arithmetic_incomplete_type, 8233 PointeeTy, Operand->getSourceRange()); 8234 } 8235 8236 /// \brief Check the validity of an arithmetic pointer operand. 8237 /// 8238 /// If the operand has pointer type, this code will check for pointer types 8239 /// which are invalid in arithmetic operations. These will be diagnosed 8240 /// appropriately, including whether or not the use is supported as an 8241 /// extension. 8242 /// 8243 /// \returns True when the operand is valid to use (even if as an extension). 8244 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8245 Expr *Operand) { 8246 QualType ResType = Operand->getType(); 8247 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8248 ResType = ResAtomicType->getValueType(); 8249 8250 if (!ResType->isAnyPointerType()) return true; 8251 8252 QualType PointeeTy = ResType->getPointeeType(); 8253 if (PointeeTy->isVoidType()) { 8254 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8255 return !S.getLangOpts().CPlusPlus; 8256 } 8257 if (PointeeTy->isFunctionType()) { 8258 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8259 return !S.getLangOpts().CPlusPlus; 8260 } 8261 8262 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8263 8264 return true; 8265 } 8266 8267 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8268 /// operands. 8269 /// 8270 /// This routine will diagnose any invalid arithmetic on pointer operands much 8271 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8272 /// for emitting a single diagnostic even for operations where both LHS and RHS 8273 /// are (potentially problematic) pointers. 8274 /// 8275 /// \returns True when the operand is valid to use (even if as an extension). 8276 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8277 Expr *LHSExpr, Expr *RHSExpr) { 8278 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8279 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8280 if (!isLHSPointer && !isRHSPointer) return true; 8281 8282 QualType LHSPointeeTy, RHSPointeeTy; 8283 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8284 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8285 8286 // if both are pointers check if operation is valid wrt address spaces 8287 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8288 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8289 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8290 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8291 S.Diag(Loc, 8292 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8293 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8294 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8295 return false; 8296 } 8297 } 8298 8299 // Check for arithmetic on pointers to incomplete types. 8300 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8301 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8302 if (isLHSVoidPtr || isRHSVoidPtr) { 8303 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8304 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8305 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8306 8307 return !S.getLangOpts().CPlusPlus; 8308 } 8309 8310 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8311 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8312 if (isLHSFuncPtr || isRHSFuncPtr) { 8313 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8314 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8315 RHSExpr); 8316 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8317 8318 return !S.getLangOpts().CPlusPlus; 8319 } 8320 8321 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8322 return false; 8323 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8324 return false; 8325 8326 return true; 8327 } 8328 8329 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8330 /// literal. 8331 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8332 Expr *LHSExpr, Expr *RHSExpr) { 8333 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8334 Expr* IndexExpr = RHSExpr; 8335 if (!StrExpr) { 8336 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8337 IndexExpr = LHSExpr; 8338 } 8339 8340 bool IsStringPlusInt = StrExpr && 8341 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8342 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8343 return; 8344 8345 llvm::APSInt index; 8346 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8347 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8348 if (index.isNonNegative() && 8349 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8350 index.isUnsigned())) 8351 return; 8352 } 8353 8354 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8355 Self.Diag(OpLoc, diag::warn_string_plus_int) 8356 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8357 8358 // Only print a fixit for "str" + int, not for int + "str". 8359 if (IndexExpr == RHSExpr) { 8360 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8361 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8362 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8363 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8364 << FixItHint::CreateInsertion(EndLoc, "]"); 8365 } else 8366 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8367 } 8368 8369 /// \brief Emit a warning when adding a char literal to a string. 8370 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8371 Expr *LHSExpr, Expr *RHSExpr) { 8372 const Expr *StringRefExpr = LHSExpr; 8373 const CharacterLiteral *CharExpr = 8374 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8375 8376 if (!CharExpr) { 8377 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8378 StringRefExpr = RHSExpr; 8379 } 8380 8381 if (!CharExpr || !StringRefExpr) 8382 return; 8383 8384 const QualType StringType = StringRefExpr->getType(); 8385 8386 // Return if not a PointerType. 8387 if (!StringType->isAnyPointerType()) 8388 return; 8389 8390 // Return if not a CharacterType. 8391 if (!StringType->getPointeeType()->isAnyCharacterType()) 8392 return; 8393 8394 ASTContext &Ctx = Self.getASTContext(); 8395 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8396 8397 const QualType CharType = CharExpr->getType(); 8398 if (!CharType->isAnyCharacterType() && 8399 CharType->isIntegerType() && 8400 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8401 Self.Diag(OpLoc, diag::warn_string_plus_char) 8402 << DiagRange << Ctx.CharTy; 8403 } else { 8404 Self.Diag(OpLoc, diag::warn_string_plus_char) 8405 << DiagRange << CharExpr->getType(); 8406 } 8407 8408 // Only print a fixit for str + char, not for char + str. 8409 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8410 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8411 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8412 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8413 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8414 << FixItHint::CreateInsertion(EndLoc, "]"); 8415 } else { 8416 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8417 } 8418 } 8419 8420 /// \brief Emit error when two pointers are incompatible. 8421 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8422 Expr *LHSExpr, Expr *RHSExpr) { 8423 assert(LHSExpr->getType()->isAnyPointerType()); 8424 assert(RHSExpr->getType()->isAnyPointerType()); 8425 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8426 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8427 << RHSExpr->getSourceRange(); 8428 } 8429 8430 // C99 6.5.6 8431 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8432 SourceLocation Loc, BinaryOperatorKind Opc, 8433 QualType* CompLHSTy) { 8434 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8435 8436 if (LHS.get()->getType()->isVectorType() || 8437 RHS.get()->getType()->isVectorType()) { 8438 QualType compType = CheckVectorOperands( 8439 LHS, RHS, Loc, CompLHSTy, 8440 /*AllowBothBool*/getLangOpts().AltiVec, 8441 /*AllowBoolConversions*/getLangOpts().ZVector); 8442 if (CompLHSTy) *CompLHSTy = compType; 8443 return compType; 8444 } 8445 8446 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8447 if (LHS.isInvalid() || RHS.isInvalid()) 8448 return QualType(); 8449 8450 // Diagnose "string literal" '+' int and string '+' "char literal". 8451 if (Opc == BO_Add) { 8452 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8453 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8454 } 8455 8456 // handle the common case first (both operands are arithmetic). 8457 if (!compType.isNull() && compType->isArithmeticType()) { 8458 if (CompLHSTy) *CompLHSTy = compType; 8459 return compType; 8460 } 8461 8462 // Type-checking. Ultimately the pointer's going to be in PExp; 8463 // note that we bias towards the LHS being the pointer. 8464 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8465 8466 bool isObjCPointer; 8467 if (PExp->getType()->isPointerType()) { 8468 isObjCPointer = false; 8469 } else if (PExp->getType()->isObjCObjectPointerType()) { 8470 isObjCPointer = true; 8471 } else { 8472 std::swap(PExp, IExp); 8473 if (PExp->getType()->isPointerType()) { 8474 isObjCPointer = false; 8475 } else if (PExp->getType()->isObjCObjectPointerType()) { 8476 isObjCPointer = true; 8477 } else { 8478 return InvalidOperands(Loc, LHS, RHS); 8479 } 8480 } 8481 assert(PExp->getType()->isAnyPointerType()); 8482 8483 if (!IExp->getType()->isIntegerType()) 8484 return InvalidOperands(Loc, LHS, RHS); 8485 8486 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8487 return QualType(); 8488 8489 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8490 return QualType(); 8491 8492 // Check array bounds for pointer arithemtic 8493 CheckArrayAccess(PExp, IExp); 8494 8495 if (CompLHSTy) { 8496 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8497 if (LHSTy.isNull()) { 8498 LHSTy = LHS.get()->getType(); 8499 if (LHSTy->isPromotableIntegerType()) 8500 LHSTy = Context.getPromotedIntegerType(LHSTy); 8501 } 8502 *CompLHSTy = LHSTy; 8503 } 8504 8505 return PExp->getType(); 8506 } 8507 8508 // C99 6.5.6 8509 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8510 SourceLocation Loc, 8511 QualType* CompLHSTy) { 8512 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8513 8514 if (LHS.get()->getType()->isVectorType() || 8515 RHS.get()->getType()->isVectorType()) { 8516 QualType compType = CheckVectorOperands( 8517 LHS, RHS, Loc, CompLHSTy, 8518 /*AllowBothBool*/getLangOpts().AltiVec, 8519 /*AllowBoolConversions*/getLangOpts().ZVector); 8520 if (CompLHSTy) *CompLHSTy = compType; 8521 return compType; 8522 } 8523 8524 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8525 if (LHS.isInvalid() || RHS.isInvalid()) 8526 return QualType(); 8527 8528 // Enforce type constraints: C99 6.5.6p3. 8529 8530 // Handle the common case first (both operands are arithmetic). 8531 if (!compType.isNull() && compType->isArithmeticType()) { 8532 if (CompLHSTy) *CompLHSTy = compType; 8533 return compType; 8534 } 8535 8536 // Either ptr - int or ptr - ptr. 8537 if (LHS.get()->getType()->isAnyPointerType()) { 8538 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8539 8540 // Diagnose bad cases where we step over interface counts. 8541 if (LHS.get()->getType()->isObjCObjectPointerType() && 8542 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8543 return QualType(); 8544 8545 // The result type of a pointer-int computation is the pointer type. 8546 if (RHS.get()->getType()->isIntegerType()) { 8547 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8548 return QualType(); 8549 8550 // Check array bounds for pointer arithemtic 8551 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8552 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8553 8554 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8555 return LHS.get()->getType(); 8556 } 8557 8558 // Handle pointer-pointer subtractions. 8559 if (const PointerType *RHSPTy 8560 = RHS.get()->getType()->getAs<PointerType>()) { 8561 QualType rpointee = RHSPTy->getPointeeType(); 8562 8563 if (getLangOpts().CPlusPlus) { 8564 // Pointee types must be the same: C++ [expr.add] 8565 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8566 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8567 } 8568 } else { 8569 // Pointee types must be compatible C99 6.5.6p3 8570 if (!Context.typesAreCompatible( 8571 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8572 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8573 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8574 return QualType(); 8575 } 8576 } 8577 8578 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8579 LHS.get(), RHS.get())) 8580 return QualType(); 8581 8582 // The pointee type may have zero size. As an extension, a structure or 8583 // union may have zero size or an array may have zero length. In this 8584 // case subtraction does not make sense. 8585 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8586 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8587 if (ElementSize.isZero()) { 8588 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8589 << rpointee.getUnqualifiedType() 8590 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8591 } 8592 } 8593 8594 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8595 return Context.getPointerDiffType(); 8596 } 8597 } 8598 8599 return InvalidOperands(Loc, LHS, RHS); 8600 } 8601 8602 static bool isScopedEnumerationType(QualType T) { 8603 if (const EnumType *ET = T->getAs<EnumType>()) 8604 return ET->getDecl()->isScoped(); 8605 return false; 8606 } 8607 8608 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8609 SourceLocation Loc, BinaryOperatorKind Opc, 8610 QualType LHSType) { 8611 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8612 // so skip remaining warnings as we don't want to modify values within Sema. 8613 if (S.getLangOpts().OpenCL) 8614 return; 8615 8616 llvm::APSInt Right; 8617 // Check right/shifter operand 8618 if (RHS.get()->isValueDependent() || 8619 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8620 return; 8621 8622 if (Right.isNegative()) { 8623 S.DiagRuntimeBehavior(Loc, RHS.get(), 8624 S.PDiag(diag::warn_shift_negative) 8625 << RHS.get()->getSourceRange()); 8626 return; 8627 } 8628 llvm::APInt LeftBits(Right.getBitWidth(), 8629 S.Context.getTypeSize(LHS.get()->getType())); 8630 if (Right.uge(LeftBits)) { 8631 S.DiagRuntimeBehavior(Loc, RHS.get(), 8632 S.PDiag(diag::warn_shift_gt_typewidth) 8633 << RHS.get()->getSourceRange()); 8634 return; 8635 } 8636 if (Opc != BO_Shl) 8637 return; 8638 8639 // When left shifting an ICE which is signed, we can check for overflow which 8640 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8641 // integers have defined behavior modulo one more than the maximum value 8642 // representable in the result type, so never warn for those. 8643 llvm::APSInt Left; 8644 if (LHS.get()->isValueDependent() || 8645 LHSType->hasUnsignedIntegerRepresentation() || 8646 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8647 return; 8648 8649 // If LHS does not have a signed type and non-negative value 8650 // then, the behavior is undefined. Warn about it. 8651 if (Left.isNegative()) { 8652 S.DiagRuntimeBehavior(Loc, LHS.get(), 8653 S.PDiag(diag::warn_shift_lhs_negative) 8654 << LHS.get()->getSourceRange()); 8655 return; 8656 } 8657 8658 llvm::APInt ResultBits = 8659 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8660 if (LeftBits.uge(ResultBits)) 8661 return; 8662 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8663 Result = Result.shl(Right); 8664 8665 // Print the bit representation of the signed integer as an unsigned 8666 // hexadecimal number. 8667 SmallString<40> HexResult; 8668 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8669 8670 // If we are only missing a sign bit, this is less likely to result in actual 8671 // bugs -- if the result is cast back to an unsigned type, it will have the 8672 // expected value. Thus we place this behind a different warning that can be 8673 // turned off separately if needed. 8674 if (LeftBits == ResultBits - 1) { 8675 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8676 << HexResult << LHSType 8677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8678 return; 8679 } 8680 8681 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8682 << HexResult.str() << Result.getMinSignedBits() << LHSType 8683 << Left.getBitWidth() << LHS.get()->getSourceRange() 8684 << RHS.get()->getSourceRange(); 8685 } 8686 8687 /// \brief Return the resulting type when a vector is shifted 8688 /// by a scalar or vector shift amount. 8689 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8690 SourceLocation Loc, bool IsCompAssign) { 8691 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8692 if (!LHS.get()->getType()->isVectorType()) { 8693 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8694 << RHS.get()->getType() << LHS.get()->getType() 8695 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8696 return QualType(); 8697 } 8698 8699 if (!IsCompAssign) { 8700 LHS = S.UsualUnaryConversions(LHS.get()); 8701 if (LHS.isInvalid()) return QualType(); 8702 } 8703 8704 RHS = S.UsualUnaryConversions(RHS.get()); 8705 if (RHS.isInvalid()) return QualType(); 8706 8707 QualType LHSType = LHS.get()->getType(); 8708 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8709 QualType LHSEleType = LHSVecTy->getElementType(); 8710 8711 // Note that RHS might not be a vector. 8712 QualType RHSType = RHS.get()->getType(); 8713 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8714 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8715 8716 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8717 if (!LHSEleType->isIntegerType()) { 8718 S.Diag(Loc, diag::err_typecheck_expect_int) 8719 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8720 return QualType(); 8721 } 8722 8723 if (!RHSEleType->isIntegerType()) { 8724 S.Diag(Loc, diag::err_typecheck_expect_int) 8725 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8726 return QualType(); 8727 } 8728 8729 if (RHSVecTy) { 8730 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8731 // are applied component-wise. So if RHS is a vector, then ensure 8732 // that the number of elements is the same as LHS... 8733 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8734 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8735 << LHS.get()->getType() << RHS.get()->getType() 8736 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8737 return QualType(); 8738 } 8739 } else { 8740 // ...else expand RHS to match the number of elements in LHS. 8741 QualType VecTy = 8742 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8743 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8744 } 8745 8746 return LHSType; 8747 } 8748 8749 // C99 6.5.7 8750 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8751 SourceLocation Loc, BinaryOperatorKind Opc, 8752 bool IsCompAssign) { 8753 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8754 8755 // Vector shifts promote their scalar inputs to vector type. 8756 if (LHS.get()->getType()->isVectorType() || 8757 RHS.get()->getType()->isVectorType()) { 8758 if (LangOpts.ZVector) { 8759 // The shift operators for the z vector extensions work basically 8760 // like general shifts, except that neither the LHS nor the RHS is 8761 // allowed to be a "vector bool". 8762 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8763 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8764 return InvalidOperands(Loc, LHS, RHS); 8765 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8766 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8767 return InvalidOperands(Loc, LHS, RHS); 8768 } 8769 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8770 } 8771 8772 // Shifts don't perform usual arithmetic conversions, they just do integer 8773 // promotions on each operand. C99 6.5.7p3 8774 8775 // For the LHS, do usual unary conversions, but then reset them away 8776 // if this is a compound assignment. 8777 ExprResult OldLHS = LHS; 8778 LHS = UsualUnaryConversions(LHS.get()); 8779 if (LHS.isInvalid()) 8780 return QualType(); 8781 QualType LHSType = LHS.get()->getType(); 8782 if (IsCompAssign) LHS = OldLHS; 8783 8784 // The RHS is simpler. 8785 RHS = UsualUnaryConversions(RHS.get()); 8786 if (RHS.isInvalid()) 8787 return QualType(); 8788 QualType RHSType = RHS.get()->getType(); 8789 8790 // C99 6.5.7p2: Each of the operands shall have integer type. 8791 if (!LHSType->hasIntegerRepresentation() || 8792 !RHSType->hasIntegerRepresentation()) 8793 return InvalidOperands(Loc, LHS, RHS); 8794 8795 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8796 // hasIntegerRepresentation() above instead of this. 8797 if (isScopedEnumerationType(LHSType) || 8798 isScopedEnumerationType(RHSType)) { 8799 return InvalidOperands(Loc, LHS, RHS); 8800 } 8801 // Sanity-check shift operands 8802 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8803 8804 // "The type of the result is that of the promoted left operand." 8805 return LHSType; 8806 } 8807 8808 static bool IsWithinTemplateSpecialization(Decl *D) { 8809 if (DeclContext *DC = D->getDeclContext()) { 8810 if (isa<ClassTemplateSpecializationDecl>(DC)) 8811 return true; 8812 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8813 return FD->isFunctionTemplateSpecialization(); 8814 } 8815 return false; 8816 } 8817 8818 /// If two different enums are compared, raise a warning. 8819 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8820 Expr *RHS) { 8821 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8822 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8823 8824 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8825 if (!LHSEnumType) 8826 return; 8827 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8828 if (!RHSEnumType) 8829 return; 8830 8831 // Ignore anonymous enums. 8832 if (!LHSEnumType->getDecl()->getIdentifier()) 8833 return; 8834 if (!RHSEnumType->getDecl()->getIdentifier()) 8835 return; 8836 8837 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8838 return; 8839 8840 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8841 << LHSStrippedType << RHSStrippedType 8842 << LHS->getSourceRange() << RHS->getSourceRange(); 8843 } 8844 8845 /// \brief Diagnose bad pointer comparisons. 8846 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8847 ExprResult &LHS, ExprResult &RHS, 8848 bool IsError) { 8849 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8850 : diag::ext_typecheck_comparison_of_distinct_pointers) 8851 << LHS.get()->getType() << RHS.get()->getType() 8852 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8853 } 8854 8855 /// \brief Returns false if the pointers are converted to a composite type, 8856 /// true otherwise. 8857 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8858 ExprResult &LHS, ExprResult &RHS) { 8859 // C++ [expr.rel]p2: 8860 // [...] Pointer conversions (4.10) and qualification 8861 // conversions (4.4) are performed on pointer operands (or on 8862 // a pointer operand and a null pointer constant) to bring 8863 // them to their composite pointer type. [...] 8864 // 8865 // C++ [expr.eq]p1 uses the same notion for (in)equality 8866 // comparisons of pointers. 8867 8868 // C++ [expr.eq]p2: 8869 // In addition, pointers to members can be compared, or a pointer to 8870 // member and a null pointer constant. Pointer to member conversions 8871 // (4.11) and qualification conversions (4.4) are performed to bring 8872 // them to a common type. If one operand is a null pointer constant, 8873 // the common type is the type of the other operand. Otherwise, the 8874 // common type is a pointer to member type similar (4.4) to the type 8875 // of one of the operands, with a cv-qualification signature (4.4) 8876 // that is the union of the cv-qualification signatures of the operand 8877 // types. 8878 8879 QualType LHSType = LHS.get()->getType(); 8880 QualType RHSType = RHS.get()->getType(); 8881 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8882 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8883 8884 bool NonStandardCompositeType = false; 8885 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8886 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8887 if (T.isNull()) { 8888 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8889 return true; 8890 } 8891 8892 if (NonStandardCompositeType) 8893 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8894 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8895 << RHS.get()->getSourceRange(); 8896 8897 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8898 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8899 return false; 8900 } 8901 8902 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8903 ExprResult &LHS, 8904 ExprResult &RHS, 8905 bool IsError) { 8906 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8907 : diag::ext_typecheck_comparison_of_fptr_to_void) 8908 << LHS.get()->getType() << RHS.get()->getType() 8909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8910 } 8911 8912 static bool isObjCObjectLiteral(ExprResult &E) { 8913 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8914 case Stmt::ObjCArrayLiteralClass: 8915 case Stmt::ObjCDictionaryLiteralClass: 8916 case Stmt::ObjCStringLiteralClass: 8917 case Stmt::ObjCBoxedExprClass: 8918 return true; 8919 default: 8920 // Note that ObjCBoolLiteral is NOT an object literal! 8921 return false; 8922 } 8923 } 8924 8925 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8926 const ObjCObjectPointerType *Type = 8927 LHS->getType()->getAs<ObjCObjectPointerType>(); 8928 8929 // If this is not actually an Objective-C object, bail out. 8930 if (!Type) 8931 return false; 8932 8933 // Get the LHS object's interface type. 8934 QualType InterfaceType = Type->getPointeeType(); 8935 8936 // If the RHS isn't an Objective-C object, bail out. 8937 if (!RHS->getType()->isObjCObjectPointerType()) 8938 return false; 8939 8940 // Try to find the -isEqual: method. 8941 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8942 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8943 InterfaceType, 8944 /*instance=*/true); 8945 if (!Method) { 8946 if (Type->isObjCIdType()) { 8947 // For 'id', just check the global pool. 8948 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8949 /*receiverId=*/true); 8950 } else { 8951 // Check protocols. 8952 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8953 /*instance=*/true); 8954 } 8955 } 8956 8957 if (!Method) 8958 return false; 8959 8960 QualType T = Method->parameters()[0]->getType(); 8961 if (!T->isObjCObjectPointerType()) 8962 return false; 8963 8964 QualType R = Method->getReturnType(); 8965 if (!R->isScalarType()) 8966 return false; 8967 8968 return true; 8969 } 8970 8971 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8972 FromE = FromE->IgnoreParenImpCasts(); 8973 switch (FromE->getStmtClass()) { 8974 default: 8975 break; 8976 case Stmt::ObjCStringLiteralClass: 8977 // "string literal" 8978 return LK_String; 8979 case Stmt::ObjCArrayLiteralClass: 8980 // "array literal" 8981 return LK_Array; 8982 case Stmt::ObjCDictionaryLiteralClass: 8983 // "dictionary literal" 8984 return LK_Dictionary; 8985 case Stmt::BlockExprClass: 8986 return LK_Block; 8987 case Stmt::ObjCBoxedExprClass: { 8988 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8989 switch (Inner->getStmtClass()) { 8990 case Stmt::IntegerLiteralClass: 8991 case Stmt::FloatingLiteralClass: 8992 case Stmt::CharacterLiteralClass: 8993 case Stmt::ObjCBoolLiteralExprClass: 8994 case Stmt::CXXBoolLiteralExprClass: 8995 // "numeric literal" 8996 return LK_Numeric; 8997 case Stmt::ImplicitCastExprClass: { 8998 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8999 // Boolean literals can be represented by implicit casts. 9000 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9001 return LK_Numeric; 9002 break; 9003 } 9004 default: 9005 break; 9006 } 9007 return LK_Boxed; 9008 } 9009 } 9010 return LK_None; 9011 } 9012 9013 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9014 ExprResult &LHS, ExprResult &RHS, 9015 BinaryOperator::Opcode Opc){ 9016 Expr *Literal; 9017 Expr *Other; 9018 if (isObjCObjectLiteral(LHS)) { 9019 Literal = LHS.get(); 9020 Other = RHS.get(); 9021 } else { 9022 Literal = RHS.get(); 9023 Other = LHS.get(); 9024 } 9025 9026 // Don't warn on comparisons against nil. 9027 Other = Other->IgnoreParenCasts(); 9028 if (Other->isNullPointerConstant(S.getASTContext(), 9029 Expr::NPC_ValueDependentIsNotNull)) 9030 return; 9031 9032 // This should be kept in sync with warn_objc_literal_comparison. 9033 // LK_String should always be after the other literals, since it has its own 9034 // warning flag. 9035 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9036 assert(LiteralKind != Sema::LK_Block); 9037 if (LiteralKind == Sema::LK_None) { 9038 llvm_unreachable("Unknown Objective-C object literal kind"); 9039 } 9040 9041 if (LiteralKind == Sema::LK_String) 9042 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9043 << Literal->getSourceRange(); 9044 else 9045 S.Diag(Loc, diag::warn_objc_literal_comparison) 9046 << LiteralKind << Literal->getSourceRange(); 9047 9048 if (BinaryOperator::isEqualityOp(Opc) && 9049 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9050 SourceLocation Start = LHS.get()->getLocStart(); 9051 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9052 CharSourceRange OpRange = 9053 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9054 9055 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9056 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9057 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9058 << FixItHint::CreateInsertion(End, "]"); 9059 } 9060 } 9061 9062 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 9063 ExprResult &RHS, 9064 SourceLocation Loc, 9065 BinaryOperatorKind Opc) { 9066 // Check that left hand side is !something. 9067 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9068 if (!UO || UO->getOpcode() != UO_LNot) return; 9069 9070 // Only check if the right hand side is non-bool arithmetic type. 9071 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9072 9073 // Make sure that the something in !something is not bool. 9074 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9075 if (SubExpr->isKnownToHaveBooleanValue()) return; 9076 9077 // Emit warning. 9078 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 9079 << Loc; 9080 9081 // First note suggest !(x < y) 9082 SourceLocation FirstOpen = SubExpr->getLocStart(); 9083 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9084 FirstClose = S.getLocForEndOfToken(FirstClose); 9085 if (FirstClose.isInvalid()) 9086 FirstOpen = SourceLocation(); 9087 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9088 << FixItHint::CreateInsertion(FirstOpen, "(") 9089 << FixItHint::CreateInsertion(FirstClose, ")"); 9090 9091 // Second note suggests (!x) < y 9092 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9093 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9094 SecondClose = S.getLocForEndOfToken(SecondClose); 9095 if (SecondClose.isInvalid()) 9096 SecondOpen = SourceLocation(); 9097 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9098 << FixItHint::CreateInsertion(SecondOpen, "(") 9099 << FixItHint::CreateInsertion(SecondClose, ")"); 9100 } 9101 9102 // Get the decl for a simple expression: a reference to a variable, 9103 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9104 static ValueDecl *getCompareDecl(Expr *E) { 9105 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9106 return DR->getDecl(); 9107 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9108 if (Ivar->isFreeIvar()) 9109 return Ivar->getDecl(); 9110 } 9111 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9112 if (Mem->isImplicitAccess()) 9113 return Mem->getMemberDecl(); 9114 } 9115 return nullptr; 9116 } 9117 9118 // C99 6.5.8, C++ [expr.rel] 9119 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9120 SourceLocation Loc, BinaryOperatorKind Opc, 9121 bool IsRelational) { 9122 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9123 9124 // Handle vector comparisons separately. 9125 if (LHS.get()->getType()->isVectorType() || 9126 RHS.get()->getType()->isVectorType()) 9127 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9128 9129 QualType LHSType = LHS.get()->getType(); 9130 QualType RHSType = RHS.get()->getType(); 9131 9132 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9133 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9134 9135 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9136 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9137 9138 if (!LHSType->hasFloatingRepresentation() && 9139 !(LHSType->isBlockPointerType() && IsRelational) && 9140 !LHS.get()->getLocStart().isMacroID() && 9141 !RHS.get()->getLocStart().isMacroID() && 9142 ActiveTemplateInstantiations.empty()) { 9143 // For non-floating point types, check for self-comparisons of the form 9144 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9145 // often indicate logic errors in the program. 9146 // 9147 // NOTE: Don't warn about comparison expressions resulting from macro 9148 // expansion. Also don't warn about comparisons which are only self 9149 // comparisons within a template specialization. The warnings should catch 9150 // obvious cases in the definition of the template anyways. The idea is to 9151 // warn when the typed comparison operator will always evaluate to the same 9152 // result. 9153 ValueDecl *DL = getCompareDecl(LHSStripped); 9154 ValueDecl *DR = getCompareDecl(RHSStripped); 9155 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9156 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9157 << 0 // self- 9158 << (Opc == BO_EQ 9159 || Opc == BO_LE 9160 || Opc == BO_GE)); 9161 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9162 !DL->getType()->isReferenceType() && 9163 !DR->getType()->isReferenceType()) { 9164 // what is it always going to eval to? 9165 char always_evals_to; 9166 switch(Opc) { 9167 case BO_EQ: // e.g. array1 == array2 9168 always_evals_to = 0; // false 9169 break; 9170 case BO_NE: // e.g. array1 != array2 9171 always_evals_to = 1; // true 9172 break; 9173 default: 9174 // best we can say is 'a constant' 9175 always_evals_to = 2; // e.g. array1 <= array2 9176 break; 9177 } 9178 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9179 << 1 // array 9180 << always_evals_to); 9181 } 9182 9183 if (isa<CastExpr>(LHSStripped)) 9184 LHSStripped = LHSStripped->IgnoreParenCasts(); 9185 if (isa<CastExpr>(RHSStripped)) 9186 RHSStripped = RHSStripped->IgnoreParenCasts(); 9187 9188 // Warn about comparisons against a string constant (unless the other 9189 // operand is null), the user probably wants strcmp. 9190 Expr *literalString = nullptr; 9191 Expr *literalStringStripped = nullptr; 9192 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9193 !RHSStripped->isNullPointerConstant(Context, 9194 Expr::NPC_ValueDependentIsNull)) { 9195 literalString = LHS.get(); 9196 literalStringStripped = LHSStripped; 9197 } else if ((isa<StringLiteral>(RHSStripped) || 9198 isa<ObjCEncodeExpr>(RHSStripped)) && 9199 !LHSStripped->isNullPointerConstant(Context, 9200 Expr::NPC_ValueDependentIsNull)) { 9201 literalString = RHS.get(); 9202 literalStringStripped = RHSStripped; 9203 } 9204 9205 if (literalString) { 9206 DiagRuntimeBehavior(Loc, nullptr, 9207 PDiag(diag::warn_stringcompare) 9208 << isa<ObjCEncodeExpr>(literalStringStripped) 9209 << literalString->getSourceRange()); 9210 } 9211 } 9212 9213 // C99 6.5.8p3 / C99 6.5.9p4 9214 UsualArithmeticConversions(LHS, RHS); 9215 if (LHS.isInvalid() || RHS.isInvalid()) 9216 return QualType(); 9217 9218 LHSType = LHS.get()->getType(); 9219 RHSType = RHS.get()->getType(); 9220 9221 // The result of comparisons is 'bool' in C++, 'int' in C. 9222 QualType ResultTy = Context.getLogicalOperationType(); 9223 9224 if (IsRelational) { 9225 if (LHSType->isRealType() && RHSType->isRealType()) 9226 return ResultTy; 9227 } else { 9228 // Check for comparisons of floating point operands using != and ==. 9229 if (LHSType->hasFloatingRepresentation()) 9230 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9231 9232 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9233 return ResultTy; 9234 } 9235 9236 const Expr::NullPointerConstantKind LHSNullKind = 9237 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9238 const Expr::NullPointerConstantKind RHSNullKind = 9239 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9240 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9241 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9242 9243 if (!IsRelational && LHSIsNull != RHSIsNull) { 9244 bool IsEquality = Opc == BO_EQ; 9245 if (RHSIsNull) 9246 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9247 RHS.get()->getSourceRange()); 9248 else 9249 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9250 LHS.get()->getSourceRange()); 9251 } 9252 9253 // All of the following pointer-related warnings are GCC extensions, except 9254 // when handling null pointer constants. 9255 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9256 QualType LCanPointeeTy = 9257 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9258 QualType RCanPointeeTy = 9259 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9260 9261 if (getLangOpts().CPlusPlus) { 9262 if (LCanPointeeTy == RCanPointeeTy) 9263 return ResultTy; 9264 if (!IsRelational && 9265 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9266 // Valid unless comparison between non-null pointer and function pointer 9267 // This is a gcc extension compatibility comparison. 9268 // In a SFINAE context, we treat this as a hard error to maintain 9269 // conformance with the C++ standard. 9270 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9271 && !LHSIsNull && !RHSIsNull) { 9272 diagnoseFunctionPointerToVoidComparison( 9273 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9274 9275 if (isSFINAEContext()) 9276 return QualType(); 9277 9278 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9279 return ResultTy; 9280 } 9281 } 9282 9283 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9284 return QualType(); 9285 else 9286 return ResultTy; 9287 } 9288 // C99 6.5.9p2 and C99 6.5.8p2 9289 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9290 RCanPointeeTy.getUnqualifiedType())) { 9291 // Valid unless a relational comparison of function pointers 9292 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9293 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9294 << LHSType << RHSType << LHS.get()->getSourceRange() 9295 << RHS.get()->getSourceRange(); 9296 } 9297 } else if (!IsRelational && 9298 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9299 // Valid unless comparison between non-null pointer and function pointer 9300 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9301 && !LHSIsNull && !RHSIsNull) 9302 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9303 /*isError*/false); 9304 } else { 9305 // Invalid 9306 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9307 } 9308 if (LCanPointeeTy != RCanPointeeTy) { 9309 // Treat NULL constant as a special case in OpenCL. 9310 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9311 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9312 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9313 Diag(Loc, 9314 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9315 << LHSType << RHSType << 0 /* comparison */ 9316 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9317 } 9318 } 9319 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9320 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9321 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9322 : CK_BitCast; 9323 if (LHSIsNull && !RHSIsNull) 9324 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9325 else 9326 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9327 } 9328 return ResultTy; 9329 } 9330 9331 if (getLangOpts().CPlusPlus) { 9332 // Comparison of nullptr_t with itself. 9333 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9334 return ResultTy; 9335 9336 // Comparison of pointers with null pointer constants and equality 9337 // comparisons of member pointers to null pointer constants. 9338 if (RHSIsNull && 9339 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9340 (!IsRelational && 9341 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9342 RHS = ImpCastExprToType(RHS.get(), LHSType, 9343 LHSType->isMemberPointerType() 9344 ? CK_NullToMemberPointer 9345 : CK_NullToPointer); 9346 return ResultTy; 9347 } 9348 if (LHSIsNull && 9349 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9350 (!IsRelational && 9351 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9352 LHS = ImpCastExprToType(LHS.get(), RHSType, 9353 RHSType->isMemberPointerType() 9354 ? CK_NullToMemberPointer 9355 : CK_NullToPointer); 9356 return ResultTy; 9357 } 9358 9359 // Comparison of member pointers. 9360 if (!IsRelational && 9361 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9362 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9363 return QualType(); 9364 else 9365 return ResultTy; 9366 } 9367 9368 // Handle scoped enumeration types specifically, since they don't promote 9369 // to integers. 9370 if (LHS.get()->getType()->isEnumeralType() && 9371 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9372 RHS.get()->getType())) 9373 return ResultTy; 9374 } 9375 9376 // Handle block pointer types. 9377 if (!IsRelational && LHSType->isBlockPointerType() && 9378 RHSType->isBlockPointerType()) { 9379 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9380 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9381 9382 if (!LHSIsNull && !RHSIsNull && 9383 !Context.typesAreCompatible(lpointee, rpointee)) { 9384 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9385 << LHSType << RHSType << LHS.get()->getSourceRange() 9386 << RHS.get()->getSourceRange(); 9387 } 9388 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9389 return ResultTy; 9390 } 9391 9392 // Allow block pointers to be compared with null pointer constants. 9393 if (!IsRelational 9394 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9395 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9396 if (!LHSIsNull && !RHSIsNull) { 9397 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9398 ->getPointeeType()->isVoidType()) 9399 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9400 ->getPointeeType()->isVoidType()))) 9401 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9402 << LHSType << RHSType << LHS.get()->getSourceRange() 9403 << RHS.get()->getSourceRange(); 9404 } 9405 if (LHSIsNull && !RHSIsNull) 9406 LHS = ImpCastExprToType(LHS.get(), RHSType, 9407 RHSType->isPointerType() ? CK_BitCast 9408 : CK_AnyPointerToBlockPointerCast); 9409 else 9410 RHS = ImpCastExprToType(RHS.get(), LHSType, 9411 LHSType->isPointerType() ? CK_BitCast 9412 : CK_AnyPointerToBlockPointerCast); 9413 return ResultTy; 9414 } 9415 9416 if (LHSType->isObjCObjectPointerType() || 9417 RHSType->isObjCObjectPointerType()) { 9418 const PointerType *LPT = LHSType->getAs<PointerType>(); 9419 const PointerType *RPT = RHSType->getAs<PointerType>(); 9420 if (LPT || RPT) { 9421 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9422 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9423 9424 if (!LPtrToVoid && !RPtrToVoid && 9425 !Context.typesAreCompatible(LHSType, RHSType)) { 9426 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9427 /*isError*/false); 9428 } 9429 if (LHSIsNull && !RHSIsNull) { 9430 Expr *E = LHS.get(); 9431 if (getLangOpts().ObjCAutoRefCount) 9432 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9433 LHS = ImpCastExprToType(E, RHSType, 9434 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9435 } 9436 else { 9437 Expr *E = RHS.get(); 9438 if (getLangOpts().ObjCAutoRefCount) 9439 CheckObjCARCConversion(SourceRange(), LHSType, E, 9440 CCK_ImplicitConversion, /*Diagnose=*/true, 9441 /*DiagnoseCFAudited=*/false, Opc); 9442 RHS = ImpCastExprToType(E, LHSType, 9443 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9444 } 9445 return ResultTy; 9446 } 9447 if (LHSType->isObjCObjectPointerType() && 9448 RHSType->isObjCObjectPointerType()) { 9449 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9450 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9451 /*isError*/false); 9452 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9453 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9454 9455 if (LHSIsNull && !RHSIsNull) 9456 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9457 else 9458 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9459 return ResultTy; 9460 } 9461 } 9462 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9463 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9464 unsigned DiagID = 0; 9465 bool isError = false; 9466 if (LangOpts.DebuggerSupport) { 9467 // Under a debugger, allow the comparison of pointers to integers, 9468 // since users tend to want to compare addresses. 9469 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9470 (RHSIsNull && RHSType->isIntegerType())) { 9471 if (IsRelational && !getLangOpts().CPlusPlus) 9472 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9473 } else if (IsRelational && !getLangOpts().CPlusPlus) 9474 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9475 else if (getLangOpts().CPlusPlus) { 9476 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9477 isError = true; 9478 } else 9479 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9480 9481 if (DiagID) { 9482 Diag(Loc, DiagID) 9483 << LHSType << RHSType << LHS.get()->getSourceRange() 9484 << RHS.get()->getSourceRange(); 9485 if (isError) 9486 return QualType(); 9487 } 9488 9489 if (LHSType->isIntegerType()) 9490 LHS = ImpCastExprToType(LHS.get(), RHSType, 9491 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9492 else 9493 RHS = ImpCastExprToType(RHS.get(), LHSType, 9494 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9495 return ResultTy; 9496 } 9497 9498 // Handle block pointers. 9499 if (!IsRelational && RHSIsNull 9500 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9501 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9502 return ResultTy; 9503 } 9504 if (!IsRelational && LHSIsNull 9505 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9506 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9507 return ResultTy; 9508 } 9509 9510 return InvalidOperands(Loc, LHS, RHS); 9511 } 9512 9513 9514 // Return a signed type that is of identical size and number of elements. 9515 // For floating point vectors, return an integer type of identical size 9516 // and number of elements. 9517 QualType Sema::GetSignedVectorType(QualType V) { 9518 const VectorType *VTy = V->getAs<VectorType>(); 9519 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9520 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9521 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9522 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9523 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9524 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9525 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9526 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9527 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9528 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9529 "Unhandled vector element size in vector compare"); 9530 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9531 } 9532 9533 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9534 /// operates on extended vector types. Instead of producing an IntTy result, 9535 /// like a scalar comparison, a vector comparison produces a vector of integer 9536 /// types. 9537 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9538 SourceLocation Loc, 9539 bool IsRelational) { 9540 // Check to make sure we're operating on vectors of the same type and width, 9541 // Allowing one side to be a scalar of element type. 9542 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9543 /*AllowBothBool*/true, 9544 /*AllowBoolConversions*/getLangOpts().ZVector); 9545 if (vType.isNull()) 9546 return vType; 9547 9548 QualType LHSType = LHS.get()->getType(); 9549 9550 // If AltiVec, the comparison results in a numeric type, i.e. 9551 // bool for C++, int for C 9552 if (getLangOpts().AltiVec && 9553 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9554 return Context.getLogicalOperationType(); 9555 9556 // For non-floating point types, check for self-comparisons of the form 9557 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9558 // often indicate logic errors in the program. 9559 if (!LHSType->hasFloatingRepresentation() && 9560 ActiveTemplateInstantiations.empty()) { 9561 if (DeclRefExpr* DRL 9562 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9563 if (DeclRefExpr* DRR 9564 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9565 if (DRL->getDecl() == DRR->getDecl()) 9566 DiagRuntimeBehavior(Loc, nullptr, 9567 PDiag(diag::warn_comparison_always) 9568 << 0 // self- 9569 << 2 // "a constant" 9570 ); 9571 } 9572 9573 // Check for comparisons of floating point operands using != and ==. 9574 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9575 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9576 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9577 } 9578 9579 // Return a signed type for the vector. 9580 return GetSignedVectorType(vType); 9581 } 9582 9583 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9584 SourceLocation Loc) { 9585 // Ensure that either both operands are of the same vector type, or 9586 // one operand is of a vector type and the other is of its element type. 9587 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9588 /*AllowBothBool*/true, 9589 /*AllowBoolConversions*/false); 9590 if (vType.isNull()) 9591 return InvalidOperands(Loc, LHS, RHS); 9592 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9593 vType->hasFloatingRepresentation()) 9594 return InvalidOperands(Loc, LHS, RHS); 9595 9596 return GetSignedVectorType(LHS.get()->getType()); 9597 } 9598 9599 inline QualType Sema::CheckBitwiseOperands( 9600 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9601 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9602 9603 if (LHS.get()->getType()->isVectorType() || 9604 RHS.get()->getType()->isVectorType()) { 9605 if (LHS.get()->getType()->hasIntegerRepresentation() && 9606 RHS.get()->getType()->hasIntegerRepresentation()) 9607 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9608 /*AllowBothBool*/true, 9609 /*AllowBoolConversions*/getLangOpts().ZVector); 9610 return InvalidOperands(Loc, LHS, RHS); 9611 } 9612 9613 ExprResult LHSResult = LHS, RHSResult = RHS; 9614 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9615 IsCompAssign); 9616 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9617 return QualType(); 9618 LHS = LHSResult.get(); 9619 RHS = RHSResult.get(); 9620 9621 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9622 return compType; 9623 return InvalidOperands(Loc, LHS, RHS); 9624 } 9625 9626 // C99 6.5.[13,14] 9627 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9628 SourceLocation Loc, 9629 BinaryOperatorKind Opc) { 9630 // Check vector operands differently. 9631 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9632 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9633 9634 // Diagnose cases where the user write a logical and/or but probably meant a 9635 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9636 // is a constant. 9637 if (LHS.get()->getType()->isIntegerType() && 9638 !LHS.get()->getType()->isBooleanType() && 9639 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9640 // Don't warn in macros or template instantiations. 9641 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9642 // If the RHS can be constant folded, and if it constant folds to something 9643 // that isn't 0 or 1 (which indicate a potential logical operation that 9644 // happened to fold to true/false) then warn. 9645 // Parens on the RHS are ignored. 9646 llvm::APSInt Result; 9647 if (RHS.get()->EvaluateAsInt(Result, Context)) 9648 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9649 !RHS.get()->getExprLoc().isMacroID()) || 9650 (Result != 0 && Result != 1)) { 9651 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9652 << RHS.get()->getSourceRange() 9653 << (Opc == BO_LAnd ? "&&" : "||"); 9654 // Suggest replacing the logical operator with the bitwise version 9655 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9656 << (Opc == BO_LAnd ? "&" : "|") 9657 << FixItHint::CreateReplacement(SourceRange( 9658 Loc, getLocForEndOfToken(Loc)), 9659 Opc == BO_LAnd ? "&" : "|"); 9660 if (Opc == BO_LAnd) 9661 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9662 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9663 << FixItHint::CreateRemoval( 9664 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9665 RHS.get()->getLocEnd())); 9666 } 9667 } 9668 9669 if (!Context.getLangOpts().CPlusPlus) { 9670 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9671 // not operate on the built-in scalar and vector float types. 9672 if (Context.getLangOpts().OpenCL && 9673 Context.getLangOpts().OpenCLVersion < 120) { 9674 if (LHS.get()->getType()->isFloatingType() || 9675 RHS.get()->getType()->isFloatingType()) 9676 return InvalidOperands(Loc, LHS, RHS); 9677 } 9678 9679 LHS = UsualUnaryConversions(LHS.get()); 9680 if (LHS.isInvalid()) 9681 return QualType(); 9682 9683 RHS = UsualUnaryConversions(RHS.get()); 9684 if (RHS.isInvalid()) 9685 return QualType(); 9686 9687 if (!LHS.get()->getType()->isScalarType() || 9688 !RHS.get()->getType()->isScalarType()) 9689 return InvalidOperands(Loc, LHS, RHS); 9690 9691 return Context.IntTy; 9692 } 9693 9694 // The following is safe because we only use this method for 9695 // non-overloadable operands. 9696 9697 // C++ [expr.log.and]p1 9698 // C++ [expr.log.or]p1 9699 // The operands are both contextually converted to type bool. 9700 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9701 if (LHSRes.isInvalid()) 9702 return InvalidOperands(Loc, LHS, RHS); 9703 LHS = LHSRes; 9704 9705 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9706 if (RHSRes.isInvalid()) 9707 return InvalidOperands(Loc, LHS, RHS); 9708 RHS = RHSRes; 9709 9710 // C++ [expr.log.and]p2 9711 // C++ [expr.log.or]p2 9712 // The result is a bool. 9713 return Context.BoolTy; 9714 } 9715 9716 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9717 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9718 if (!ME) return false; 9719 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9720 ObjCMessageExpr *Base = 9721 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9722 if (!Base) return false; 9723 return Base->getMethodDecl() != nullptr; 9724 } 9725 9726 /// Is the given expression (which must be 'const') a reference to a 9727 /// variable which was originally non-const, but which has become 9728 /// 'const' due to being captured within a block? 9729 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9730 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9731 assert(E->isLValue() && E->getType().isConstQualified()); 9732 E = E->IgnoreParens(); 9733 9734 // Must be a reference to a declaration from an enclosing scope. 9735 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9736 if (!DRE) return NCCK_None; 9737 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9738 9739 // The declaration must be a variable which is not declared 'const'. 9740 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9741 if (!var) return NCCK_None; 9742 if (var->getType().isConstQualified()) return NCCK_None; 9743 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9744 9745 // Decide whether the first capture was for a block or a lambda. 9746 DeclContext *DC = S.CurContext, *Prev = nullptr; 9747 // Decide whether the first capture was for a block or a lambda. 9748 while (DC) { 9749 // For init-capture, it is possible that the variable belongs to the 9750 // template pattern of the current context. 9751 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9752 if (var->isInitCapture() && 9753 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9754 break; 9755 if (DC == var->getDeclContext()) 9756 break; 9757 Prev = DC; 9758 DC = DC->getParent(); 9759 } 9760 // Unless we have an init-capture, we've gone one step too far. 9761 if (!var->isInitCapture()) 9762 DC = Prev; 9763 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9764 } 9765 9766 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9767 Ty = Ty.getNonReferenceType(); 9768 if (IsDereference && Ty->isPointerType()) 9769 Ty = Ty->getPointeeType(); 9770 return !Ty.isConstQualified(); 9771 } 9772 9773 /// Emit the "read-only variable not assignable" error and print notes to give 9774 /// more information about why the variable is not assignable, such as pointing 9775 /// to the declaration of a const variable, showing that a method is const, or 9776 /// that the function is returning a const reference. 9777 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9778 SourceLocation Loc) { 9779 // Update err_typecheck_assign_const and note_typecheck_assign_const 9780 // when this enum is changed. 9781 enum { 9782 ConstFunction, 9783 ConstVariable, 9784 ConstMember, 9785 ConstMethod, 9786 ConstUnknown, // Keep as last element 9787 }; 9788 9789 SourceRange ExprRange = E->getSourceRange(); 9790 9791 // Only emit one error on the first const found. All other consts will emit 9792 // a note to the error. 9793 bool DiagnosticEmitted = false; 9794 9795 // Track if the current expression is the result of a derefence, and if the 9796 // next checked expression is the result of a derefence. 9797 bool IsDereference = false; 9798 bool NextIsDereference = false; 9799 9800 // Loop to process MemberExpr chains. 9801 while (true) { 9802 IsDereference = NextIsDereference; 9803 NextIsDereference = false; 9804 9805 E = E->IgnoreParenImpCasts(); 9806 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9807 NextIsDereference = ME->isArrow(); 9808 const ValueDecl *VD = ME->getMemberDecl(); 9809 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9810 // Mutable fields can be modified even if the class is const. 9811 if (Field->isMutable()) { 9812 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9813 break; 9814 } 9815 9816 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9817 if (!DiagnosticEmitted) { 9818 S.Diag(Loc, diag::err_typecheck_assign_const) 9819 << ExprRange << ConstMember << false /*static*/ << Field 9820 << Field->getType(); 9821 DiagnosticEmitted = true; 9822 } 9823 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9824 << ConstMember << false /*static*/ << Field << Field->getType() 9825 << Field->getSourceRange(); 9826 } 9827 E = ME->getBase(); 9828 continue; 9829 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9830 if (VDecl->getType().isConstQualified()) { 9831 if (!DiagnosticEmitted) { 9832 S.Diag(Loc, diag::err_typecheck_assign_const) 9833 << ExprRange << ConstMember << true /*static*/ << VDecl 9834 << VDecl->getType(); 9835 DiagnosticEmitted = true; 9836 } 9837 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9838 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9839 << VDecl->getSourceRange(); 9840 } 9841 // Static fields do not inherit constness from parents. 9842 break; 9843 } 9844 break; 9845 } // End MemberExpr 9846 break; 9847 } 9848 9849 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9850 // Function calls 9851 const FunctionDecl *FD = CE->getDirectCallee(); 9852 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9853 if (!DiagnosticEmitted) { 9854 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9855 << ConstFunction << FD; 9856 DiagnosticEmitted = true; 9857 } 9858 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9859 diag::note_typecheck_assign_const) 9860 << ConstFunction << FD << FD->getReturnType() 9861 << FD->getReturnTypeSourceRange(); 9862 } 9863 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9864 // Point to variable declaration. 9865 if (const ValueDecl *VD = DRE->getDecl()) { 9866 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9867 if (!DiagnosticEmitted) { 9868 S.Diag(Loc, diag::err_typecheck_assign_const) 9869 << ExprRange << ConstVariable << VD << VD->getType(); 9870 DiagnosticEmitted = true; 9871 } 9872 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9873 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9874 } 9875 } 9876 } else if (isa<CXXThisExpr>(E)) { 9877 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9878 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9879 if (MD->isConst()) { 9880 if (!DiagnosticEmitted) { 9881 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9882 << ConstMethod << MD; 9883 DiagnosticEmitted = true; 9884 } 9885 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9886 << ConstMethod << MD << MD->getSourceRange(); 9887 } 9888 } 9889 } 9890 } 9891 9892 if (DiagnosticEmitted) 9893 return; 9894 9895 // Can't determine a more specific message, so display the generic error. 9896 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9897 } 9898 9899 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9900 /// emit an error and return true. If so, return false. 9901 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9902 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9903 9904 S.CheckShadowingDeclModification(E, Loc); 9905 9906 SourceLocation OrigLoc = Loc; 9907 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9908 &Loc); 9909 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9910 IsLV = Expr::MLV_InvalidMessageExpression; 9911 if (IsLV == Expr::MLV_Valid) 9912 return false; 9913 9914 unsigned DiagID = 0; 9915 bool NeedType = false; 9916 switch (IsLV) { // C99 6.5.16p2 9917 case Expr::MLV_ConstQualified: 9918 // Use a specialized diagnostic when we're assigning to an object 9919 // from an enclosing function or block. 9920 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9921 if (NCCK == NCCK_Block) 9922 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9923 else 9924 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9925 break; 9926 } 9927 9928 // In ARC, use some specialized diagnostics for occasions where we 9929 // infer 'const'. These are always pseudo-strong variables. 9930 if (S.getLangOpts().ObjCAutoRefCount) { 9931 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9932 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9933 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9934 9935 // Use the normal diagnostic if it's pseudo-__strong but the 9936 // user actually wrote 'const'. 9937 if (var->isARCPseudoStrong() && 9938 (!var->getTypeSourceInfo() || 9939 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9940 // There are two pseudo-strong cases: 9941 // - self 9942 ObjCMethodDecl *method = S.getCurMethodDecl(); 9943 if (method && var == method->getSelfDecl()) 9944 DiagID = method->isClassMethod() 9945 ? diag::err_typecheck_arc_assign_self_class_method 9946 : diag::err_typecheck_arc_assign_self; 9947 9948 // - fast enumeration variables 9949 else 9950 DiagID = diag::err_typecheck_arr_assign_enumeration; 9951 9952 SourceRange Assign; 9953 if (Loc != OrigLoc) 9954 Assign = SourceRange(OrigLoc, OrigLoc); 9955 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9956 // We need to preserve the AST regardless, so migration tool 9957 // can do its job. 9958 return false; 9959 } 9960 } 9961 } 9962 9963 // If none of the special cases above are triggered, then this is a 9964 // simple const assignment. 9965 if (DiagID == 0) { 9966 DiagnoseConstAssignment(S, E, Loc); 9967 return true; 9968 } 9969 9970 break; 9971 case Expr::MLV_ConstAddrSpace: 9972 DiagnoseConstAssignment(S, E, Loc); 9973 return true; 9974 case Expr::MLV_ArrayType: 9975 case Expr::MLV_ArrayTemporary: 9976 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9977 NeedType = true; 9978 break; 9979 case Expr::MLV_NotObjectType: 9980 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9981 NeedType = true; 9982 break; 9983 case Expr::MLV_LValueCast: 9984 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9985 break; 9986 case Expr::MLV_Valid: 9987 llvm_unreachable("did not take early return for MLV_Valid"); 9988 case Expr::MLV_InvalidExpression: 9989 case Expr::MLV_MemberFunction: 9990 case Expr::MLV_ClassTemporary: 9991 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9992 break; 9993 case Expr::MLV_IncompleteType: 9994 case Expr::MLV_IncompleteVoidType: 9995 return S.RequireCompleteType(Loc, E->getType(), 9996 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9997 case Expr::MLV_DuplicateVectorComponents: 9998 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9999 break; 10000 case Expr::MLV_NoSetterProperty: 10001 llvm_unreachable("readonly properties should be processed differently"); 10002 case Expr::MLV_InvalidMessageExpression: 10003 DiagID = diag::error_readonly_message_assignment; 10004 break; 10005 case Expr::MLV_SubObjCPropertySetting: 10006 DiagID = diag::error_no_subobject_property_setting; 10007 break; 10008 } 10009 10010 SourceRange Assign; 10011 if (Loc != OrigLoc) 10012 Assign = SourceRange(OrigLoc, OrigLoc); 10013 if (NeedType) 10014 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10015 else 10016 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10017 return true; 10018 } 10019 10020 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10021 SourceLocation Loc, 10022 Sema &Sema) { 10023 // C / C++ fields 10024 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10025 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10026 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10027 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10028 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10029 } 10030 10031 // Objective-C instance variables 10032 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10033 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10034 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10035 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10036 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10037 if (RL && RR && RL->getDecl() == RR->getDecl()) 10038 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10039 } 10040 } 10041 10042 // C99 6.5.16.1 10043 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10044 SourceLocation Loc, 10045 QualType CompoundType) { 10046 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10047 10048 // Verify that LHS is a modifiable lvalue, and emit error if not. 10049 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10050 return QualType(); 10051 10052 QualType LHSType = LHSExpr->getType(); 10053 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10054 CompoundType; 10055 AssignConvertType ConvTy; 10056 if (CompoundType.isNull()) { 10057 Expr *RHSCheck = RHS.get(); 10058 10059 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10060 10061 QualType LHSTy(LHSType); 10062 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10063 if (RHS.isInvalid()) 10064 return QualType(); 10065 // Special case of NSObject attributes on c-style pointer types. 10066 if (ConvTy == IncompatiblePointer && 10067 ((Context.isObjCNSObjectType(LHSType) && 10068 RHSType->isObjCObjectPointerType()) || 10069 (Context.isObjCNSObjectType(RHSType) && 10070 LHSType->isObjCObjectPointerType()))) 10071 ConvTy = Compatible; 10072 10073 if (ConvTy == Compatible && 10074 LHSType->isObjCObjectType()) 10075 Diag(Loc, diag::err_objc_object_assignment) 10076 << LHSType; 10077 10078 // If the RHS is a unary plus or minus, check to see if they = and + are 10079 // right next to each other. If so, the user may have typo'd "x =+ 4" 10080 // instead of "x += 4". 10081 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10082 RHSCheck = ICE->getSubExpr(); 10083 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10084 if ((UO->getOpcode() == UO_Plus || 10085 UO->getOpcode() == UO_Minus) && 10086 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10087 // Only if the two operators are exactly adjacent. 10088 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10089 // And there is a space or other character before the subexpr of the 10090 // unary +/-. We don't want to warn on "x=-1". 10091 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10092 UO->getSubExpr()->getLocStart().isFileID()) { 10093 Diag(Loc, diag::warn_not_compound_assign) 10094 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10095 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10096 } 10097 } 10098 10099 if (ConvTy == Compatible) { 10100 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10101 // Warn about retain cycles where a block captures the LHS, but 10102 // not if the LHS is a simple variable into which the block is 10103 // being stored...unless that variable can be captured by reference! 10104 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10105 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10106 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10107 checkRetainCycles(LHSExpr, RHS.get()); 10108 10109 // It is safe to assign a weak reference into a strong variable. 10110 // Although this code can still have problems: 10111 // id x = self.weakProp; 10112 // id y = self.weakProp; 10113 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10114 // paths through the function. This should be revisited if 10115 // -Wrepeated-use-of-weak is made flow-sensitive. 10116 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10117 RHS.get()->getLocStart())) 10118 getCurFunction()->markSafeWeakUse(RHS.get()); 10119 10120 } else if (getLangOpts().ObjCAutoRefCount) { 10121 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10122 } 10123 } 10124 } else { 10125 // Compound assignment "x += y" 10126 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10127 } 10128 10129 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10130 RHS.get(), AA_Assigning)) 10131 return QualType(); 10132 10133 CheckForNullPointerDereference(*this, LHSExpr); 10134 10135 // C99 6.5.16p3: The type of an assignment expression is the type of the 10136 // left operand unless the left operand has qualified type, in which case 10137 // it is the unqualified version of the type of the left operand. 10138 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10139 // is converted to the type of the assignment expression (above). 10140 // C++ 5.17p1: the type of the assignment expression is that of its left 10141 // operand. 10142 return (getLangOpts().CPlusPlus 10143 ? LHSType : LHSType.getUnqualifiedType()); 10144 } 10145 10146 // Only ignore explicit casts to void. 10147 static bool IgnoreCommaOperand(const Expr *E) { 10148 E = E->IgnoreParens(); 10149 10150 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10151 if (CE->getCastKind() == CK_ToVoid) { 10152 return true; 10153 } 10154 } 10155 10156 return false; 10157 } 10158 10159 // Look for instances where it is likely the comma operator is confused with 10160 // another operator. There is a whitelist of acceptable expressions for the 10161 // left hand side of the comma operator, otherwise emit a warning. 10162 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10163 // No warnings in macros 10164 if (Loc.isMacroID()) 10165 return; 10166 10167 // Don't warn in template instantiations. 10168 if (!ActiveTemplateInstantiations.empty()) 10169 return; 10170 10171 // Scope isn't fine-grained enough to whitelist the specific cases, so 10172 // instead, skip more than needed, then call back into here with the 10173 // CommaVisitor in SemaStmt.cpp. 10174 // The whitelisted locations are the initialization and increment portions 10175 // of a for loop. The additional checks are on the condition of 10176 // if statements, do/while loops, and for loops. 10177 const unsigned ForIncrementFlags = 10178 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10179 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10180 const unsigned ScopeFlags = getCurScope()->getFlags(); 10181 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10182 (ScopeFlags & ForInitFlags) == ForInitFlags) 10183 return; 10184 10185 // If there are multiple comma operators used together, get the RHS of the 10186 // of the comma operator as the LHS. 10187 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10188 if (BO->getOpcode() != BO_Comma) 10189 break; 10190 LHS = BO->getRHS(); 10191 } 10192 10193 // Only allow some expressions on LHS to not warn. 10194 if (IgnoreCommaOperand(LHS)) 10195 return; 10196 10197 Diag(Loc, diag::warn_comma_operator); 10198 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10199 << LHS->getSourceRange() 10200 << FixItHint::CreateInsertion(LHS->getLocStart(), 10201 LangOpts.CPlusPlus ? "static_cast<void>(" 10202 : "(void)(") 10203 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10204 ")"); 10205 } 10206 10207 // C99 6.5.17 10208 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10209 SourceLocation Loc) { 10210 LHS = S.CheckPlaceholderExpr(LHS.get()); 10211 RHS = S.CheckPlaceholderExpr(RHS.get()); 10212 if (LHS.isInvalid() || RHS.isInvalid()) 10213 return QualType(); 10214 10215 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10216 // operands, but not unary promotions. 10217 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10218 10219 // So we treat the LHS as a ignored value, and in C++ we allow the 10220 // containing site to determine what should be done with the RHS. 10221 LHS = S.IgnoredValueConversions(LHS.get()); 10222 if (LHS.isInvalid()) 10223 return QualType(); 10224 10225 S.DiagnoseUnusedExprResult(LHS.get()); 10226 10227 if (!S.getLangOpts().CPlusPlus) { 10228 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10229 if (RHS.isInvalid()) 10230 return QualType(); 10231 if (!RHS.get()->getType()->isVoidType()) 10232 S.RequireCompleteType(Loc, RHS.get()->getType(), 10233 diag::err_incomplete_type); 10234 } 10235 10236 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10237 S.DiagnoseCommaOperator(LHS.get(), Loc); 10238 10239 return RHS.get()->getType(); 10240 } 10241 10242 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10243 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10244 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10245 ExprValueKind &VK, 10246 ExprObjectKind &OK, 10247 SourceLocation OpLoc, 10248 bool IsInc, bool IsPrefix) { 10249 if (Op->isTypeDependent()) 10250 return S.Context.DependentTy; 10251 10252 QualType ResType = Op->getType(); 10253 // Atomic types can be used for increment / decrement where the non-atomic 10254 // versions can, so ignore the _Atomic() specifier for the purpose of 10255 // checking. 10256 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10257 ResType = ResAtomicType->getValueType(); 10258 10259 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10260 10261 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10262 // Decrement of bool is not allowed. 10263 if (!IsInc) { 10264 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10265 return QualType(); 10266 } 10267 // Increment of bool sets it to true, but is deprecated. 10268 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10269 : diag::warn_increment_bool) 10270 << Op->getSourceRange(); 10271 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10272 // Error on enum increments and decrements in C++ mode 10273 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10274 return QualType(); 10275 } else if (ResType->isRealType()) { 10276 // OK! 10277 } else if (ResType->isPointerType()) { 10278 // C99 6.5.2.4p2, 6.5.6p2 10279 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10280 return QualType(); 10281 } else if (ResType->isObjCObjectPointerType()) { 10282 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10283 // Otherwise, we just need a complete type. 10284 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10285 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10286 return QualType(); 10287 } else if (ResType->isAnyComplexType()) { 10288 // C99 does not support ++/-- on complex types, we allow as an extension. 10289 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10290 << ResType << Op->getSourceRange(); 10291 } else if (ResType->isPlaceholderType()) { 10292 ExprResult PR = S.CheckPlaceholderExpr(Op); 10293 if (PR.isInvalid()) return QualType(); 10294 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10295 IsInc, IsPrefix); 10296 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10297 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10298 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10299 (ResType->getAs<VectorType>()->getVectorKind() != 10300 VectorType::AltiVecBool)) { 10301 // The z vector extensions allow ++ and -- for non-bool vectors. 10302 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10303 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10304 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10305 } else { 10306 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10307 << ResType << int(IsInc) << Op->getSourceRange(); 10308 return QualType(); 10309 } 10310 // At this point, we know we have a real, complex or pointer type. 10311 // Now make sure the operand is a modifiable lvalue. 10312 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10313 return QualType(); 10314 // In C++, a prefix increment is the same type as the operand. Otherwise 10315 // (in C or with postfix), the increment is the unqualified type of the 10316 // operand. 10317 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10318 VK = VK_LValue; 10319 OK = Op->getObjectKind(); 10320 return ResType; 10321 } else { 10322 VK = VK_RValue; 10323 return ResType.getUnqualifiedType(); 10324 } 10325 } 10326 10327 10328 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10329 /// This routine allows us to typecheck complex/recursive expressions 10330 /// where the declaration is needed for type checking. We only need to 10331 /// handle cases when the expression references a function designator 10332 /// or is an lvalue. Here are some examples: 10333 /// - &(x) => x 10334 /// - &*****f => f for f a function designator. 10335 /// - &s.xx => s 10336 /// - &s.zz[1].yy -> s, if zz is an array 10337 /// - *(x + 1) -> x, if x is an array 10338 /// - &"123"[2] -> 0 10339 /// - & __real__ x -> x 10340 static ValueDecl *getPrimaryDecl(Expr *E) { 10341 switch (E->getStmtClass()) { 10342 case Stmt::DeclRefExprClass: 10343 return cast<DeclRefExpr>(E)->getDecl(); 10344 case Stmt::MemberExprClass: 10345 // If this is an arrow operator, the address is an offset from 10346 // the base's value, so the object the base refers to is 10347 // irrelevant. 10348 if (cast<MemberExpr>(E)->isArrow()) 10349 return nullptr; 10350 // Otherwise, the expression refers to a part of the base 10351 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10352 case Stmt::ArraySubscriptExprClass: { 10353 // FIXME: This code shouldn't be necessary! We should catch the implicit 10354 // promotion of register arrays earlier. 10355 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10356 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10357 if (ICE->getSubExpr()->getType()->isArrayType()) 10358 return getPrimaryDecl(ICE->getSubExpr()); 10359 } 10360 return nullptr; 10361 } 10362 case Stmt::UnaryOperatorClass: { 10363 UnaryOperator *UO = cast<UnaryOperator>(E); 10364 10365 switch(UO->getOpcode()) { 10366 case UO_Real: 10367 case UO_Imag: 10368 case UO_Extension: 10369 return getPrimaryDecl(UO->getSubExpr()); 10370 default: 10371 return nullptr; 10372 } 10373 } 10374 case Stmt::ParenExprClass: 10375 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10376 case Stmt::ImplicitCastExprClass: 10377 // If the result of an implicit cast is an l-value, we care about 10378 // the sub-expression; otherwise, the result here doesn't matter. 10379 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10380 default: 10381 return nullptr; 10382 } 10383 } 10384 10385 namespace { 10386 enum { 10387 AO_Bit_Field = 0, 10388 AO_Vector_Element = 1, 10389 AO_Property_Expansion = 2, 10390 AO_Register_Variable = 3, 10391 AO_No_Error = 4 10392 }; 10393 } 10394 /// \brief Diagnose invalid operand for address of operations. 10395 /// 10396 /// \param Type The type of operand which cannot have its address taken. 10397 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10398 Expr *E, unsigned Type) { 10399 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10400 } 10401 10402 /// CheckAddressOfOperand - The operand of & must be either a function 10403 /// designator or an lvalue designating an object. If it is an lvalue, the 10404 /// object cannot be declared with storage class register or be a bit field. 10405 /// Note: The usual conversions are *not* applied to the operand of the & 10406 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10407 /// In C++, the operand might be an overloaded function name, in which case 10408 /// we allow the '&' but retain the overloaded-function type. 10409 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10410 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10411 if (PTy->getKind() == BuiltinType::Overload) { 10412 Expr *E = OrigOp.get()->IgnoreParens(); 10413 if (!isa<OverloadExpr>(E)) { 10414 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10415 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10416 << OrigOp.get()->getSourceRange(); 10417 return QualType(); 10418 } 10419 10420 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10421 if (isa<UnresolvedMemberExpr>(Ovl)) 10422 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10423 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10424 << OrigOp.get()->getSourceRange(); 10425 return QualType(); 10426 } 10427 10428 return Context.OverloadTy; 10429 } 10430 10431 if (PTy->getKind() == BuiltinType::UnknownAny) 10432 return Context.UnknownAnyTy; 10433 10434 if (PTy->getKind() == BuiltinType::BoundMember) { 10435 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10436 << OrigOp.get()->getSourceRange(); 10437 return QualType(); 10438 } 10439 10440 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10441 if (OrigOp.isInvalid()) return QualType(); 10442 } 10443 10444 if (OrigOp.get()->isTypeDependent()) 10445 return Context.DependentTy; 10446 10447 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10448 10449 // Make sure to ignore parentheses in subsequent checks 10450 Expr *op = OrigOp.get()->IgnoreParens(); 10451 10452 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10453 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10454 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10455 return QualType(); 10456 } 10457 10458 if (getLangOpts().C99) { 10459 // Implement C99-only parts of addressof rules. 10460 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10461 if (uOp->getOpcode() == UO_Deref) 10462 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10463 // (assuming the deref expression is valid). 10464 return uOp->getSubExpr()->getType(); 10465 } 10466 // Technically, there should be a check for array subscript 10467 // expressions here, but the result of one is always an lvalue anyway. 10468 } 10469 ValueDecl *dcl = getPrimaryDecl(op); 10470 10471 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10472 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10473 op->getLocStart())) 10474 return QualType(); 10475 10476 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10477 unsigned AddressOfError = AO_No_Error; 10478 10479 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10480 bool sfinae = (bool)isSFINAEContext(); 10481 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10482 : diag::ext_typecheck_addrof_temporary) 10483 << op->getType() << op->getSourceRange(); 10484 if (sfinae) 10485 return QualType(); 10486 // Materialize the temporary as an lvalue so that we can take its address. 10487 OrigOp = op = 10488 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10489 } else if (isa<ObjCSelectorExpr>(op)) { 10490 return Context.getPointerType(op->getType()); 10491 } else if (lval == Expr::LV_MemberFunction) { 10492 // If it's an instance method, make a member pointer. 10493 // The expression must have exactly the form &A::foo. 10494 10495 // If the underlying expression isn't a decl ref, give up. 10496 if (!isa<DeclRefExpr>(op)) { 10497 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10498 << OrigOp.get()->getSourceRange(); 10499 return QualType(); 10500 } 10501 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10502 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10503 10504 // The id-expression was parenthesized. 10505 if (OrigOp.get() != DRE) { 10506 Diag(OpLoc, diag::err_parens_pointer_member_function) 10507 << OrigOp.get()->getSourceRange(); 10508 10509 // The method was named without a qualifier. 10510 } else if (!DRE->getQualifier()) { 10511 if (MD->getParent()->getName().empty()) 10512 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10513 << op->getSourceRange(); 10514 else { 10515 SmallString<32> Str; 10516 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10517 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10518 << op->getSourceRange() 10519 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10520 } 10521 } 10522 10523 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10524 if (isa<CXXDestructorDecl>(MD)) 10525 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10526 10527 QualType MPTy = Context.getMemberPointerType( 10528 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10529 // Under the MS ABI, lock down the inheritance model now. 10530 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10531 (void)isCompleteType(OpLoc, MPTy); 10532 return MPTy; 10533 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10534 // C99 6.5.3.2p1 10535 // The operand must be either an l-value or a function designator 10536 if (!op->getType()->isFunctionType()) { 10537 // Use a special diagnostic for loads from property references. 10538 if (isa<PseudoObjectExpr>(op)) { 10539 AddressOfError = AO_Property_Expansion; 10540 } else { 10541 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10542 << op->getType() << op->getSourceRange(); 10543 return QualType(); 10544 } 10545 } 10546 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10547 // The operand cannot be a bit-field 10548 AddressOfError = AO_Bit_Field; 10549 } else if (op->getObjectKind() == OK_VectorComponent) { 10550 // The operand cannot be an element of a vector 10551 AddressOfError = AO_Vector_Element; 10552 } else if (dcl) { // C99 6.5.3.2p1 10553 // We have an lvalue with a decl. Make sure the decl is not declared 10554 // with the register storage-class specifier. 10555 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10556 // in C++ it is not error to take address of a register 10557 // variable (c++03 7.1.1P3) 10558 if (vd->getStorageClass() == SC_Register && 10559 !getLangOpts().CPlusPlus) { 10560 AddressOfError = AO_Register_Variable; 10561 } 10562 } else if (isa<MSPropertyDecl>(dcl)) { 10563 AddressOfError = AO_Property_Expansion; 10564 } else if (isa<FunctionTemplateDecl>(dcl)) { 10565 return Context.OverloadTy; 10566 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10567 // Okay: we can take the address of a field. 10568 // Could be a pointer to member, though, if there is an explicit 10569 // scope qualifier for the class. 10570 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10571 DeclContext *Ctx = dcl->getDeclContext(); 10572 if (Ctx && Ctx->isRecord()) { 10573 if (dcl->getType()->isReferenceType()) { 10574 Diag(OpLoc, 10575 diag::err_cannot_form_pointer_to_member_of_reference_type) 10576 << dcl->getDeclName() << dcl->getType(); 10577 return QualType(); 10578 } 10579 10580 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10581 Ctx = Ctx->getParent(); 10582 10583 QualType MPTy = Context.getMemberPointerType( 10584 op->getType(), 10585 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10586 // Under the MS ABI, lock down the inheritance model now. 10587 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10588 (void)isCompleteType(OpLoc, MPTy); 10589 return MPTy; 10590 } 10591 } 10592 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10593 !isa<BindingDecl>(dcl)) 10594 llvm_unreachable("Unknown/unexpected decl type"); 10595 } 10596 10597 if (AddressOfError != AO_No_Error) { 10598 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10599 return QualType(); 10600 } 10601 10602 if (lval == Expr::LV_IncompleteVoidType) { 10603 // Taking the address of a void variable is technically illegal, but we 10604 // allow it in cases which are otherwise valid. 10605 // Example: "extern void x; void* y = &x;". 10606 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10607 } 10608 10609 // If the operand has type "type", the result has type "pointer to type". 10610 if (op->getType()->isObjCObjectType()) 10611 return Context.getObjCObjectPointerType(op->getType()); 10612 10613 CheckAddressOfPackedMember(op); 10614 10615 return Context.getPointerType(op->getType()); 10616 } 10617 10618 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10619 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10620 if (!DRE) 10621 return; 10622 const Decl *D = DRE->getDecl(); 10623 if (!D) 10624 return; 10625 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10626 if (!Param) 10627 return; 10628 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10629 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10630 return; 10631 if (FunctionScopeInfo *FD = S.getCurFunction()) 10632 if (!FD->ModifiedNonNullParams.count(Param)) 10633 FD->ModifiedNonNullParams.insert(Param); 10634 } 10635 10636 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10637 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10638 SourceLocation OpLoc) { 10639 if (Op->isTypeDependent()) 10640 return S.Context.DependentTy; 10641 10642 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10643 if (ConvResult.isInvalid()) 10644 return QualType(); 10645 Op = ConvResult.get(); 10646 QualType OpTy = Op->getType(); 10647 QualType Result; 10648 10649 if (isa<CXXReinterpretCastExpr>(Op)) { 10650 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10651 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10652 Op->getSourceRange()); 10653 } 10654 10655 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10656 { 10657 Result = PT->getPointeeType(); 10658 } 10659 else if (const ObjCObjectPointerType *OPT = 10660 OpTy->getAs<ObjCObjectPointerType>()) 10661 Result = OPT->getPointeeType(); 10662 else { 10663 ExprResult PR = S.CheckPlaceholderExpr(Op); 10664 if (PR.isInvalid()) return QualType(); 10665 if (PR.get() != Op) 10666 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10667 } 10668 10669 if (Result.isNull()) { 10670 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10671 << OpTy << Op->getSourceRange(); 10672 return QualType(); 10673 } 10674 10675 // Note that per both C89 and C99, indirection is always legal, even if Result 10676 // is an incomplete type or void. It would be possible to warn about 10677 // dereferencing a void pointer, but it's completely well-defined, and such a 10678 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10679 // for pointers to 'void' but is fine for any other pointer type: 10680 // 10681 // C++ [expr.unary.op]p1: 10682 // [...] the expression to which [the unary * operator] is applied shall 10683 // be a pointer to an object type, or a pointer to a function type 10684 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10685 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10686 << OpTy << Op->getSourceRange(); 10687 10688 // Dereferences are usually l-values... 10689 VK = VK_LValue; 10690 10691 // ...except that certain expressions are never l-values in C. 10692 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10693 VK = VK_RValue; 10694 10695 return Result; 10696 } 10697 10698 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10699 BinaryOperatorKind Opc; 10700 switch (Kind) { 10701 default: llvm_unreachable("Unknown binop!"); 10702 case tok::periodstar: Opc = BO_PtrMemD; break; 10703 case tok::arrowstar: Opc = BO_PtrMemI; break; 10704 case tok::star: Opc = BO_Mul; break; 10705 case tok::slash: Opc = BO_Div; break; 10706 case tok::percent: Opc = BO_Rem; break; 10707 case tok::plus: Opc = BO_Add; break; 10708 case tok::minus: Opc = BO_Sub; break; 10709 case tok::lessless: Opc = BO_Shl; break; 10710 case tok::greatergreater: Opc = BO_Shr; break; 10711 case tok::lessequal: Opc = BO_LE; break; 10712 case tok::less: Opc = BO_LT; break; 10713 case tok::greaterequal: Opc = BO_GE; break; 10714 case tok::greater: Opc = BO_GT; break; 10715 case tok::exclaimequal: Opc = BO_NE; break; 10716 case tok::equalequal: Opc = BO_EQ; break; 10717 case tok::amp: Opc = BO_And; break; 10718 case tok::caret: Opc = BO_Xor; break; 10719 case tok::pipe: Opc = BO_Or; break; 10720 case tok::ampamp: Opc = BO_LAnd; break; 10721 case tok::pipepipe: Opc = BO_LOr; break; 10722 case tok::equal: Opc = BO_Assign; break; 10723 case tok::starequal: Opc = BO_MulAssign; break; 10724 case tok::slashequal: Opc = BO_DivAssign; break; 10725 case tok::percentequal: Opc = BO_RemAssign; break; 10726 case tok::plusequal: Opc = BO_AddAssign; break; 10727 case tok::minusequal: Opc = BO_SubAssign; break; 10728 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10729 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10730 case tok::ampequal: Opc = BO_AndAssign; break; 10731 case tok::caretequal: Opc = BO_XorAssign; break; 10732 case tok::pipeequal: Opc = BO_OrAssign; break; 10733 case tok::comma: Opc = BO_Comma; break; 10734 } 10735 return Opc; 10736 } 10737 10738 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10739 tok::TokenKind Kind) { 10740 UnaryOperatorKind Opc; 10741 switch (Kind) { 10742 default: llvm_unreachable("Unknown unary op!"); 10743 case tok::plusplus: Opc = UO_PreInc; break; 10744 case tok::minusminus: Opc = UO_PreDec; break; 10745 case tok::amp: Opc = UO_AddrOf; break; 10746 case tok::star: Opc = UO_Deref; break; 10747 case tok::plus: Opc = UO_Plus; break; 10748 case tok::minus: Opc = UO_Minus; break; 10749 case tok::tilde: Opc = UO_Not; break; 10750 case tok::exclaim: Opc = UO_LNot; break; 10751 case tok::kw___real: Opc = UO_Real; break; 10752 case tok::kw___imag: Opc = UO_Imag; break; 10753 case tok::kw___extension__: Opc = UO_Extension; break; 10754 } 10755 return Opc; 10756 } 10757 10758 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10759 /// This warning is only emitted for builtin assignment operations. It is also 10760 /// suppressed in the event of macro expansions. 10761 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10762 SourceLocation OpLoc) { 10763 if (!S.ActiveTemplateInstantiations.empty()) 10764 return; 10765 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10766 return; 10767 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10768 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10769 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10770 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10771 if (!LHSDeclRef || !RHSDeclRef || 10772 LHSDeclRef->getLocation().isMacroID() || 10773 RHSDeclRef->getLocation().isMacroID()) 10774 return; 10775 const ValueDecl *LHSDecl = 10776 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10777 const ValueDecl *RHSDecl = 10778 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10779 if (LHSDecl != RHSDecl) 10780 return; 10781 if (LHSDecl->getType().isVolatileQualified()) 10782 return; 10783 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10784 if (RefTy->getPointeeType().isVolatileQualified()) 10785 return; 10786 10787 S.Diag(OpLoc, diag::warn_self_assignment) 10788 << LHSDeclRef->getType() 10789 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10790 } 10791 10792 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10793 /// is usually indicative of introspection within the Objective-C pointer. 10794 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10795 SourceLocation OpLoc) { 10796 if (!S.getLangOpts().ObjC1) 10797 return; 10798 10799 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10800 const Expr *LHS = L.get(); 10801 const Expr *RHS = R.get(); 10802 10803 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10804 ObjCPointerExpr = LHS; 10805 OtherExpr = RHS; 10806 } 10807 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10808 ObjCPointerExpr = RHS; 10809 OtherExpr = LHS; 10810 } 10811 10812 // This warning is deliberately made very specific to reduce false 10813 // positives with logic that uses '&' for hashing. This logic mainly 10814 // looks for code trying to introspect into tagged pointers, which 10815 // code should generally never do. 10816 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10817 unsigned Diag = diag::warn_objc_pointer_masking; 10818 // Determine if we are introspecting the result of performSelectorXXX. 10819 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10820 // Special case messages to -performSelector and friends, which 10821 // can return non-pointer values boxed in a pointer value. 10822 // Some clients may wish to silence warnings in this subcase. 10823 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10824 Selector S = ME->getSelector(); 10825 StringRef SelArg0 = S.getNameForSlot(0); 10826 if (SelArg0.startswith("performSelector")) 10827 Diag = diag::warn_objc_pointer_masking_performSelector; 10828 } 10829 10830 S.Diag(OpLoc, Diag) 10831 << ObjCPointerExpr->getSourceRange(); 10832 } 10833 } 10834 10835 static NamedDecl *getDeclFromExpr(Expr *E) { 10836 if (!E) 10837 return nullptr; 10838 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10839 return DRE->getDecl(); 10840 if (auto *ME = dyn_cast<MemberExpr>(E)) 10841 return ME->getMemberDecl(); 10842 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10843 return IRE->getDecl(); 10844 return nullptr; 10845 } 10846 10847 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10848 /// operator @p Opc at location @c TokLoc. This routine only supports 10849 /// built-in operations; ActOnBinOp handles overloaded operators. 10850 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10851 BinaryOperatorKind Opc, 10852 Expr *LHSExpr, Expr *RHSExpr) { 10853 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10854 // The syntax only allows initializer lists on the RHS of assignment, 10855 // so we don't need to worry about accepting invalid code for 10856 // non-assignment operators. 10857 // C++11 5.17p9: 10858 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10859 // of x = {} is x = T(). 10860 InitializationKind Kind = 10861 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10862 InitializedEntity Entity = 10863 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10864 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10865 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10866 if (Init.isInvalid()) 10867 return Init; 10868 RHSExpr = Init.get(); 10869 } 10870 10871 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10872 QualType ResultTy; // Result type of the binary operator. 10873 // The following two variables are used for compound assignment operators 10874 QualType CompLHSTy; // Type of LHS after promotions for computation 10875 QualType CompResultTy; // Type of computation result 10876 ExprValueKind VK = VK_RValue; 10877 ExprObjectKind OK = OK_Ordinary; 10878 10879 if (!getLangOpts().CPlusPlus) { 10880 // C cannot handle TypoExpr nodes on either side of a binop because it 10881 // doesn't handle dependent types properly, so make sure any TypoExprs have 10882 // been dealt with before checking the operands. 10883 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10884 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10885 if (Opc != BO_Assign) 10886 return ExprResult(E); 10887 // Avoid correcting the RHS to the same Expr as the LHS. 10888 Decl *D = getDeclFromExpr(E); 10889 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10890 }); 10891 if (!LHS.isUsable() || !RHS.isUsable()) 10892 return ExprError(); 10893 } 10894 10895 if (getLangOpts().OpenCL) { 10896 QualType LHSTy = LHSExpr->getType(); 10897 QualType RHSTy = RHSExpr->getType(); 10898 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10899 // the ATOMIC_VAR_INIT macro. 10900 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 10901 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10902 if (BO_Assign == Opc) 10903 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10904 else 10905 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10906 return ExprError(); 10907 } 10908 10909 // OpenCL special types - image, sampler, pipe, and blocks are to be used 10910 // only with a builtin functions and therefore should be disallowed here. 10911 if (LHSTy->isImageType() || RHSTy->isImageType() || 10912 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 10913 LHSTy->isPipeType() || RHSTy->isPipeType() || 10914 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 10915 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10916 return ExprError(); 10917 } 10918 } 10919 10920 switch (Opc) { 10921 case BO_Assign: 10922 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10923 if (getLangOpts().CPlusPlus && 10924 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10925 VK = LHS.get()->getValueKind(); 10926 OK = LHS.get()->getObjectKind(); 10927 } 10928 if (!ResultTy.isNull()) { 10929 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10930 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10931 } 10932 RecordModifiableNonNullParam(*this, LHS.get()); 10933 break; 10934 case BO_PtrMemD: 10935 case BO_PtrMemI: 10936 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10937 Opc == BO_PtrMemI); 10938 break; 10939 case BO_Mul: 10940 case BO_Div: 10941 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10942 Opc == BO_Div); 10943 break; 10944 case BO_Rem: 10945 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10946 break; 10947 case BO_Add: 10948 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10949 break; 10950 case BO_Sub: 10951 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10952 break; 10953 case BO_Shl: 10954 case BO_Shr: 10955 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10956 break; 10957 case BO_LE: 10958 case BO_LT: 10959 case BO_GE: 10960 case BO_GT: 10961 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10962 break; 10963 case BO_EQ: 10964 case BO_NE: 10965 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10966 break; 10967 case BO_And: 10968 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10969 case BO_Xor: 10970 case BO_Or: 10971 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10972 break; 10973 case BO_LAnd: 10974 case BO_LOr: 10975 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10976 break; 10977 case BO_MulAssign: 10978 case BO_DivAssign: 10979 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10980 Opc == BO_DivAssign); 10981 CompLHSTy = CompResultTy; 10982 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10983 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10984 break; 10985 case BO_RemAssign: 10986 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10987 CompLHSTy = CompResultTy; 10988 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10989 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10990 break; 10991 case BO_AddAssign: 10992 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10993 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10994 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10995 break; 10996 case BO_SubAssign: 10997 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10998 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10999 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11000 break; 11001 case BO_ShlAssign: 11002 case BO_ShrAssign: 11003 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11004 CompLHSTy = CompResultTy; 11005 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11006 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11007 break; 11008 case BO_AndAssign: 11009 case BO_OrAssign: // fallthrough 11010 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11011 case BO_XorAssign: 11012 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 11013 CompLHSTy = CompResultTy; 11014 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11015 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11016 break; 11017 case BO_Comma: 11018 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11019 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11020 VK = RHS.get()->getValueKind(); 11021 OK = RHS.get()->getObjectKind(); 11022 } 11023 break; 11024 } 11025 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11026 return ExprError(); 11027 11028 // Check for array bounds violations for both sides of the BinaryOperator 11029 CheckArrayAccess(LHS.get()); 11030 CheckArrayAccess(RHS.get()); 11031 11032 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11033 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11034 &Context.Idents.get("object_setClass"), 11035 SourceLocation(), LookupOrdinaryName); 11036 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11037 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11038 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11039 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11040 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11041 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11042 } 11043 else 11044 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11045 } 11046 else if (const ObjCIvarRefExpr *OIRE = 11047 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11048 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11049 11050 if (CompResultTy.isNull()) 11051 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11052 OK, OpLoc, FPFeatures.fp_contract); 11053 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11054 OK_ObjCProperty) { 11055 VK = VK_LValue; 11056 OK = LHS.get()->getObjectKind(); 11057 } 11058 return new (Context) CompoundAssignOperator( 11059 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11060 OpLoc, FPFeatures.fp_contract); 11061 } 11062 11063 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11064 /// operators are mixed in a way that suggests that the programmer forgot that 11065 /// comparison operators have higher precedence. The most typical example of 11066 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11067 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11068 SourceLocation OpLoc, Expr *LHSExpr, 11069 Expr *RHSExpr) { 11070 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11071 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11072 11073 // Check that one of the sides is a comparison operator and the other isn't. 11074 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11075 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11076 if (isLeftComp == isRightComp) 11077 return; 11078 11079 // Bitwise operations are sometimes used as eager logical ops. 11080 // Don't diagnose this. 11081 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11082 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11083 if (isLeftBitwise || isRightBitwise) 11084 return; 11085 11086 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11087 OpLoc) 11088 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11089 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11090 SourceRange ParensRange = isLeftComp ? 11091 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11092 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11093 11094 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11095 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11096 SuggestParentheses(Self, OpLoc, 11097 Self.PDiag(diag::note_precedence_silence) << OpStr, 11098 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11099 SuggestParentheses(Self, OpLoc, 11100 Self.PDiag(diag::note_precedence_bitwise_first) 11101 << BinaryOperator::getOpcodeStr(Opc), 11102 ParensRange); 11103 } 11104 11105 /// \brief It accepts a '&&' expr that is inside a '||' one. 11106 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11107 /// in parentheses. 11108 static void 11109 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11110 BinaryOperator *Bop) { 11111 assert(Bop->getOpcode() == BO_LAnd); 11112 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11113 << Bop->getSourceRange() << OpLoc; 11114 SuggestParentheses(Self, Bop->getOperatorLoc(), 11115 Self.PDiag(diag::note_precedence_silence) 11116 << Bop->getOpcodeStr(), 11117 Bop->getSourceRange()); 11118 } 11119 11120 /// \brief Returns true if the given expression can be evaluated as a constant 11121 /// 'true'. 11122 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11123 bool Res; 11124 return !E->isValueDependent() && 11125 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11126 } 11127 11128 /// \brief Returns true if the given expression can be evaluated as a constant 11129 /// 'false'. 11130 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11131 bool Res; 11132 return !E->isValueDependent() && 11133 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11134 } 11135 11136 /// \brief Look for '&&' in the left hand of a '||' expr. 11137 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11138 Expr *LHSExpr, Expr *RHSExpr) { 11139 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11140 if (Bop->getOpcode() == BO_LAnd) { 11141 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11142 if (EvaluatesAsFalse(S, RHSExpr)) 11143 return; 11144 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11145 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11146 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11147 } else if (Bop->getOpcode() == BO_LOr) { 11148 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11149 // If it's "a || b && 1 || c" we didn't warn earlier for 11150 // "a || b && 1", but warn now. 11151 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11152 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11153 } 11154 } 11155 } 11156 } 11157 11158 /// \brief Look for '&&' in the right hand of a '||' expr. 11159 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11160 Expr *LHSExpr, Expr *RHSExpr) { 11161 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11162 if (Bop->getOpcode() == BO_LAnd) { 11163 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11164 if (EvaluatesAsFalse(S, LHSExpr)) 11165 return; 11166 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11167 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11168 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11169 } 11170 } 11171 } 11172 11173 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11174 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11175 /// the '&' expression in parentheses. 11176 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11177 SourceLocation OpLoc, Expr *SubExpr) { 11178 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11179 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11180 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11181 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11182 << Bop->getSourceRange() << OpLoc; 11183 SuggestParentheses(S, Bop->getOperatorLoc(), 11184 S.PDiag(diag::note_precedence_silence) 11185 << Bop->getOpcodeStr(), 11186 Bop->getSourceRange()); 11187 } 11188 } 11189 } 11190 11191 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11192 Expr *SubExpr, StringRef Shift) { 11193 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11194 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11195 StringRef Op = Bop->getOpcodeStr(); 11196 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11197 << Bop->getSourceRange() << OpLoc << Shift << Op; 11198 SuggestParentheses(S, Bop->getOperatorLoc(), 11199 S.PDiag(diag::note_precedence_silence) << Op, 11200 Bop->getSourceRange()); 11201 } 11202 } 11203 } 11204 11205 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11206 Expr *LHSExpr, Expr *RHSExpr) { 11207 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11208 if (!OCE) 11209 return; 11210 11211 FunctionDecl *FD = OCE->getDirectCallee(); 11212 if (!FD || !FD->isOverloadedOperator()) 11213 return; 11214 11215 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11216 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11217 return; 11218 11219 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11220 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11221 << (Kind == OO_LessLess); 11222 SuggestParentheses(S, OCE->getOperatorLoc(), 11223 S.PDiag(diag::note_precedence_silence) 11224 << (Kind == OO_LessLess ? "<<" : ">>"), 11225 OCE->getSourceRange()); 11226 SuggestParentheses(S, OpLoc, 11227 S.PDiag(diag::note_evaluate_comparison_first), 11228 SourceRange(OCE->getArg(1)->getLocStart(), 11229 RHSExpr->getLocEnd())); 11230 } 11231 11232 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11233 /// precedence. 11234 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11235 SourceLocation OpLoc, Expr *LHSExpr, 11236 Expr *RHSExpr){ 11237 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11238 if (BinaryOperator::isBitwiseOp(Opc)) 11239 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11240 11241 // Diagnose "arg1 & arg2 | arg3" 11242 if ((Opc == BO_Or || Opc == BO_Xor) && 11243 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11244 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11245 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11246 } 11247 11248 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11249 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11250 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11251 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11252 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11253 } 11254 11255 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11256 || Opc == BO_Shr) { 11257 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11258 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11259 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11260 } 11261 11262 // Warn on overloaded shift operators and comparisons, such as: 11263 // cout << 5 == 4; 11264 if (BinaryOperator::isComparisonOp(Opc)) 11265 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11266 } 11267 11268 // Binary Operators. 'Tok' is the token for the operator. 11269 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11270 tok::TokenKind Kind, 11271 Expr *LHSExpr, Expr *RHSExpr) { 11272 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11273 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11274 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11275 11276 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11277 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11278 11279 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11280 } 11281 11282 /// Build an overloaded binary operator expression in the given scope. 11283 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11284 BinaryOperatorKind Opc, 11285 Expr *LHS, Expr *RHS) { 11286 // Find all of the overloaded operators visible from this 11287 // point. We perform both an operator-name lookup from the local 11288 // scope and an argument-dependent lookup based on the types of 11289 // the arguments. 11290 UnresolvedSet<16> Functions; 11291 OverloadedOperatorKind OverOp 11292 = BinaryOperator::getOverloadedOperator(Opc); 11293 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11294 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11295 RHS->getType(), Functions); 11296 11297 // Build the (potentially-overloaded, potentially-dependent) 11298 // binary operation. 11299 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11300 } 11301 11302 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11303 BinaryOperatorKind Opc, 11304 Expr *LHSExpr, Expr *RHSExpr) { 11305 // We want to end up calling one of checkPseudoObjectAssignment 11306 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11307 // both expressions are overloadable or either is type-dependent), 11308 // or CreateBuiltinBinOp (in any other case). We also want to get 11309 // any placeholder types out of the way. 11310 11311 // Handle pseudo-objects in the LHS. 11312 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11313 // Assignments with a pseudo-object l-value need special analysis. 11314 if (pty->getKind() == BuiltinType::PseudoObject && 11315 BinaryOperator::isAssignmentOp(Opc)) 11316 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11317 11318 // Don't resolve overloads if the other type is overloadable. 11319 if (pty->getKind() == BuiltinType::Overload) { 11320 // We can't actually test that if we still have a placeholder, 11321 // though. Fortunately, none of the exceptions we see in that 11322 // code below are valid when the LHS is an overload set. Note 11323 // that an overload set can be dependently-typed, but it never 11324 // instantiates to having an overloadable type. 11325 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11326 if (resolvedRHS.isInvalid()) return ExprError(); 11327 RHSExpr = resolvedRHS.get(); 11328 11329 if (RHSExpr->isTypeDependent() || 11330 RHSExpr->getType()->isOverloadableType()) 11331 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11332 } 11333 11334 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11335 if (LHS.isInvalid()) return ExprError(); 11336 LHSExpr = LHS.get(); 11337 } 11338 11339 // Handle pseudo-objects in the RHS. 11340 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11341 // An overload in the RHS can potentially be resolved by the type 11342 // being assigned to. 11343 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11344 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11345 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11346 11347 if (LHSExpr->getType()->isOverloadableType()) 11348 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11349 11350 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11351 } 11352 11353 // Don't resolve overloads if the other type is overloadable. 11354 if (pty->getKind() == BuiltinType::Overload && 11355 LHSExpr->getType()->isOverloadableType()) 11356 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11357 11358 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11359 if (!resolvedRHS.isUsable()) return ExprError(); 11360 RHSExpr = resolvedRHS.get(); 11361 } 11362 11363 if (getLangOpts().CPlusPlus) { 11364 // If either expression is type-dependent, always build an 11365 // overloaded op. 11366 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11367 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11368 11369 // Otherwise, build an overloaded op if either expression has an 11370 // overloadable type. 11371 if (LHSExpr->getType()->isOverloadableType() || 11372 RHSExpr->getType()->isOverloadableType()) 11373 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11374 } 11375 11376 // Build a built-in binary operation. 11377 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11378 } 11379 11380 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11381 UnaryOperatorKind Opc, 11382 Expr *InputExpr) { 11383 ExprResult Input = InputExpr; 11384 ExprValueKind VK = VK_RValue; 11385 ExprObjectKind OK = OK_Ordinary; 11386 QualType resultType; 11387 if (getLangOpts().OpenCL) { 11388 QualType Ty = InputExpr->getType(); 11389 // The only legal unary operation for atomics is '&'. 11390 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11391 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11392 // only with a builtin functions and therefore should be disallowed here. 11393 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11394 || Ty->isBlockPointerType())) { 11395 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11396 << InputExpr->getType() 11397 << Input.get()->getSourceRange()); 11398 } 11399 } 11400 switch (Opc) { 11401 case UO_PreInc: 11402 case UO_PreDec: 11403 case UO_PostInc: 11404 case UO_PostDec: 11405 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11406 OpLoc, 11407 Opc == UO_PreInc || 11408 Opc == UO_PostInc, 11409 Opc == UO_PreInc || 11410 Opc == UO_PreDec); 11411 break; 11412 case UO_AddrOf: 11413 resultType = CheckAddressOfOperand(Input, OpLoc); 11414 RecordModifiableNonNullParam(*this, InputExpr); 11415 break; 11416 case UO_Deref: { 11417 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11418 if (Input.isInvalid()) return ExprError(); 11419 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11420 break; 11421 } 11422 case UO_Plus: 11423 case UO_Minus: 11424 Input = UsualUnaryConversions(Input.get()); 11425 if (Input.isInvalid()) return ExprError(); 11426 resultType = Input.get()->getType(); 11427 if (resultType->isDependentType()) 11428 break; 11429 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11430 break; 11431 else if (resultType->isVectorType() && 11432 // The z vector extensions don't allow + or - with bool vectors. 11433 (!Context.getLangOpts().ZVector || 11434 resultType->getAs<VectorType>()->getVectorKind() != 11435 VectorType::AltiVecBool)) 11436 break; 11437 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11438 Opc == UO_Plus && 11439 resultType->isPointerType()) 11440 break; 11441 11442 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11443 << resultType << Input.get()->getSourceRange()); 11444 11445 case UO_Not: // bitwise complement 11446 Input = UsualUnaryConversions(Input.get()); 11447 if (Input.isInvalid()) 11448 return ExprError(); 11449 resultType = Input.get()->getType(); 11450 if (resultType->isDependentType()) 11451 break; 11452 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11453 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11454 // C99 does not support '~' for complex conjugation. 11455 Diag(OpLoc, diag::ext_integer_complement_complex) 11456 << resultType << Input.get()->getSourceRange(); 11457 else if (resultType->hasIntegerRepresentation()) 11458 break; 11459 else if (resultType->isExtVectorType()) { 11460 if (Context.getLangOpts().OpenCL) { 11461 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11462 // on vector float types. 11463 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11464 if (!T->isIntegerType()) 11465 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11466 << resultType << Input.get()->getSourceRange()); 11467 } 11468 break; 11469 } else { 11470 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11471 << resultType << Input.get()->getSourceRange()); 11472 } 11473 break; 11474 11475 case UO_LNot: // logical negation 11476 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11477 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11478 if (Input.isInvalid()) return ExprError(); 11479 resultType = Input.get()->getType(); 11480 11481 // Though we still have to promote half FP to float... 11482 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11483 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11484 resultType = Context.FloatTy; 11485 } 11486 11487 if (resultType->isDependentType()) 11488 break; 11489 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11490 // C99 6.5.3.3p1: ok, fallthrough; 11491 if (Context.getLangOpts().CPlusPlus) { 11492 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11493 // operand contextually converted to bool. 11494 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11495 ScalarTypeToBooleanCastKind(resultType)); 11496 } else if (Context.getLangOpts().OpenCL && 11497 Context.getLangOpts().OpenCLVersion < 120) { 11498 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11499 // operate on scalar float types. 11500 if (!resultType->isIntegerType()) 11501 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11502 << resultType << Input.get()->getSourceRange()); 11503 } 11504 } else if (resultType->isExtVectorType()) { 11505 if (Context.getLangOpts().OpenCL && 11506 Context.getLangOpts().OpenCLVersion < 120) { 11507 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11508 // operate on vector float types. 11509 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11510 if (!T->isIntegerType()) 11511 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11512 << resultType << Input.get()->getSourceRange()); 11513 } 11514 // Vector logical not returns the signed variant of the operand type. 11515 resultType = GetSignedVectorType(resultType); 11516 break; 11517 } else { 11518 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11519 << resultType << Input.get()->getSourceRange()); 11520 } 11521 11522 // LNot always has type int. C99 6.5.3.3p5. 11523 // In C++, it's bool. C++ 5.3.1p8 11524 resultType = Context.getLogicalOperationType(); 11525 break; 11526 case UO_Real: 11527 case UO_Imag: 11528 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11529 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11530 // complex l-values to ordinary l-values and all other values to r-values. 11531 if (Input.isInvalid()) return ExprError(); 11532 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11533 if (Input.get()->getValueKind() != VK_RValue && 11534 Input.get()->getObjectKind() == OK_Ordinary) 11535 VK = Input.get()->getValueKind(); 11536 } else if (!getLangOpts().CPlusPlus) { 11537 // In C, a volatile scalar is read by __imag. In C++, it is not. 11538 Input = DefaultLvalueConversion(Input.get()); 11539 } 11540 break; 11541 case UO_Extension: 11542 case UO_Coawait: 11543 resultType = Input.get()->getType(); 11544 VK = Input.get()->getValueKind(); 11545 OK = Input.get()->getObjectKind(); 11546 break; 11547 } 11548 if (resultType.isNull() || Input.isInvalid()) 11549 return ExprError(); 11550 11551 // Check for array bounds violations in the operand of the UnaryOperator, 11552 // except for the '*' and '&' operators that have to be handled specially 11553 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11554 // that are explicitly defined as valid by the standard). 11555 if (Opc != UO_AddrOf && Opc != UO_Deref) 11556 CheckArrayAccess(Input.get()); 11557 11558 return new (Context) 11559 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11560 } 11561 11562 /// \brief Determine whether the given expression is a qualified member 11563 /// access expression, of a form that could be turned into a pointer to member 11564 /// with the address-of operator. 11565 static bool isQualifiedMemberAccess(Expr *E) { 11566 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11567 if (!DRE->getQualifier()) 11568 return false; 11569 11570 ValueDecl *VD = DRE->getDecl(); 11571 if (!VD->isCXXClassMember()) 11572 return false; 11573 11574 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11575 return true; 11576 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11577 return Method->isInstance(); 11578 11579 return false; 11580 } 11581 11582 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11583 if (!ULE->getQualifier()) 11584 return false; 11585 11586 for (NamedDecl *D : ULE->decls()) { 11587 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11588 if (Method->isInstance()) 11589 return true; 11590 } else { 11591 // Overload set does not contain methods. 11592 break; 11593 } 11594 } 11595 11596 return false; 11597 } 11598 11599 return false; 11600 } 11601 11602 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11603 UnaryOperatorKind Opc, Expr *Input) { 11604 // First things first: handle placeholders so that the 11605 // overloaded-operator check considers the right type. 11606 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11607 // Increment and decrement of pseudo-object references. 11608 if (pty->getKind() == BuiltinType::PseudoObject && 11609 UnaryOperator::isIncrementDecrementOp(Opc)) 11610 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11611 11612 // extension is always a builtin operator. 11613 if (Opc == UO_Extension) 11614 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11615 11616 // & gets special logic for several kinds of placeholder. 11617 // The builtin code knows what to do. 11618 if (Opc == UO_AddrOf && 11619 (pty->getKind() == BuiltinType::Overload || 11620 pty->getKind() == BuiltinType::UnknownAny || 11621 pty->getKind() == BuiltinType::BoundMember)) 11622 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11623 11624 // Anything else needs to be handled now. 11625 ExprResult Result = CheckPlaceholderExpr(Input); 11626 if (Result.isInvalid()) return ExprError(); 11627 Input = Result.get(); 11628 } 11629 11630 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11631 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11632 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11633 // Find all of the overloaded operators visible from this 11634 // point. We perform both an operator-name lookup from the local 11635 // scope and an argument-dependent lookup based on the types of 11636 // the arguments. 11637 UnresolvedSet<16> Functions; 11638 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11639 if (S && OverOp != OO_None) 11640 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11641 Functions); 11642 11643 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11644 } 11645 11646 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11647 } 11648 11649 // Unary Operators. 'Tok' is the token for the operator. 11650 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11651 tok::TokenKind Op, Expr *Input) { 11652 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11653 } 11654 11655 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11656 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11657 LabelDecl *TheDecl) { 11658 TheDecl->markUsed(Context); 11659 // Create the AST node. The address of a label always has type 'void*'. 11660 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11661 Context.getPointerType(Context.VoidTy)); 11662 } 11663 11664 /// Given the last statement in a statement-expression, check whether 11665 /// the result is a producing expression (like a call to an 11666 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11667 /// release out of the full-expression. Otherwise, return null. 11668 /// Cannot fail. 11669 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11670 // Should always be wrapped with one of these. 11671 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11672 if (!cleanups) return nullptr; 11673 11674 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11675 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11676 return nullptr; 11677 11678 // Splice out the cast. This shouldn't modify any interesting 11679 // features of the statement. 11680 Expr *producer = cast->getSubExpr(); 11681 assert(producer->getType() == cast->getType()); 11682 assert(producer->getValueKind() == cast->getValueKind()); 11683 cleanups->setSubExpr(producer); 11684 return cleanups; 11685 } 11686 11687 void Sema::ActOnStartStmtExpr() { 11688 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11689 } 11690 11691 void Sema::ActOnStmtExprError() { 11692 // Note that function is also called by TreeTransform when leaving a 11693 // StmtExpr scope without rebuilding anything. 11694 11695 DiscardCleanupsInEvaluationContext(); 11696 PopExpressionEvaluationContext(); 11697 } 11698 11699 ExprResult 11700 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11701 SourceLocation RPLoc) { // "({..})" 11702 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11703 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11704 11705 if (hasAnyUnrecoverableErrorsInThisFunction()) 11706 DiscardCleanupsInEvaluationContext(); 11707 assert(!Cleanup.exprNeedsCleanups() && 11708 "cleanups within StmtExpr not correctly bound!"); 11709 PopExpressionEvaluationContext(); 11710 11711 // FIXME: there are a variety of strange constraints to enforce here, for 11712 // example, it is not possible to goto into a stmt expression apparently. 11713 // More semantic analysis is needed. 11714 11715 // If there are sub-stmts in the compound stmt, take the type of the last one 11716 // as the type of the stmtexpr. 11717 QualType Ty = Context.VoidTy; 11718 bool StmtExprMayBindToTemp = false; 11719 if (!Compound->body_empty()) { 11720 Stmt *LastStmt = Compound->body_back(); 11721 LabelStmt *LastLabelStmt = nullptr; 11722 // If LastStmt is a label, skip down through into the body. 11723 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11724 LastLabelStmt = Label; 11725 LastStmt = Label->getSubStmt(); 11726 } 11727 11728 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11729 // Do function/array conversion on the last expression, but not 11730 // lvalue-to-rvalue. However, initialize an unqualified type. 11731 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11732 if (LastExpr.isInvalid()) 11733 return ExprError(); 11734 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11735 11736 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11737 // In ARC, if the final expression ends in a consume, splice 11738 // the consume out and bind it later. In the alternate case 11739 // (when dealing with a retainable type), the result 11740 // initialization will create a produce. In both cases the 11741 // result will be +1, and we'll need to balance that out with 11742 // a bind. 11743 if (Expr *rebuiltLastStmt 11744 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11745 LastExpr = rebuiltLastStmt; 11746 } else { 11747 LastExpr = PerformCopyInitialization( 11748 InitializedEntity::InitializeResult(LPLoc, 11749 Ty, 11750 false), 11751 SourceLocation(), 11752 LastExpr); 11753 } 11754 11755 if (LastExpr.isInvalid()) 11756 return ExprError(); 11757 if (LastExpr.get() != nullptr) { 11758 if (!LastLabelStmt) 11759 Compound->setLastStmt(LastExpr.get()); 11760 else 11761 LastLabelStmt->setSubStmt(LastExpr.get()); 11762 StmtExprMayBindToTemp = true; 11763 } 11764 } 11765 } 11766 } 11767 11768 // FIXME: Check that expression type is complete/non-abstract; statement 11769 // expressions are not lvalues. 11770 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11771 if (StmtExprMayBindToTemp) 11772 return MaybeBindToTemporary(ResStmtExpr); 11773 return ResStmtExpr; 11774 } 11775 11776 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11777 TypeSourceInfo *TInfo, 11778 ArrayRef<OffsetOfComponent> Components, 11779 SourceLocation RParenLoc) { 11780 QualType ArgTy = TInfo->getType(); 11781 bool Dependent = ArgTy->isDependentType(); 11782 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11783 11784 // We must have at least one component that refers to the type, and the first 11785 // one is known to be a field designator. Verify that the ArgTy represents 11786 // a struct/union/class. 11787 if (!Dependent && !ArgTy->isRecordType()) 11788 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11789 << ArgTy << TypeRange); 11790 11791 // Type must be complete per C99 7.17p3 because a declaring a variable 11792 // with an incomplete type would be ill-formed. 11793 if (!Dependent 11794 && RequireCompleteType(BuiltinLoc, ArgTy, 11795 diag::err_offsetof_incomplete_type, TypeRange)) 11796 return ExprError(); 11797 11798 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11799 // GCC extension, diagnose them. 11800 // FIXME: This diagnostic isn't actually visible because the location is in 11801 // a system header! 11802 if (Components.size() != 1) 11803 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11804 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11805 11806 bool DidWarnAboutNonPOD = false; 11807 QualType CurrentType = ArgTy; 11808 SmallVector<OffsetOfNode, 4> Comps; 11809 SmallVector<Expr*, 4> Exprs; 11810 for (const OffsetOfComponent &OC : Components) { 11811 if (OC.isBrackets) { 11812 // Offset of an array sub-field. TODO: Should we allow vector elements? 11813 if (!CurrentType->isDependentType()) { 11814 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11815 if(!AT) 11816 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11817 << CurrentType); 11818 CurrentType = AT->getElementType(); 11819 } else 11820 CurrentType = Context.DependentTy; 11821 11822 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11823 if (IdxRval.isInvalid()) 11824 return ExprError(); 11825 Expr *Idx = IdxRval.get(); 11826 11827 // The expression must be an integral expression. 11828 // FIXME: An integral constant expression? 11829 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11830 !Idx->getType()->isIntegerType()) 11831 return ExprError(Diag(Idx->getLocStart(), 11832 diag::err_typecheck_subscript_not_integer) 11833 << Idx->getSourceRange()); 11834 11835 // Record this array index. 11836 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11837 Exprs.push_back(Idx); 11838 continue; 11839 } 11840 11841 // Offset of a field. 11842 if (CurrentType->isDependentType()) { 11843 // We have the offset of a field, but we can't look into the dependent 11844 // type. Just record the identifier of the field. 11845 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11846 CurrentType = Context.DependentTy; 11847 continue; 11848 } 11849 11850 // We need to have a complete type to look into. 11851 if (RequireCompleteType(OC.LocStart, CurrentType, 11852 diag::err_offsetof_incomplete_type)) 11853 return ExprError(); 11854 11855 // Look for the designated field. 11856 const RecordType *RC = CurrentType->getAs<RecordType>(); 11857 if (!RC) 11858 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11859 << CurrentType); 11860 RecordDecl *RD = RC->getDecl(); 11861 11862 // C++ [lib.support.types]p5: 11863 // The macro offsetof accepts a restricted set of type arguments in this 11864 // International Standard. type shall be a POD structure or a POD union 11865 // (clause 9). 11866 // C++11 [support.types]p4: 11867 // If type is not a standard-layout class (Clause 9), the results are 11868 // undefined. 11869 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11870 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11871 unsigned DiagID = 11872 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11873 : diag::ext_offsetof_non_pod_type; 11874 11875 if (!IsSafe && !DidWarnAboutNonPOD && 11876 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11877 PDiag(DiagID) 11878 << SourceRange(Components[0].LocStart, OC.LocEnd) 11879 << CurrentType)) 11880 DidWarnAboutNonPOD = true; 11881 } 11882 11883 // Look for the field. 11884 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11885 LookupQualifiedName(R, RD); 11886 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11887 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11888 if (!MemberDecl) { 11889 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11890 MemberDecl = IndirectMemberDecl->getAnonField(); 11891 } 11892 11893 if (!MemberDecl) 11894 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11895 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11896 OC.LocEnd)); 11897 11898 // C99 7.17p3: 11899 // (If the specified member is a bit-field, the behavior is undefined.) 11900 // 11901 // We diagnose this as an error. 11902 if (MemberDecl->isBitField()) { 11903 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11904 << MemberDecl->getDeclName() 11905 << SourceRange(BuiltinLoc, RParenLoc); 11906 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11907 return ExprError(); 11908 } 11909 11910 RecordDecl *Parent = MemberDecl->getParent(); 11911 if (IndirectMemberDecl) 11912 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11913 11914 // If the member was found in a base class, introduce OffsetOfNodes for 11915 // the base class indirections. 11916 CXXBasePaths Paths; 11917 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11918 Paths)) { 11919 if (Paths.getDetectedVirtual()) { 11920 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11921 << MemberDecl->getDeclName() 11922 << SourceRange(BuiltinLoc, RParenLoc); 11923 return ExprError(); 11924 } 11925 11926 CXXBasePath &Path = Paths.front(); 11927 for (const CXXBasePathElement &B : Path) 11928 Comps.push_back(OffsetOfNode(B.Base)); 11929 } 11930 11931 if (IndirectMemberDecl) { 11932 for (auto *FI : IndirectMemberDecl->chain()) { 11933 assert(isa<FieldDecl>(FI)); 11934 Comps.push_back(OffsetOfNode(OC.LocStart, 11935 cast<FieldDecl>(FI), OC.LocEnd)); 11936 } 11937 } else 11938 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11939 11940 CurrentType = MemberDecl->getType().getNonReferenceType(); 11941 } 11942 11943 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11944 Comps, Exprs, RParenLoc); 11945 } 11946 11947 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11948 SourceLocation BuiltinLoc, 11949 SourceLocation TypeLoc, 11950 ParsedType ParsedArgTy, 11951 ArrayRef<OffsetOfComponent> Components, 11952 SourceLocation RParenLoc) { 11953 11954 TypeSourceInfo *ArgTInfo; 11955 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11956 if (ArgTy.isNull()) 11957 return ExprError(); 11958 11959 if (!ArgTInfo) 11960 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11961 11962 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11963 } 11964 11965 11966 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11967 Expr *CondExpr, 11968 Expr *LHSExpr, Expr *RHSExpr, 11969 SourceLocation RPLoc) { 11970 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11971 11972 ExprValueKind VK = VK_RValue; 11973 ExprObjectKind OK = OK_Ordinary; 11974 QualType resType; 11975 bool ValueDependent = false; 11976 bool CondIsTrue = false; 11977 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11978 resType = Context.DependentTy; 11979 ValueDependent = true; 11980 } else { 11981 // The conditional expression is required to be a constant expression. 11982 llvm::APSInt condEval(32); 11983 ExprResult CondICE 11984 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11985 diag::err_typecheck_choose_expr_requires_constant, false); 11986 if (CondICE.isInvalid()) 11987 return ExprError(); 11988 CondExpr = CondICE.get(); 11989 CondIsTrue = condEval.getZExtValue(); 11990 11991 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11992 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11993 11994 resType = ActiveExpr->getType(); 11995 ValueDependent = ActiveExpr->isValueDependent(); 11996 VK = ActiveExpr->getValueKind(); 11997 OK = ActiveExpr->getObjectKind(); 11998 } 11999 12000 return new (Context) 12001 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12002 CondIsTrue, resType->isDependentType(), ValueDependent); 12003 } 12004 12005 //===----------------------------------------------------------------------===// 12006 // Clang Extensions. 12007 //===----------------------------------------------------------------------===// 12008 12009 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12010 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12011 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12012 12013 if (LangOpts.CPlusPlus) { 12014 Decl *ManglingContextDecl; 12015 if (MangleNumberingContext *MCtx = 12016 getCurrentMangleNumberContext(Block->getDeclContext(), 12017 ManglingContextDecl)) { 12018 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12019 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12020 } 12021 } 12022 12023 PushBlockScope(CurScope, Block); 12024 CurContext->addDecl(Block); 12025 if (CurScope) 12026 PushDeclContext(CurScope, Block); 12027 else 12028 CurContext = Block; 12029 12030 getCurBlock()->HasImplicitReturnType = true; 12031 12032 // Enter a new evaluation context to insulate the block from any 12033 // cleanups from the enclosing full-expression. 12034 PushExpressionEvaluationContext(PotentiallyEvaluated); 12035 } 12036 12037 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12038 Scope *CurScope) { 12039 assert(ParamInfo.getIdentifier() == nullptr && 12040 "block-id should have no identifier!"); 12041 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12042 BlockScopeInfo *CurBlock = getCurBlock(); 12043 12044 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12045 QualType T = Sig->getType(); 12046 12047 // FIXME: We should allow unexpanded parameter packs here, but that would, 12048 // in turn, make the block expression contain unexpanded parameter packs. 12049 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12050 // Drop the parameters. 12051 FunctionProtoType::ExtProtoInfo EPI; 12052 EPI.HasTrailingReturn = false; 12053 EPI.TypeQuals |= DeclSpec::TQ_const; 12054 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12055 Sig = Context.getTrivialTypeSourceInfo(T); 12056 } 12057 12058 // GetTypeForDeclarator always produces a function type for a block 12059 // literal signature. Furthermore, it is always a FunctionProtoType 12060 // unless the function was written with a typedef. 12061 assert(T->isFunctionType() && 12062 "GetTypeForDeclarator made a non-function block signature"); 12063 12064 // Look for an explicit signature in that function type. 12065 FunctionProtoTypeLoc ExplicitSignature; 12066 12067 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12068 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12069 12070 // Check whether that explicit signature was synthesized by 12071 // GetTypeForDeclarator. If so, don't save that as part of the 12072 // written signature. 12073 if (ExplicitSignature.getLocalRangeBegin() == 12074 ExplicitSignature.getLocalRangeEnd()) { 12075 // This would be much cheaper if we stored TypeLocs instead of 12076 // TypeSourceInfos. 12077 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12078 unsigned Size = Result.getFullDataSize(); 12079 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12080 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12081 12082 ExplicitSignature = FunctionProtoTypeLoc(); 12083 } 12084 } 12085 12086 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12087 CurBlock->FunctionType = T; 12088 12089 const FunctionType *Fn = T->getAs<FunctionType>(); 12090 QualType RetTy = Fn->getReturnType(); 12091 bool isVariadic = 12092 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12093 12094 CurBlock->TheDecl->setIsVariadic(isVariadic); 12095 12096 // Context.DependentTy is used as a placeholder for a missing block 12097 // return type. TODO: what should we do with declarators like: 12098 // ^ * { ... } 12099 // If the answer is "apply template argument deduction".... 12100 if (RetTy != Context.DependentTy) { 12101 CurBlock->ReturnType = RetTy; 12102 CurBlock->TheDecl->setBlockMissingReturnType(false); 12103 CurBlock->HasImplicitReturnType = false; 12104 } 12105 12106 // Push block parameters from the declarator if we had them. 12107 SmallVector<ParmVarDecl*, 8> Params; 12108 if (ExplicitSignature) { 12109 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12110 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12111 if (Param->getIdentifier() == nullptr && 12112 !Param->isImplicit() && 12113 !Param->isInvalidDecl() && 12114 !getLangOpts().CPlusPlus) 12115 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12116 Params.push_back(Param); 12117 } 12118 12119 // Fake up parameter variables if we have a typedef, like 12120 // ^ fntype { ... } 12121 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12122 for (const auto &I : Fn->param_types()) { 12123 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12124 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12125 Params.push_back(Param); 12126 } 12127 } 12128 12129 // Set the parameters on the block decl. 12130 if (!Params.empty()) { 12131 CurBlock->TheDecl->setParams(Params); 12132 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12133 /*CheckParameterNames=*/false); 12134 } 12135 12136 // Finally we can process decl attributes. 12137 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12138 12139 // Put the parameter variables in scope. 12140 for (auto AI : CurBlock->TheDecl->parameters()) { 12141 AI->setOwningFunction(CurBlock->TheDecl); 12142 12143 // If this has an identifier, add it to the scope stack. 12144 if (AI->getIdentifier()) { 12145 CheckShadow(CurBlock->TheScope, AI); 12146 12147 PushOnScopeChains(AI, CurBlock->TheScope); 12148 } 12149 } 12150 } 12151 12152 /// ActOnBlockError - If there is an error parsing a block, this callback 12153 /// is invoked to pop the information about the block from the action impl. 12154 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12155 // Leave the expression-evaluation context. 12156 DiscardCleanupsInEvaluationContext(); 12157 PopExpressionEvaluationContext(); 12158 12159 // Pop off CurBlock, handle nested blocks. 12160 PopDeclContext(); 12161 PopFunctionScopeInfo(); 12162 } 12163 12164 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12165 /// literal was successfully completed. ^(int x){...} 12166 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12167 Stmt *Body, Scope *CurScope) { 12168 // If blocks are disabled, emit an error. 12169 if (!LangOpts.Blocks) 12170 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12171 12172 // Leave the expression-evaluation context. 12173 if (hasAnyUnrecoverableErrorsInThisFunction()) 12174 DiscardCleanupsInEvaluationContext(); 12175 assert(!Cleanup.exprNeedsCleanups() && 12176 "cleanups within block not correctly bound!"); 12177 PopExpressionEvaluationContext(); 12178 12179 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12180 12181 if (BSI->HasImplicitReturnType) 12182 deduceClosureReturnType(*BSI); 12183 12184 PopDeclContext(); 12185 12186 QualType RetTy = Context.VoidTy; 12187 if (!BSI->ReturnType.isNull()) 12188 RetTy = BSI->ReturnType; 12189 12190 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12191 QualType BlockTy; 12192 12193 // Set the captured variables on the block. 12194 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12195 SmallVector<BlockDecl::Capture, 4> Captures; 12196 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12197 if (Cap.isThisCapture()) 12198 continue; 12199 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12200 Cap.isNested(), Cap.getInitExpr()); 12201 Captures.push_back(NewCap); 12202 } 12203 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12204 12205 // If the user wrote a function type in some form, try to use that. 12206 if (!BSI->FunctionType.isNull()) { 12207 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12208 12209 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12210 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12211 12212 // Turn protoless block types into nullary block types. 12213 if (isa<FunctionNoProtoType>(FTy)) { 12214 FunctionProtoType::ExtProtoInfo EPI; 12215 EPI.ExtInfo = Ext; 12216 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12217 12218 // Otherwise, if we don't need to change anything about the function type, 12219 // preserve its sugar structure. 12220 } else if (FTy->getReturnType() == RetTy && 12221 (!NoReturn || FTy->getNoReturnAttr())) { 12222 BlockTy = BSI->FunctionType; 12223 12224 // Otherwise, make the minimal modifications to the function type. 12225 } else { 12226 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12227 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12228 EPI.TypeQuals = 0; // FIXME: silently? 12229 EPI.ExtInfo = Ext; 12230 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12231 } 12232 12233 // If we don't have a function type, just build one from nothing. 12234 } else { 12235 FunctionProtoType::ExtProtoInfo EPI; 12236 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12237 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12238 } 12239 12240 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12241 BlockTy = Context.getBlockPointerType(BlockTy); 12242 12243 // If needed, diagnose invalid gotos and switches in the block. 12244 if (getCurFunction()->NeedsScopeChecking() && 12245 !PP.isCodeCompletionEnabled()) 12246 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12247 12248 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12249 12250 // Try to apply the named return value optimization. We have to check again 12251 // if we can do this, though, because blocks keep return statements around 12252 // to deduce an implicit return type. 12253 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12254 !BSI->TheDecl->isDependentContext()) 12255 computeNRVO(Body, BSI); 12256 12257 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12258 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12259 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12260 12261 // If the block isn't obviously global, i.e. it captures anything at 12262 // all, then we need to do a few things in the surrounding context: 12263 if (Result->getBlockDecl()->hasCaptures()) { 12264 // First, this expression has a new cleanup object. 12265 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12266 Cleanup.setExprNeedsCleanups(true); 12267 12268 // It also gets a branch-protected scope if any of the captured 12269 // variables needs destruction. 12270 for (const auto &CI : Result->getBlockDecl()->captures()) { 12271 const VarDecl *var = CI.getVariable(); 12272 if (var->getType().isDestructedType() != QualType::DK_none) { 12273 getCurFunction()->setHasBranchProtectedScope(); 12274 break; 12275 } 12276 } 12277 } 12278 12279 return Result; 12280 } 12281 12282 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12283 SourceLocation RPLoc) { 12284 TypeSourceInfo *TInfo; 12285 GetTypeFromParser(Ty, &TInfo); 12286 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12287 } 12288 12289 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12290 Expr *E, TypeSourceInfo *TInfo, 12291 SourceLocation RPLoc) { 12292 Expr *OrigExpr = E; 12293 bool IsMS = false; 12294 12295 // CUDA device code does not support varargs. 12296 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12297 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12298 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12299 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12300 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12301 } 12302 } 12303 12304 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12305 // as Microsoft ABI on an actual Microsoft platform, where 12306 // __builtin_ms_va_list and __builtin_va_list are the same.) 12307 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12308 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12309 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12310 if (Context.hasSameType(MSVaListType, E->getType())) { 12311 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12312 return ExprError(); 12313 IsMS = true; 12314 } 12315 } 12316 12317 // Get the va_list type 12318 QualType VaListType = Context.getBuiltinVaListType(); 12319 if (!IsMS) { 12320 if (VaListType->isArrayType()) { 12321 // Deal with implicit array decay; for example, on x86-64, 12322 // va_list is an array, but it's supposed to decay to 12323 // a pointer for va_arg. 12324 VaListType = Context.getArrayDecayedType(VaListType); 12325 // Make sure the input expression also decays appropriately. 12326 ExprResult Result = UsualUnaryConversions(E); 12327 if (Result.isInvalid()) 12328 return ExprError(); 12329 E = Result.get(); 12330 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12331 // If va_list is a record type and we are compiling in C++ mode, 12332 // check the argument using reference binding. 12333 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12334 Context, Context.getLValueReferenceType(VaListType), false); 12335 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12336 if (Init.isInvalid()) 12337 return ExprError(); 12338 E = Init.getAs<Expr>(); 12339 } else { 12340 // Otherwise, the va_list argument must be an l-value because 12341 // it is modified by va_arg. 12342 if (!E->isTypeDependent() && 12343 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12344 return ExprError(); 12345 } 12346 } 12347 12348 if (!IsMS && !E->isTypeDependent() && 12349 !Context.hasSameType(VaListType, E->getType())) 12350 return ExprError(Diag(E->getLocStart(), 12351 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12352 << OrigExpr->getType() << E->getSourceRange()); 12353 12354 if (!TInfo->getType()->isDependentType()) { 12355 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12356 diag::err_second_parameter_to_va_arg_incomplete, 12357 TInfo->getTypeLoc())) 12358 return ExprError(); 12359 12360 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12361 TInfo->getType(), 12362 diag::err_second_parameter_to_va_arg_abstract, 12363 TInfo->getTypeLoc())) 12364 return ExprError(); 12365 12366 if (!TInfo->getType().isPODType(Context)) { 12367 Diag(TInfo->getTypeLoc().getBeginLoc(), 12368 TInfo->getType()->isObjCLifetimeType() 12369 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12370 : diag::warn_second_parameter_to_va_arg_not_pod) 12371 << TInfo->getType() 12372 << TInfo->getTypeLoc().getSourceRange(); 12373 } 12374 12375 // Check for va_arg where arguments of the given type will be promoted 12376 // (i.e. this va_arg is guaranteed to have undefined behavior). 12377 QualType PromoteType; 12378 if (TInfo->getType()->isPromotableIntegerType()) { 12379 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12380 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12381 PromoteType = QualType(); 12382 } 12383 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12384 PromoteType = Context.DoubleTy; 12385 if (!PromoteType.isNull()) 12386 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12387 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12388 << TInfo->getType() 12389 << PromoteType 12390 << TInfo->getTypeLoc().getSourceRange()); 12391 } 12392 12393 QualType T = TInfo->getType().getNonLValueExprType(Context); 12394 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12395 } 12396 12397 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12398 // The type of __null will be int or long, depending on the size of 12399 // pointers on the target. 12400 QualType Ty; 12401 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12402 if (pw == Context.getTargetInfo().getIntWidth()) 12403 Ty = Context.IntTy; 12404 else if (pw == Context.getTargetInfo().getLongWidth()) 12405 Ty = Context.LongTy; 12406 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12407 Ty = Context.LongLongTy; 12408 else { 12409 llvm_unreachable("I don't know size of pointer!"); 12410 } 12411 12412 return new (Context) GNUNullExpr(Ty, TokenLoc); 12413 } 12414 12415 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12416 bool Diagnose) { 12417 if (!getLangOpts().ObjC1) 12418 return false; 12419 12420 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12421 if (!PT) 12422 return false; 12423 12424 if (!PT->isObjCIdType()) { 12425 // Check if the destination is the 'NSString' interface. 12426 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12427 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12428 return false; 12429 } 12430 12431 // Ignore any parens, implicit casts (should only be 12432 // array-to-pointer decays), and not-so-opaque values. The last is 12433 // important for making this trigger for property assignments. 12434 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12435 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12436 if (OV->getSourceExpr()) 12437 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12438 12439 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12440 if (!SL || !SL->isAscii()) 12441 return false; 12442 if (Diagnose) { 12443 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12444 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12445 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12446 } 12447 return true; 12448 } 12449 12450 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12451 const Expr *SrcExpr) { 12452 if (!DstType->isFunctionPointerType() || 12453 !SrcExpr->getType()->isFunctionType()) 12454 return false; 12455 12456 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12457 if (!DRE) 12458 return false; 12459 12460 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12461 if (!FD) 12462 return false; 12463 12464 return !S.checkAddressOfFunctionIsAvailable(FD, 12465 /*Complain=*/true, 12466 SrcExpr->getLocStart()); 12467 } 12468 12469 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12470 SourceLocation Loc, 12471 QualType DstType, QualType SrcType, 12472 Expr *SrcExpr, AssignmentAction Action, 12473 bool *Complained) { 12474 if (Complained) 12475 *Complained = false; 12476 12477 // Decode the result (notice that AST's are still created for extensions). 12478 bool CheckInferredResultType = false; 12479 bool isInvalid = false; 12480 unsigned DiagKind = 0; 12481 FixItHint Hint; 12482 ConversionFixItGenerator ConvHints; 12483 bool MayHaveConvFixit = false; 12484 bool MayHaveFunctionDiff = false; 12485 const ObjCInterfaceDecl *IFace = nullptr; 12486 const ObjCProtocolDecl *PDecl = nullptr; 12487 12488 switch (ConvTy) { 12489 case Compatible: 12490 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12491 return false; 12492 12493 case PointerToInt: 12494 DiagKind = diag::ext_typecheck_convert_pointer_int; 12495 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12496 MayHaveConvFixit = true; 12497 break; 12498 case IntToPointer: 12499 DiagKind = diag::ext_typecheck_convert_int_pointer; 12500 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12501 MayHaveConvFixit = true; 12502 break; 12503 case IncompatiblePointer: 12504 if (Action == AA_Passing_CFAudited) 12505 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12506 else if (SrcType->isFunctionPointerType() && 12507 DstType->isFunctionPointerType()) 12508 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12509 else 12510 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12511 12512 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12513 SrcType->isObjCObjectPointerType(); 12514 if (Hint.isNull() && !CheckInferredResultType) { 12515 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12516 } 12517 else if (CheckInferredResultType) { 12518 SrcType = SrcType.getUnqualifiedType(); 12519 DstType = DstType.getUnqualifiedType(); 12520 } 12521 MayHaveConvFixit = true; 12522 break; 12523 case IncompatiblePointerSign: 12524 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12525 break; 12526 case FunctionVoidPointer: 12527 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12528 break; 12529 case IncompatiblePointerDiscardsQualifiers: { 12530 // Perform array-to-pointer decay if necessary. 12531 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12532 12533 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12534 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12535 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12536 DiagKind = diag::err_typecheck_incompatible_address_space; 12537 break; 12538 12539 12540 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12541 DiagKind = diag::err_typecheck_incompatible_ownership; 12542 break; 12543 } 12544 12545 llvm_unreachable("unknown error case for discarding qualifiers!"); 12546 // fallthrough 12547 } 12548 case CompatiblePointerDiscardsQualifiers: 12549 // If the qualifiers lost were because we were applying the 12550 // (deprecated) C++ conversion from a string literal to a char* 12551 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12552 // Ideally, this check would be performed in 12553 // checkPointerTypesForAssignment. However, that would require a 12554 // bit of refactoring (so that the second argument is an 12555 // expression, rather than a type), which should be done as part 12556 // of a larger effort to fix checkPointerTypesForAssignment for 12557 // C++ semantics. 12558 if (getLangOpts().CPlusPlus && 12559 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12560 return false; 12561 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12562 break; 12563 case IncompatibleNestedPointerQualifiers: 12564 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12565 break; 12566 case IntToBlockPointer: 12567 DiagKind = diag::err_int_to_block_pointer; 12568 break; 12569 case IncompatibleBlockPointer: 12570 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12571 break; 12572 case IncompatibleObjCQualifiedId: { 12573 if (SrcType->isObjCQualifiedIdType()) { 12574 const ObjCObjectPointerType *srcOPT = 12575 SrcType->getAs<ObjCObjectPointerType>(); 12576 for (auto *srcProto : srcOPT->quals()) { 12577 PDecl = srcProto; 12578 break; 12579 } 12580 if (const ObjCInterfaceType *IFaceT = 12581 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12582 IFace = IFaceT->getDecl(); 12583 } 12584 else if (DstType->isObjCQualifiedIdType()) { 12585 const ObjCObjectPointerType *dstOPT = 12586 DstType->getAs<ObjCObjectPointerType>(); 12587 for (auto *dstProto : dstOPT->quals()) { 12588 PDecl = dstProto; 12589 break; 12590 } 12591 if (const ObjCInterfaceType *IFaceT = 12592 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12593 IFace = IFaceT->getDecl(); 12594 } 12595 DiagKind = diag::warn_incompatible_qualified_id; 12596 break; 12597 } 12598 case IncompatibleVectors: 12599 DiagKind = diag::warn_incompatible_vectors; 12600 break; 12601 case IncompatibleObjCWeakRef: 12602 DiagKind = diag::err_arc_weak_unavailable_assign; 12603 break; 12604 case Incompatible: 12605 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12606 if (Complained) 12607 *Complained = true; 12608 return true; 12609 } 12610 12611 DiagKind = diag::err_typecheck_convert_incompatible; 12612 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12613 MayHaveConvFixit = true; 12614 isInvalid = true; 12615 MayHaveFunctionDiff = true; 12616 break; 12617 } 12618 12619 QualType FirstType, SecondType; 12620 switch (Action) { 12621 case AA_Assigning: 12622 case AA_Initializing: 12623 // The destination type comes first. 12624 FirstType = DstType; 12625 SecondType = SrcType; 12626 break; 12627 12628 case AA_Returning: 12629 case AA_Passing: 12630 case AA_Passing_CFAudited: 12631 case AA_Converting: 12632 case AA_Sending: 12633 case AA_Casting: 12634 // The source type comes first. 12635 FirstType = SrcType; 12636 SecondType = DstType; 12637 break; 12638 } 12639 12640 PartialDiagnostic FDiag = PDiag(DiagKind); 12641 if (Action == AA_Passing_CFAudited) 12642 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12643 else 12644 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12645 12646 // If we can fix the conversion, suggest the FixIts. 12647 assert(ConvHints.isNull() || Hint.isNull()); 12648 if (!ConvHints.isNull()) { 12649 for (FixItHint &H : ConvHints.Hints) 12650 FDiag << H; 12651 } else { 12652 FDiag << Hint; 12653 } 12654 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12655 12656 if (MayHaveFunctionDiff) 12657 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12658 12659 Diag(Loc, FDiag); 12660 if (DiagKind == diag::warn_incompatible_qualified_id && 12661 PDecl && IFace && !IFace->hasDefinition()) 12662 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12663 << IFace->getName() << PDecl->getName(); 12664 12665 if (SecondType == Context.OverloadTy) 12666 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12667 FirstType, /*TakingAddress=*/true); 12668 12669 if (CheckInferredResultType) 12670 EmitRelatedResultTypeNote(SrcExpr); 12671 12672 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12673 EmitRelatedResultTypeNoteForReturn(DstType); 12674 12675 if (Complained) 12676 *Complained = true; 12677 return isInvalid; 12678 } 12679 12680 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12681 llvm::APSInt *Result) { 12682 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12683 public: 12684 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12685 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12686 } 12687 } Diagnoser; 12688 12689 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12690 } 12691 12692 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12693 llvm::APSInt *Result, 12694 unsigned DiagID, 12695 bool AllowFold) { 12696 class IDDiagnoser : public VerifyICEDiagnoser { 12697 unsigned DiagID; 12698 12699 public: 12700 IDDiagnoser(unsigned DiagID) 12701 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12702 12703 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12704 S.Diag(Loc, DiagID) << SR; 12705 } 12706 } Diagnoser(DiagID); 12707 12708 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12709 } 12710 12711 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12712 SourceRange SR) { 12713 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12714 } 12715 12716 ExprResult 12717 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12718 VerifyICEDiagnoser &Diagnoser, 12719 bool AllowFold) { 12720 SourceLocation DiagLoc = E->getLocStart(); 12721 12722 if (getLangOpts().CPlusPlus11) { 12723 // C++11 [expr.const]p5: 12724 // If an expression of literal class type is used in a context where an 12725 // integral constant expression is required, then that class type shall 12726 // have a single non-explicit conversion function to an integral or 12727 // unscoped enumeration type 12728 ExprResult Converted; 12729 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12730 public: 12731 CXX11ConvertDiagnoser(bool Silent) 12732 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12733 Silent, true) {} 12734 12735 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12736 QualType T) override { 12737 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12738 } 12739 12740 SemaDiagnosticBuilder diagnoseIncomplete( 12741 Sema &S, SourceLocation Loc, QualType T) override { 12742 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12743 } 12744 12745 SemaDiagnosticBuilder diagnoseExplicitConv( 12746 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12747 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12748 } 12749 12750 SemaDiagnosticBuilder noteExplicitConv( 12751 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12752 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12753 << ConvTy->isEnumeralType() << ConvTy; 12754 } 12755 12756 SemaDiagnosticBuilder diagnoseAmbiguous( 12757 Sema &S, SourceLocation Loc, QualType T) override { 12758 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12759 } 12760 12761 SemaDiagnosticBuilder noteAmbiguous( 12762 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12763 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12764 << ConvTy->isEnumeralType() << ConvTy; 12765 } 12766 12767 SemaDiagnosticBuilder diagnoseConversion( 12768 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12769 llvm_unreachable("conversion functions are permitted"); 12770 } 12771 } ConvertDiagnoser(Diagnoser.Suppress); 12772 12773 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12774 ConvertDiagnoser); 12775 if (Converted.isInvalid()) 12776 return Converted; 12777 E = Converted.get(); 12778 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12779 return ExprError(); 12780 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12781 // An ICE must be of integral or unscoped enumeration type. 12782 if (!Diagnoser.Suppress) 12783 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12784 return ExprError(); 12785 } 12786 12787 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12788 // in the non-ICE case. 12789 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12790 if (Result) 12791 *Result = E->EvaluateKnownConstInt(Context); 12792 return E; 12793 } 12794 12795 Expr::EvalResult EvalResult; 12796 SmallVector<PartialDiagnosticAt, 8> Notes; 12797 EvalResult.Diag = &Notes; 12798 12799 // Try to evaluate the expression, and produce diagnostics explaining why it's 12800 // not a constant expression as a side-effect. 12801 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12802 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12803 12804 // In C++11, we can rely on diagnostics being produced for any expression 12805 // which is not a constant expression. If no diagnostics were produced, then 12806 // this is a constant expression. 12807 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12808 if (Result) 12809 *Result = EvalResult.Val.getInt(); 12810 return E; 12811 } 12812 12813 // If our only note is the usual "invalid subexpression" note, just point 12814 // the caret at its location rather than producing an essentially 12815 // redundant note. 12816 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12817 diag::note_invalid_subexpr_in_const_expr) { 12818 DiagLoc = Notes[0].first; 12819 Notes.clear(); 12820 } 12821 12822 if (!Folded || !AllowFold) { 12823 if (!Diagnoser.Suppress) { 12824 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12825 for (const PartialDiagnosticAt &Note : Notes) 12826 Diag(Note.first, Note.second); 12827 } 12828 12829 return ExprError(); 12830 } 12831 12832 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12833 for (const PartialDiagnosticAt &Note : Notes) 12834 Diag(Note.first, Note.second); 12835 12836 if (Result) 12837 *Result = EvalResult.Val.getInt(); 12838 return E; 12839 } 12840 12841 namespace { 12842 // Handle the case where we conclude a expression which we speculatively 12843 // considered to be unevaluated is actually evaluated. 12844 class TransformToPE : public TreeTransform<TransformToPE> { 12845 typedef TreeTransform<TransformToPE> BaseTransform; 12846 12847 public: 12848 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12849 12850 // Make sure we redo semantic analysis 12851 bool AlwaysRebuild() { return true; } 12852 12853 // Make sure we handle LabelStmts correctly. 12854 // FIXME: This does the right thing, but maybe we need a more general 12855 // fix to TreeTransform? 12856 StmtResult TransformLabelStmt(LabelStmt *S) { 12857 S->getDecl()->setStmt(nullptr); 12858 return BaseTransform::TransformLabelStmt(S); 12859 } 12860 12861 // We need to special-case DeclRefExprs referring to FieldDecls which 12862 // are not part of a member pointer formation; normal TreeTransforming 12863 // doesn't catch this case because of the way we represent them in the AST. 12864 // FIXME: This is a bit ugly; is it really the best way to handle this 12865 // case? 12866 // 12867 // Error on DeclRefExprs referring to FieldDecls. 12868 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12869 if (isa<FieldDecl>(E->getDecl()) && 12870 !SemaRef.isUnevaluatedContext()) 12871 return SemaRef.Diag(E->getLocation(), 12872 diag::err_invalid_non_static_member_use) 12873 << E->getDecl() << E->getSourceRange(); 12874 12875 return BaseTransform::TransformDeclRefExpr(E); 12876 } 12877 12878 // Exception: filter out member pointer formation 12879 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12880 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12881 return E; 12882 12883 return BaseTransform::TransformUnaryOperator(E); 12884 } 12885 12886 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12887 // Lambdas never need to be transformed. 12888 return E; 12889 } 12890 }; 12891 } 12892 12893 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12894 assert(isUnevaluatedContext() && 12895 "Should only transform unevaluated expressions"); 12896 ExprEvalContexts.back().Context = 12897 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12898 if (isUnevaluatedContext()) 12899 return E; 12900 return TransformToPE(*this).TransformExpr(E); 12901 } 12902 12903 void 12904 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12905 Decl *LambdaContextDecl, 12906 bool IsDecltype) { 12907 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12908 LambdaContextDecl, IsDecltype); 12909 Cleanup.reset(); 12910 if (!MaybeODRUseExprs.empty()) 12911 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12912 } 12913 12914 void 12915 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12916 ReuseLambdaContextDecl_t, 12917 bool IsDecltype) { 12918 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12919 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12920 } 12921 12922 void Sema::PopExpressionEvaluationContext() { 12923 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12924 unsigned NumTypos = Rec.NumTypos; 12925 12926 if (!Rec.Lambdas.empty()) { 12927 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12928 unsigned D; 12929 if (Rec.isUnevaluated()) { 12930 // C++11 [expr.prim.lambda]p2: 12931 // A lambda-expression shall not appear in an unevaluated operand 12932 // (Clause 5). 12933 D = diag::err_lambda_unevaluated_operand; 12934 } else { 12935 // C++1y [expr.const]p2: 12936 // A conditional-expression e is a core constant expression unless the 12937 // evaluation of e, following the rules of the abstract machine, would 12938 // evaluate [...] a lambda-expression. 12939 D = diag::err_lambda_in_constant_expression; 12940 } 12941 for (const auto *L : Rec.Lambdas) 12942 Diag(L->getLocStart(), D); 12943 } else { 12944 // Mark the capture expressions odr-used. This was deferred 12945 // during lambda expression creation. 12946 for (auto *Lambda : Rec.Lambdas) { 12947 for (auto *C : Lambda->capture_inits()) 12948 MarkDeclarationsReferencedInExpr(C); 12949 } 12950 } 12951 } 12952 12953 // When are coming out of an unevaluated context, clear out any 12954 // temporaries that we may have created as part of the evaluation of 12955 // the expression in that context: they aren't relevant because they 12956 // will never be constructed. 12957 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12958 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12959 ExprCleanupObjects.end()); 12960 Cleanup = Rec.ParentCleanup; 12961 CleanupVarDeclMarking(); 12962 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12963 // Otherwise, merge the contexts together. 12964 } else { 12965 Cleanup.mergeFrom(Rec.ParentCleanup); 12966 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12967 Rec.SavedMaybeODRUseExprs.end()); 12968 } 12969 12970 // Pop the current expression evaluation context off the stack. 12971 ExprEvalContexts.pop_back(); 12972 12973 if (!ExprEvalContexts.empty()) 12974 ExprEvalContexts.back().NumTypos += NumTypos; 12975 else 12976 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12977 "last ExpressionEvaluationContextRecord"); 12978 } 12979 12980 void Sema::DiscardCleanupsInEvaluationContext() { 12981 ExprCleanupObjects.erase( 12982 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12983 ExprCleanupObjects.end()); 12984 Cleanup.reset(); 12985 MaybeODRUseExprs.clear(); 12986 } 12987 12988 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12989 if (!E->getType()->isVariablyModifiedType()) 12990 return E; 12991 return TransformToPotentiallyEvaluated(E); 12992 } 12993 12994 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12995 // Do not mark anything as "used" within a dependent context; wait for 12996 // an instantiation. 12997 if (SemaRef.CurContext->isDependentContext()) 12998 return false; 12999 13000 switch (SemaRef.ExprEvalContexts.back().Context) { 13001 case Sema::Unevaluated: 13002 case Sema::UnevaluatedAbstract: 13003 // We are in an expression that is not potentially evaluated; do nothing. 13004 // (Depending on how you read the standard, we actually do need to do 13005 // something here for null pointer constants, but the standard's 13006 // definition of a null pointer constant is completely crazy.) 13007 return false; 13008 13009 case Sema::DiscardedStatement: 13010 // These are technically a potentially evaluated but they have the effect 13011 // of suppressing use marking. 13012 return false; 13013 13014 case Sema::ConstantEvaluated: 13015 case Sema::PotentiallyEvaluated: 13016 // We are in a potentially evaluated expression (or a constant-expression 13017 // in C++03); we need to do implicit template instantiation, implicitly 13018 // define class members, and mark most declarations as used. 13019 return true; 13020 13021 case Sema::PotentiallyEvaluatedIfUsed: 13022 // Referenced declarations will only be used if the construct in the 13023 // containing expression is used. 13024 return false; 13025 } 13026 llvm_unreachable("Invalid context"); 13027 } 13028 13029 /// \brief Mark a function referenced, and check whether it is odr-used 13030 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13031 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13032 bool MightBeOdrUse) { 13033 assert(Func && "No function?"); 13034 13035 Func->setReferenced(); 13036 13037 // C++11 [basic.def.odr]p3: 13038 // A function whose name appears as a potentially-evaluated expression is 13039 // odr-used if it is the unique lookup result or the selected member of a 13040 // set of overloaded functions [...]. 13041 // 13042 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13043 // can just check that here. 13044 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13045 13046 // Determine whether we require a function definition to exist, per 13047 // C++11 [temp.inst]p3: 13048 // Unless a function template specialization has been explicitly 13049 // instantiated or explicitly specialized, the function template 13050 // specialization is implicitly instantiated when the specialization is 13051 // referenced in a context that requires a function definition to exist. 13052 // 13053 // We consider constexpr function templates to be referenced in a context 13054 // that requires a definition to exist whenever they are referenced. 13055 // 13056 // FIXME: This instantiates constexpr functions too frequently. If this is 13057 // really an unevaluated context (and we're not just in the definition of a 13058 // function template or overload resolution or other cases which we 13059 // incorrectly consider to be unevaluated contexts), and we're not in a 13060 // subexpression which we actually need to evaluate (for instance, a 13061 // template argument, array bound or an expression in a braced-init-list), 13062 // we are not permitted to instantiate this constexpr function definition. 13063 // 13064 // FIXME: This also implicitly defines special members too frequently. They 13065 // are only supposed to be implicitly defined if they are odr-used, but they 13066 // are not odr-used from constant expressions in unevaluated contexts. 13067 // However, they cannot be referenced if they are deleted, and they are 13068 // deleted whenever the implicit definition of the special member would 13069 // fail (with very few exceptions). 13070 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13071 bool NeedDefinition = 13072 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13073 (MD && !MD->isUserProvided()))); 13074 13075 // C++14 [temp.expl.spec]p6: 13076 // If a template [...] is explicitly specialized then that specialization 13077 // shall be declared before the first use of that specialization that would 13078 // cause an implicit instantiation to take place, in every translation unit 13079 // in which such a use occurs 13080 if (NeedDefinition && 13081 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13082 Func->getMemberSpecializationInfo())) 13083 checkSpecializationVisibility(Loc, Func); 13084 13085 // If we don't need to mark the function as used, and we don't need to 13086 // try to provide a definition, there's nothing more to do. 13087 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13088 (!NeedDefinition || Func->getBody())) 13089 return; 13090 13091 // Note that this declaration has been used. 13092 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13093 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13094 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13095 if (Constructor->isDefaultConstructor()) { 13096 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13097 return; 13098 DefineImplicitDefaultConstructor(Loc, Constructor); 13099 } else if (Constructor->isCopyConstructor()) { 13100 DefineImplicitCopyConstructor(Loc, Constructor); 13101 } else if (Constructor->isMoveConstructor()) { 13102 DefineImplicitMoveConstructor(Loc, Constructor); 13103 } 13104 } else if (Constructor->getInheritedConstructor()) { 13105 DefineInheritingConstructor(Loc, Constructor); 13106 } 13107 } else if (CXXDestructorDecl *Destructor = 13108 dyn_cast<CXXDestructorDecl>(Func)) { 13109 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13110 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13111 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13112 return; 13113 DefineImplicitDestructor(Loc, Destructor); 13114 } 13115 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13116 MarkVTableUsed(Loc, Destructor->getParent()); 13117 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13118 if (MethodDecl->isOverloadedOperator() && 13119 MethodDecl->getOverloadedOperator() == OO_Equal) { 13120 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13121 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13122 if (MethodDecl->isCopyAssignmentOperator()) 13123 DefineImplicitCopyAssignment(Loc, MethodDecl); 13124 else if (MethodDecl->isMoveAssignmentOperator()) 13125 DefineImplicitMoveAssignment(Loc, MethodDecl); 13126 } 13127 } else if (isa<CXXConversionDecl>(MethodDecl) && 13128 MethodDecl->getParent()->isLambda()) { 13129 CXXConversionDecl *Conversion = 13130 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13131 if (Conversion->isLambdaToBlockPointerConversion()) 13132 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13133 else 13134 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13135 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13136 MarkVTableUsed(Loc, MethodDecl->getParent()); 13137 } 13138 13139 // Recursive functions should be marked when used from another function. 13140 // FIXME: Is this really right? 13141 if (CurContext == Func) return; 13142 13143 // Resolve the exception specification for any function which is 13144 // used: CodeGen will need it. 13145 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13146 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13147 ResolveExceptionSpec(Loc, FPT); 13148 13149 // Implicit instantiation of function templates and member functions of 13150 // class templates. 13151 if (Func->isImplicitlyInstantiable()) { 13152 bool AlreadyInstantiated = false; 13153 SourceLocation PointOfInstantiation = Loc; 13154 if (FunctionTemplateSpecializationInfo *SpecInfo 13155 = Func->getTemplateSpecializationInfo()) { 13156 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13157 SpecInfo->setPointOfInstantiation(Loc); 13158 else if (SpecInfo->getTemplateSpecializationKind() 13159 == TSK_ImplicitInstantiation) { 13160 AlreadyInstantiated = true; 13161 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13162 } 13163 } else if (MemberSpecializationInfo *MSInfo 13164 = Func->getMemberSpecializationInfo()) { 13165 if (MSInfo->getPointOfInstantiation().isInvalid()) 13166 MSInfo->setPointOfInstantiation(Loc); 13167 else if (MSInfo->getTemplateSpecializationKind() 13168 == TSK_ImplicitInstantiation) { 13169 AlreadyInstantiated = true; 13170 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13171 } 13172 } 13173 13174 if (!AlreadyInstantiated || Func->isConstexpr()) { 13175 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13176 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13177 ActiveTemplateInstantiations.size()) 13178 PendingLocalImplicitInstantiations.push_back( 13179 std::make_pair(Func, PointOfInstantiation)); 13180 else if (Func->isConstexpr()) 13181 // Do not defer instantiations of constexpr functions, to avoid the 13182 // expression evaluator needing to call back into Sema if it sees a 13183 // call to such a function. 13184 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13185 else { 13186 PendingInstantiations.push_back(std::make_pair(Func, 13187 PointOfInstantiation)); 13188 // Notify the consumer that a function was implicitly instantiated. 13189 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13190 } 13191 } 13192 } else { 13193 // Walk redefinitions, as some of them may be instantiable. 13194 for (auto i : Func->redecls()) { 13195 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13196 MarkFunctionReferenced(Loc, i, OdrUse); 13197 } 13198 } 13199 13200 if (!OdrUse) return; 13201 13202 // Keep track of used but undefined functions. 13203 if (!Func->isDefined()) { 13204 if (mightHaveNonExternalLinkage(Func)) 13205 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13206 else if (Func->getMostRecentDecl()->isInlined() && 13207 !LangOpts.GNUInline && 13208 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13209 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13210 } 13211 13212 Func->markUsed(Context); 13213 } 13214 13215 static void 13216 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13217 VarDecl *var, DeclContext *DC) { 13218 DeclContext *VarDC = var->getDeclContext(); 13219 13220 // If the parameter still belongs to the translation unit, then 13221 // we're actually just using one parameter in the declaration of 13222 // the next. 13223 if (isa<ParmVarDecl>(var) && 13224 isa<TranslationUnitDecl>(VarDC)) 13225 return; 13226 13227 // For C code, don't diagnose about capture if we're not actually in code 13228 // right now; it's impossible to write a non-constant expression outside of 13229 // function context, so we'll get other (more useful) diagnostics later. 13230 // 13231 // For C++, things get a bit more nasty... it would be nice to suppress this 13232 // diagnostic for certain cases like using a local variable in an array bound 13233 // for a member of a local class, but the correct predicate is not obvious. 13234 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13235 return; 13236 13237 if (isa<CXXMethodDecl>(VarDC) && 13238 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13239 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 13240 << var->getIdentifier(); 13241 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 13242 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 13243 << var->getIdentifier() << fn->getDeclName(); 13244 } else if (isa<BlockDecl>(VarDC)) { 13245 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 13246 << var->getIdentifier(); 13247 } else { 13248 // FIXME: Is there any other context where a local variable can be 13249 // declared? 13250 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 13251 << var->getIdentifier(); 13252 } 13253 13254 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13255 << var->getIdentifier(); 13256 13257 // FIXME: Add additional diagnostic info about class etc. which prevents 13258 // capture. 13259 } 13260 13261 13262 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13263 bool &SubCapturesAreNested, 13264 QualType &CaptureType, 13265 QualType &DeclRefType) { 13266 // Check whether we've already captured it. 13267 if (CSI->CaptureMap.count(Var)) { 13268 // If we found a capture, any subcaptures are nested. 13269 SubCapturesAreNested = true; 13270 13271 // Retrieve the capture type for this variable. 13272 CaptureType = CSI->getCapture(Var).getCaptureType(); 13273 13274 // Compute the type of an expression that refers to this variable. 13275 DeclRefType = CaptureType.getNonReferenceType(); 13276 13277 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13278 // are mutable in the sense that user can change their value - they are 13279 // private instances of the captured declarations. 13280 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13281 if (Cap.isCopyCapture() && 13282 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13283 !(isa<CapturedRegionScopeInfo>(CSI) && 13284 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13285 DeclRefType.addConst(); 13286 return true; 13287 } 13288 return false; 13289 } 13290 13291 // Only block literals, captured statements, and lambda expressions can 13292 // capture; other scopes don't work. 13293 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13294 SourceLocation Loc, 13295 const bool Diagnose, Sema &S) { 13296 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13297 return getLambdaAwareParentOfDeclContext(DC); 13298 else if (Var->hasLocalStorage()) { 13299 if (Diagnose) 13300 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13301 } 13302 return nullptr; 13303 } 13304 13305 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13306 // certain types of variables (unnamed, variably modified types etc.) 13307 // so check for eligibility. 13308 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13309 SourceLocation Loc, 13310 const bool Diagnose, Sema &S) { 13311 13312 bool IsBlock = isa<BlockScopeInfo>(CSI); 13313 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13314 13315 // Lambdas are not allowed to capture unnamed variables 13316 // (e.g. anonymous unions). 13317 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13318 // assuming that's the intent. 13319 if (IsLambda && !Var->getDeclName()) { 13320 if (Diagnose) { 13321 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13322 S.Diag(Var->getLocation(), diag::note_declared_at); 13323 } 13324 return false; 13325 } 13326 13327 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13328 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13329 if (Diagnose) { 13330 S.Diag(Loc, diag::err_ref_vm_type); 13331 S.Diag(Var->getLocation(), diag::note_previous_decl) 13332 << Var->getDeclName(); 13333 } 13334 return false; 13335 } 13336 // Prohibit structs with flexible array members too. 13337 // We cannot capture what is in the tail end of the struct. 13338 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13339 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13340 if (Diagnose) { 13341 if (IsBlock) 13342 S.Diag(Loc, diag::err_ref_flexarray_type); 13343 else 13344 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13345 << Var->getDeclName(); 13346 S.Diag(Var->getLocation(), diag::note_previous_decl) 13347 << Var->getDeclName(); 13348 } 13349 return false; 13350 } 13351 } 13352 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13353 // Lambdas and captured statements are not allowed to capture __block 13354 // variables; they don't support the expected semantics. 13355 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13356 if (Diagnose) { 13357 S.Diag(Loc, diag::err_capture_block_variable) 13358 << Var->getDeclName() << !IsLambda; 13359 S.Diag(Var->getLocation(), diag::note_previous_decl) 13360 << Var->getDeclName(); 13361 } 13362 return false; 13363 } 13364 13365 return true; 13366 } 13367 13368 // Returns true if the capture by block was successful. 13369 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13370 SourceLocation Loc, 13371 const bool BuildAndDiagnose, 13372 QualType &CaptureType, 13373 QualType &DeclRefType, 13374 const bool Nested, 13375 Sema &S) { 13376 Expr *CopyExpr = nullptr; 13377 bool ByRef = false; 13378 13379 // Blocks are not allowed to capture arrays. 13380 if (CaptureType->isArrayType()) { 13381 if (BuildAndDiagnose) { 13382 S.Diag(Loc, diag::err_ref_array_type); 13383 S.Diag(Var->getLocation(), diag::note_previous_decl) 13384 << Var->getDeclName(); 13385 } 13386 return false; 13387 } 13388 13389 // Forbid the block-capture of autoreleasing variables. 13390 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13391 if (BuildAndDiagnose) { 13392 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13393 << /*block*/ 0; 13394 S.Diag(Var->getLocation(), diag::note_previous_decl) 13395 << Var->getDeclName(); 13396 } 13397 return false; 13398 } 13399 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13400 if (HasBlocksAttr || CaptureType->isReferenceType() || 13401 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13402 // Block capture by reference does not change the capture or 13403 // declaration reference types. 13404 ByRef = true; 13405 } else { 13406 // Block capture by copy introduces 'const'. 13407 CaptureType = CaptureType.getNonReferenceType().withConst(); 13408 DeclRefType = CaptureType; 13409 13410 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13411 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13412 // The capture logic needs the destructor, so make sure we mark it. 13413 // Usually this is unnecessary because most local variables have 13414 // their destructors marked at declaration time, but parameters are 13415 // an exception because it's technically only the call site that 13416 // actually requires the destructor. 13417 if (isa<ParmVarDecl>(Var)) 13418 S.FinalizeVarWithDestructor(Var, Record); 13419 13420 // Enter a new evaluation context to insulate the copy 13421 // full-expression. 13422 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13423 13424 // According to the blocks spec, the capture of a variable from 13425 // the stack requires a const copy constructor. This is not true 13426 // of the copy/move done to move a __block variable to the heap. 13427 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13428 DeclRefType.withConst(), 13429 VK_LValue, Loc); 13430 13431 ExprResult Result 13432 = S.PerformCopyInitialization( 13433 InitializedEntity::InitializeBlock(Var->getLocation(), 13434 CaptureType, false), 13435 Loc, DeclRef); 13436 13437 // Build a full-expression copy expression if initialization 13438 // succeeded and used a non-trivial constructor. Recover from 13439 // errors by pretending that the copy isn't necessary. 13440 if (!Result.isInvalid() && 13441 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13442 ->isTrivial()) { 13443 Result = S.MaybeCreateExprWithCleanups(Result); 13444 CopyExpr = Result.get(); 13445 } 13446 } 13447 } 13448 } 13449 13450 // Actually capture the variable. 13451 if (BuildAndDiagnose) 13452 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13453 SourceLocation(), CaptureType, CopyExpr); 13454 13455 return true; 13456 13457 } 13458 13459 13460 /// \brief Capture the given variable in the captured region. 13461 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13462 VarDecl *Var, 13463 SourceLocation Loc, 13464 const bool BuildAndDiagnose, 13465 QualType &CaptureType, 13466 QualType &DeclRefType, 13467 const bool RefersToCapturedVariable, 13468 Sema &S) { 13469 // By default, capture variables by reference. 13470 bool ByRef = true; 13471 // Using an LValue reference type is consistent with Lambdas (see below). 13472 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13473 if (S.IsOpenMPCapturedDecl(Var)) 13474 DeclRefType = DeclRefType.getUnqualifiedType(); 13475 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13476 } 13477 13478 if (ByRef) 13479 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13480 else 13481 CaptureType = DeclRefType; 13482 13483 Expr *CopyExpr = nullptr; 13484 if (BuildAndDiagnose) { 13485 // The current implementation assumes that all variables are captured 13486 // by references. Since there is no capture by copy, no expression 13487 // evaluation will be needed. 13488 RecordDecl *RD = RSI->TheRecordDecl; 13489 13490 FieldDecl *Field 13491 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13492 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13493 nullptr, false, ICIS_NoInit); 13494 Field->setImplicit(true); 13495 Field->setAccess(AS_private); 13496 RD->addDecl(Field); 13497 13498 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13499 DeclRefType, VK_LValue, Loc); 13500 Var->setReferenced(true); 13501 Var->markUsed(S.Context); 13502 } 13503 13504 // Actually capture the variable. 13505 if (BuildAndDiagnose) 13506 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13507 SourceLocation(), CaptureType, CopyExpr); 13508 13509 13510 return true; 13511 } 13512 13513 /// \brief Create a field within the lambda class for the variable 13514 /// being captured. 13515 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13516 QualType FieldType, QualType DeclRefType, 13517 SourceLocation Loc, 13518 bool RefersToCapturedVariable) { 13519 CXXRecordDecl *Lambda = LSI->Lambda; 13520 13521 // Build the non-static data member. 13522 FieldDecl *Field 13523 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13524 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13525 nullptr, false, ICIS_NoInit); 13526 Field->setImplicit(true); 13527 Field->setAccess(AS_private); 13528 Lambda->addDecl(Field); 13529 } 13530 13531 /// \brief Capture the given variable in the lambda. 13532 static bool captureInLambda(LambdaScopeInfo *LSI, 13533 VarDecl *Var, 13534 SourceLocation Loc, 13535 const bool BuildAndDiagnose, 13536 QualType &CaptureType, 13537 QualType &DeclRefType, 13538 const bool RefersToCapturedVariable, 13539 const Sema::TryCaptureKind Kind, 13540 SourceLocation EllipsisLoc, 13541 const bool IsTopScope, 13542 Sema &S) { 13543 13544 // Determine whether we are capturing by reference or by value. 13545 bool ByRef = false; 13546 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13547 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13548 } else { 13549 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13550 } 13551 13552 // Compute the type of the field that will capture this variable. 13553 if (ByRef) { 13554 // C++11 [expr.prim.lambda]p15: 13555 // An entity is captured by reference if it is implicitly or 13556 // explicitly captured but not captured by copy. It is 13557 // unspecified whether additional unnamed non-static data 13558 // members are declared in the closure type for entities 13559 // captured by reference. 13560 // 13561 // FIXME: It is not clear whether we want to build an lvalue reference 13562 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13563 // to do the former, while EDG does the latter. Core issue 1249 will 13564 // clarify, but for now we follow GCC because it's a more permissive and 13565 // easily defensible position. 13566 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13567 } else { 13568 // C++11 [expr.prim.lambda]p14: 13569 // For each entity captured by copy, an unnamed non-static 13570 // data member is declared in the closure type. The 13571 // declaration order of these members is unspecified. The type 13572 // of such a data member is the type of the corresponding 13573 // captured entity if the entity is not a reference to an 13574 // object, or the referenced type otherwise. [Note: If the 13575 // captured entity is a reference to a function, the 13576 // corresponding data member is also a reference to a 13577 // function. - end note ] 13578 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13579 if (!RefType->getPointeeType()->isFunctionType()) 13580 CaptureType = RefType->getPointeeType(); 13581 } 13582 13583 // Forbid the lambda copy-capture of autoreleasing variables. 13584 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13585 if (BuildAndDiagnose) { 13586 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13587 S.Diag(Var->getLocation(), diag::note_previous_decl) 13588 << Var->getDeclName(); 13589 } 13590 return false; 13591 } 13592 13593 // Make sure that by-copy captures are of a complete and non-abstract type. 13594 if (BuildAndDiagnose) { 13595 if (!CaptureType->isDependentType() && 13596 S.RequireCompleteType(Loc, CaptureType, 13597 diag::err_capture_of_incomplete_type, 13598 Var->getDeclName())) 13599 return false; 13600 13601 if (S.RequireNonAbstractType(Loc, CaptureType, 13602 diag::err_capture_of_abstract_type)) 13603 return false; 13604 } 13605 } 13606 13607 // Capture this variable in the lambda. 13608 if (BuildAndDiagnose) 13609 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13610 RefersToCapturedVariable); 13611 13612 // Compute the type of a reference to this captured variable. 13613 if (ByRef) 13614 DeclRefType = CaptureType.getNonReferenceType(); 13615 else { 13616 // C++ [expr.prim.lambda]p5: 13617 // The closure type for a lambda-expression has a public inline 13618 // function call operator [...]. This function call operator is 13619 // declared const (9.3.1) if and only if the lambda-expression’s 13620 // parameter-declaration-clause is not followed by mutable. 13621 DeclRefType = CaptureType.getNonReferenceType(); 13622 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13623 DeclRefType.addConst(); 13624 } 13625 13626 // Add the capture. 13627 if (BuildAndDiagnose) 13628 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13629 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13630 13631 return true; 13632 } 13633 13634 bool Sema::tryCaptureVariable( 13635 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13636 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13637 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13638 // An init-capture is notionally from the context surrounding its 13639 // declaration, but its parent DC is the lambda class. 13640 DeclContext *VarDC = Var->getDeclContext(); 13641 if (Var->isInitCapture()) 13642 VarDC = VarDC->getParent(); 13643 13644 DeclContext *DC = CurContext; 13645 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13646 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13647 // We need to sync up the Declaration Context with the 13648 // FunctionScopeIndexToStopAt 13649 if (FunctionScopeIndexToStopAt) { 13650 unsigned FSIndex = FunctionScopes.size() - 1; 13651 while (FSIndex != MaxFunctionScopesIndex) { 13652 DC = getLambdaAwareParentOfDeclContext(DC); 13653 --FSIndex; 13654 } 13655 } 13656 13657 13658 // If the variable is declared in the current context, there is no need to 13659 // capture it. 13660 if (VarDC == DC) return true; 13661 13662 // Capture global variables if it is required to use private copy of this 13663 // variable. 13664 bool IsGlobal = !Var->hasLocalStorage(); 13665 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13666 return true; 13667 13668 // Walk up the stack to determine whether we can capture the variable, 13669 // performing the "simple" checks that don't depend on type. We stop when 13670 // we've either hit the declared scope of the variable or find an existing 13671 // capture of that variable. We start from the innermost capturing-entity 13672 // (the DC) and ensure that all intervening capturing-entities 13673 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13674 // declcontext can either capture the variable or have already captured 13675 // the variable. 13676 CaptureType = Var->getType(); 13677 DeclRefType = CaptureType.getNonReferenceType(); 13678 bool Nested = false; 13679 bool Explicit = (Kind != TryCapture_Implicit); 13680 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13681 do { 13682 // Only block literals, captured statements, and lambda expressions can 13683 // capture; other scopes don't work. 13684 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13685 ExprLoc, 13686 BuildAndDiagnose, 13687 *this); 13688 // We need to check for the parent *first* because, if we *have* 13689 // private-captured a global variable, we need to recursively capture it in 13690 // intermediate blocks, lambdas, etc. 13691 if (!ParentDC) { 13692 if (IsGlobal) { 13693 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13694 break; 13695 } 13696 return true; 13697 } 13698 13699 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13700 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13701 13702 13703 // Check whether we've already captured it. 13704 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13705 DeclRefType)) 13706 break; 13707 // If we are instantiating a generic lambda call operator body, 13708 // we do not want to capture new variables. What was captured 13709 // during either a lambdas transformation or initial parsing 13710 // should be used. 13711 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13712 if (BuildAndDiagnose) { 13713 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13714 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13715 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13716 Diag(Var->getLocation(), diag::note_previous_decl) 13717 << Var->getDeclName(); 13718 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13719 } else 13720 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13721 } 13722 return true; 13723 } 13724 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13725 // certain types of variables (unnamed, variably modified types etc.) 13726 // so check for eligibility. 13727 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13728 return true; 13729 13730 // Try to capture variable-length arrays types. 13731 if (Var->getType()->isVariablyModifiedType()) { 13732 // We're going to walk down into the type and look for VLA 13733 // expressions. 13734 QualType QTy = Var->getType(); 13735 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13736 QTy = PVD->getOriginalType(); 13737 captureVariablyModifiedType(Context, QTy, CSI); 13738 } 13739 13740 if (getLangOpts().OpenMP) { 13741 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13742 // OpenMP private variables should not be captured in outer scope, so 13743 // just break here. Similarly, global variables that are captured in a 13744 // target region should not be captured outside the scope of the region. 13745 if (RSI->CapRegionKind == CR_OpenMP) { 13746 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13747 // When we detect target captures we are looking from inside the 13748 // target region, therefore we need to propagate the capture from the 13749 // enclosing region. Therefore, the capture is not initially nested. 13750 if (IsTargetCap) 13751 FunctionScopesIndex--; 13752 13753 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13754 Nested = !IsTargetCap; 13755 DeclRefType = DeclRefType.getUnqualifiedType(); 13756 CaptureType = Context.getLValueReferenceType(DeclRefType); 13757 break; 13758 } 13759 } 13760 } 13761 } 13762 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13763 // No capture-default, and this is not an explicit capture 13764 // so cannot capture this variable. 13765 if (BuildAndDiagnose) { 13766 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13767 Diag(Var->getLocation(), diag::note_previous_decl) 13768 << Var->getDeclName(); 13769 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13770 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13771 diag::note_lambda_decl); 13772 // FIXME: If we error out because an outer lambda can not implicitly 13773 // capture a variable that an inner lambda explicitly captures, we 13774 // should have the inner lambda do the explicit capture - because 13775 // it makes for cleaner diagnostics later. This would purely be done 13776 // so that the diagnostic does not misleadingly claim that a variable 13777 // can not be captured by a lambda implicitly even though it is captured 13778 // explicitly. Suggestion: 13779 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13780 // at the function head 13781 // - cache the StartingDeclContext - this must be a lambda 13782 // - captureInLambda in the innermost lambda the variable. 13783 } 13784 return true; 13785 } 13786 13787 FunctionScopesIndex--; 13788 DC = ParentDC; 13789 Explicit = false; 13790 } while (!VarDC->Equals(DC)); 13791 13792 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13793 // computing the type of the capture at each step, checking type-specific 13794 // requirements, and adding captures if requested. 13795 // If the variable had already been captured previously, we start capturing 13796 // at the lambda nested within that one. 13797 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13798 ++I) { 13799 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13800 13801 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13802 if (!captureInBlock(BSI, Var, ExprLoc, 13803 BuildAndDiagnose, CaptureType, 13804 DeclRefType, Nested, *this)) 13805 return true; 13806 Nested = true; 13807 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13808 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13809 BuildAndDiagnose, CaptureType, 13810 DeclRefType, Nested, *this)) 13811 return true; 13812 Nested = true; 13813 } else { 13814 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13815 if (!captureInLambda(LSI, Var, ExprLoc, 13816 BuildAndDiagnose, CaptureType, 13817 DeclRefType, Nested, Kind, EllipsisLoc, 13818 /*IsTopScope*/I == N - 1, *this)) 13819 return true; 13820 Nested = true; 13821 } 13822 } 13823 return false; 13824 } 13825 13826 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13827 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13828 QualType CaptureType; 13829 QualType DeclRefType; 13830 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13831 /*BuildAndDiagnose=*/true, CaptureType, 13832 DeclRefType, nullptr); 13833 } 13834 13835 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13836 QualType CaptureType; 13837 QualType DeclRefType; 13838 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13839 /*BuildAndDiagnose=*/false, CaptureType, 13840 DeclRefType, nullptr); 13841 } 13842 13843 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13844 QualType CaptureType; 13845 QualType DeclRefType; 13846 13847 // Determine whether we can capture this variable. 13848 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13849 /*BuildAndDiagnose=*/false, CaptureType, 13850 DeclRefType, nullptr)) 13851 return QualType(); 13852 13853 return DeclRefType; 13854 } 13855 13856 13857 13858 // If either the type of the variable or the initializer is dependent, 13859 // return false. Otherwise, determine whether the variable is a constant 13860 // expression. Use this if you need to know if a variable that might or 13861 // might not be dependent is truly a constant expression. 13862 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13863 ASTContext &Context) { 13864 13865 if (Var->getType()->isDependentType()) 13866 return false; 13867 const VarDecl *DefVD = nullptr; 13868 Var->getAnyInitializer(DefVD); 13869 if (!DefVD) 13870 return false; 13871 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13872 Expr *Init = cast<Expr>(Eval->Value); 13873 if (Init->isValueDependent()) 13874 return false; 13875 return IsVariableAConstantExpression(Var, Context); 13876 } 13877 13878 13879 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13880 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13881 // an object that satisfies the requirements for appearing in a 13882 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13883 // is immediately applied." This function handles the lvalue-to-rvalue 13884 // conversion part. 13885 MaybeODRUseExprs.erase(E->IgnoreParens()); 13886 13887 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13888 // to a variable that is a constant expression, and if so, identify it as 13889 // a reference to a variable that does not involve an odr-use of that 13890 // variable. 13891 if (LambdaScopeInfo *LSI = getCurLambda()) { 13892 Expr *SansParensExpr = E->IgnoreParens(); 13893 VarDecl *Var = nullptr; 13894 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13895 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13896 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13897 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13898 13899 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13900 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13901 } 13902 } 13903 13904 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13905 Res = CorrectDelayedTyposInExpr(Res); 13906 13907 if (!Res.isUsable()) 13908 return Res; 13909 13910 // If a constant-expression is a reference to a variable where we delay 13911 // deciding whether it is an odr-use, just assume we will apply the 13912 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13913 // (a non-type template argument), we have special handling anyway. 13914 UpdateMarkingForLValueToRValue(Res.get()); 13915 return Res; 13916 } 13917 13918 void Sema::CleanupVarDeclMarking() { 13919 for (Expr *E : MaybeODRUseExprs) { 13920 VarDecl *Var; 13921 SourceLocation Loc; 13922 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13923 Var = cast<VarDecl>(DRE->getDecl()); 13924 Loc = DRE->getLocation(); 13925 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13926 Var = cast<VarDecl>(ME->getMemberDecl()); 13927 Loc = ME->getMemberLoc(); 13928 } else { 13929 llvm_unreachable("Unexpected expression"); 13930 } 13931 13932 MarkVarDeclODRUsed(Var, Loc, *this, 13933 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13934 } 13935 13936 MaybeODRUseExprs.clear(); 13937 } 13938 13939 13940 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13941 VarDecl *Var, Expr *E) { 13942 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13943 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13944 Var->setReferenced(); 13945 13946 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13947 bool MarkODRUsed = true; 13948 13949 // If the context is not potentially evaluated, this is not an odr-use and 13950 // does not trigger instantiation. 13951 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13952 if (SemaRef.isUnevaluatedContext()) 13953 return; 13954 13955 // If we don't yet know whether this context is going to end up being an 13956 // evaluated context, and we're referencing a variable from an enclosing 13957 // scope, add a potential capture. 13958 // 13959 // FIXME: Is this necessary? These contexts are only used for default 13960 // arguments, where local variables can't be used. 13961 const bool RefersToEnclosingScope = 13962 (SemaRef.CurContext != Var->getDeclContext() && 13963 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13964 if (RefersToEnclosingScope) { 13965 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13966 // If a variable could potentially be odr-used, defer marking it so 13967 // until we finish analyzing the full expression for any 13968 // lvalue-to-rvalue 13969 // or discarded value conversions that would obviate odr-use. 13970 // Add it to the list of potential captures that will be analyzed 13971 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13972 // unless the variable is a reference that was initialized by a constant 13973 // expression (this will never need to be captured or odr-used). 13974 assert(E && "Capture variable should be used in an expression."); 13975 if (!Var->getType()->isReferenceType() || 13976 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13977 LSI->addPotentialCapture(E->IgnoreParens()); 13978 } 13979 } 13980 13981 if (!isTemplateInstantiation(TSK)) 13982 return; 13983 13984 // Instantiate, but do not mark as odr-used, variable templates. 13985 MarkODRUsed = false; 13986 } 13987 13988 VarTemplateSpecializationDecl *VarSpec = 13989 dyn_cast<VarTemplateSpecializationDecl>(Var); 13990 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13991 "Can't instantiate a partial template specialization."); 13992 13993 // If this might be a member specialization of a static data member, check 13994 // the specialization is visible. We already did the checks for variable 13995 // template specializations when we created them. 13996 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 13997 SemaRef.checkSpecializationVisibility(Loc, Var); 13998 13999 // Perform implicit instantiation of static data members, static data member 14000 // templates of class templates, and variable template specializations. Delay 14001 // instantiations of variable templates, except for those that could be used 14002 // in a constant expression. 14003 if (isTemplateInstantiation(TSK)) { 14004 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14005 14006 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14007 if (Var->getPointOfInstantiation().isInvalid()) { 14008 // This is a modification of an existing AST node. Notify listeners. 14009 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14010 L->StaticDataMemberInstantiated(Var); 14011 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14012 // Don't bother trying to instantiate it again, unless we might need 14013 // its initializer before we get to the end of the TU. 14014 TryInstantiating = false; 14015 } 14016 14017 if (Var->getPointOfInstantiation().isInvalid()) 14018 Var->setTemplateSpecializationKind(TSK, Loc); 14019 14020 if (TryInstantiating) { 14021 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14022 bool InstantiationDependent = false; 14023 bool IsNonDependent = 14024 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14025 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14026 : true; 14027 14028 // Do not instantiate specializations that are still type-dependent. 14029 if (IsNonDependent) { 14030 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14031 // Do not defer instantiations of variables which could be used in a 14032 // constant expression. 14033 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14034 } else { 14035 SemaRef.PendingInstantiations 14036 .push_back(std::make_pair(Var, PointOfInstantiation)); 14037 } 14038 } 14039 } 14040 } 14041 14042 if (!MarkODRUsed) 14043 return; 14044 14045 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14046 // the requirements for appearing in a constant expression (5.19) and, if 14047 // it is an object, the lvalue-to-rvalue conversion (4.1) 14048 // is immediately applied." We check the first part here, and 14049 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14050 // Note that we use the C++11 definition everywhere because nothing in 14051 // C++03 depends on whether we get the C++03 version correct. The second 14052 // part does not apply to references, since they are not objects. 14053 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14054 // A reference initialized by a constant expression can never be 14055 // odr-used, so simply ignore it. 14056 if (!Var->getType()->isReferenceType()) 14057 SemaRef.MaybeODRUseExprs.insert(E); 14058 } else 14059 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14060 /*MaxFunctionScopeIndex ptr*/ nullptr); 14061 } 14062 14063 /// \brief Mark a variable referenced, and check whether it is odr-used 14064 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14065 /// used directly for normal expressions referring to VarDecl. 14066 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14067 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14068 } 14069 14070 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14071 Decl *D, Expr *E, bool MightBeOdrUse) { 14072 if (SemaRef.isInOpenMPDeclareTargetContext()) 14073 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14074 14075 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14076 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14077 return; 14078 } 14079 14080 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14081 14082 // If this is a call to a method via a cast, also mark the method in the 14083 // derived class used in case codegen can devirtualize the call. 14084 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14085 if (!ME) 14086 return; 14087 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14088 if (!MD) 14089 return; 14090 // Only attempt to devirtualize if this is truly a virtual call. 14091 bool IsVirtualCall = MD->isVirtual() && 14092 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14093 if (!IsVirtualCall) 14094 return; 14095 const Expr *Base = ME->getBase(); 14096 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14097 if (!MostDerivedClassDecl) 14098 return; 14099 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14100 if (!DM || DM->isPure()) 14101 return; 14102 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14103 } 14104 14105 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14106 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14107 // TODO: update this with DR# once a defect report is filed. 14108 // C++11 defect. The address of a pure member should not be an ODR use, even 14109 // if it's a qualified reference. 14110 bool OdrUse = true; 14111 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14112 if (Method->isVirtual()) 14113 OdrUse = false; 14114 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14115 } 14116 14117 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14118 void Sema::MarkMemberReferenced(MemberExpr *E) { 14119 // C++11 [basic.def.odr]p2: 14120 // A non-overloaded function whose name appears as a potentially-evaluated 14121 // expression or a member of a set of candidate functions, if selected by 14122 // overload resolution when referred to from a potentially-evaluated 14123 // expression, is odr-used, unless it is a pure virtual function and its 14124 // name is not explicitly qualified. 14125 bool MightBeOdrUse = true; 14126 if (E->performsVirtualDispatch(getLangOpts())) { 14127 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14128 if (Method->isPure()) 14129 MightBeOdrUse = false; 14130 } 14131 SourceLocation Loc = E->getMemberLoc().isValid() ? 14132 E->getMemberLoc() : E->getLocStart(); 14133 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14134 } 14135 14136 /// \brief Perform marking for a reference to an arbitrary declaration. It 14137 /// marks the declaration referenced, and performs odr-use checking for 14138 /// functions and variables. This method should not be used when building a 14139 /// normal expression which refers to a variable. 14140 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14141 bool MightBeOdrUse) { 14142 if (MightBeOdrUse) { 14143 if (auto *VD = dyn_cast<VarDecl>(D)) { 14144 MarkVariableReferenced(Loc, VD); 14145 return; 14146 } 14147 } 14148 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14149 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14150 return; 14151 } 14152 D->setReferenced(); 14153 } 14154 14155 namespace { 14156 // Mark all of the declarations referenced 14157 // FIXME: Not fully implemented yet! We need to have a better understanding 14158 // of when we're entering 14159 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14160 Sema &S; 14161 SourceLocation Loc; 14162 14163 public: 14164 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14165 14166 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14167 14168 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14169 bool TraverseRecordType(RecordType *T); 14170 }; 14171 } 14172 14173 bool MarkReferencedDecls::TraverseTemplateArgument( 14174 const TemplateArgument &Arg) { 14175 if (Arg.getKind() == TemplateArgument::Declaration) { 14176 if (Decl *D = Arg.getAsDecl()) 14177 S.MarkAnyDeclReferenced(Loc, D, true); 14178 } 14179 14180 return Inherited::TraverseTemplateArgument(Arg); 14181 } 14182 14183 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14184 if (ClassTemplateSpecializationDecl *Spec 14185 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14186 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14187 return TraverseTemplateArguments(Args.data(), Args.size()); 14188 } 14189 14190 return true; 14191 } 14192 14193 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14194 MarkReferencedDecls Marker(*this, Loc); 14195 Marker.TraverseType(Context.getCanonicalType(T)); 14196 } 14197 14198 namespace { 14199 /// \brief Helper class that marks all of the declarations referenced by 14200 /// potentially-evaluated subexpressions as "referenced". 14201 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14202 Sema &S; 14203 bool SkipLocalVariables; 14204 14205 public: 14206 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14207 14208 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14209 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14210 14211 void VisitDeclRefExpr(DeclRefExpr *E) { 14212 // If we were asked not to visit local variables, don't. 14213 if (SkipLocalVariables) { 14214 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14215 if (VD->hasLocalStorage()) 14216 return; 14217 } 14218 14219 S.MarkDeclRefReferenced(E); 14220 } 14221 14222 void VisitMemberExpr(MemberExpr *E) { 14223 S.MarkMemberReferenced(E); 14224 Inherited::VisitMemberExpr(E); 14225 } 14226 14227 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14228 S.MarkFunctionReferenced(E->getLocStart(), 14229 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14230 Visit(E->getSubExpr()); 14231 } 14232 14233 void VisitCXXNewExpr(CXXNewExpr *E) { 14234 if (E->getOperatorNew()) 14235 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14236 if (E->getOperatorDelete()) 14237 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14238 Inherited::VisitCXXNewExpr(E); 14239 } 14240 14241 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14242 if (E->getOperatorDelete()) 14243 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14244 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14245 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14246 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14247 S.MarkFunctionReferenced(E->getLocStart(), 14248 S.LookupDestructor(Record)); 14249 } 14250 14251 Inherited::VisitCXXDeleteExpr(E); 14252 } 14253 14254 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14255 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14256 Inherited::VisitCXXConstructExpr(E); 14257 } 14258 14259 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14260 Visit(E->getExpr()); 14261 } 14262 14263 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14264 Inherited::VisitImplicitCastExpr(E); 14265 14266 if (E->getCastKind() == CK_LValueToRValue) 14267 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14268 } 14269 }; 14270 } 14271 14272 /// \brief Mark any declarations that appear within this expression or any 14273 /// potentially-evaluated subexpressions as "referenced". 14274 /// 14275 /// \param SkipLocalVariables If true, don't mark local variables as 14276 /// 'referenced'. 14277 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14278 bool SkipLocalVariables) { 14279 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14280 } 14281 14282 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14283 /// of the program being compiled. 14284 /// 14285 /// This routine emits the given diagnostic when the code currently being 14286 /// type-checked is "potentially evaluated", meaning that there is a 14287 /// possibility that the code will actually be executable. Code in sizeof() 14288 /// expressions, code used only during overload resolution, etc., are not 14289 /// potentially evaluated. This routine will suppress such diagnostics or, 14290 /// in the absolutely nutty case of potentially potentially evaluated 14291 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14292 /// later. 14293 /// 14294 /// This routine should be used for all diagnostics that describe the run-time 14295 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14296 /// Failure to do so will likely result in spurious diagnostics or failures 14297 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14298 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14299 const PartialDiagnostic &PD) { 14300 switch (ExprEvalContexts.back().Context) { 14301 case Unevaluated: 14302 case UnevaluatedAbstract: 14303 case DiscardedStatement: 14304 // The argument will never be evaluated, so don't complain. 14305 break; 14306 14307 case ConstantEvaluated: 14308 // Relevant diagnostics should be produced by constant evaluation. 14309 break; 14310 14311 case PotentiallyEvaluated: 14312 case PotentiallyEvaluatedIfUsed: 14313 if (Statement && getCurFunctionOrMethodDecl()) { 14314 FunctionScopes.back()->PossiblyUnreachableDiags. 14315 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14316 } 14317 else 14318 Diag(Loc, PD); 14319 14320 return true; 14321 } 14322 14323 return false; 14324 } 14325 14326 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14327 CallExpr *CE, FunctionDecl *FD) { 14328 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14329 return false; 14330 14331 // If we're inside a decltype's expression, don't check for a valid return 14332 // type or construct temporaries until we know whether this is the last call. 14333 if (ExprEvalContexts.back().IsDecltype) { 14334 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14335 return false; 14336 } 14337 14338 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14339 FunctionDecl *FD; 14340 CallExpr *CE; 14341 14342 public: 14343 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14344 : FD(FD), CE(CE) { } 14345 14346 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14347 if (!FD) { 14348 S.Diag(Loc, diag::err_call_incomplete_return) 14349 << T << CE->getSourceRange(); 14350 return; 14351 } 14352 14353 S.Diag(Loc, diag::err_call_function_incomplete_return) 14354 << CE->getSourceRange() << FD->getDeclName() << T; 14355 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14356 << FD->getDeclName(); 14357 } 14358 } Diagnoser(FD, CE); 14359 14360 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14361 return true; 14362 14363 return false; 14364 } 14365 14366 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14367 // will prevent this condition from triggering, which is what we want. 14368 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14369 SourceLocation Loc; 14370 14371 unsigned diagnostic = diag::warn_condition_is_assignment; 14372 bool IsOrAssign = false; 14373 14374 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14375 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14376 return; 14377 14378 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14379 14380 // Greylist some idioms by putting them into a warning subcategory. 14381 if (ObjCMessageExpr *ME 14382 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14383 Selector Sel = ME->getSelector(); 14384 14385 // self = [<foo> init...] 14386 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14387 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14388 14389 // <foo> = [<bar> nextObject] 14390 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14391 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14392 } 14393 14394 Loc = Op->getOperatorLoc(); 14395 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14396 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14397 return; 14398 14399 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14400 Loc = Op->getOperatorLoc(); 14401 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14402 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14403 else { 14404 // Not an assignment. 14405 return; 14406 } 14407 14408 Diag(Loc, diagnostic) << E->getSourceRange(); 14409 14410 SourceLocation Open = E->getLocStart(); 14411 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14412 Diag(Loc, diag::note_condition_assign_silence) 14413 << FixItHint::CreateInsertion(Open, "(") 14414 << FixItHint::CreateInsertion(Close, ")"); 14415 14416 if (IsOrAssign) 14417 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14418 << FixItHint::CreateReplacement(Loc, "!="); 14419 else 14420 Diag(Loc, diag::note_condition_assign_to_comparison) 14421 << FixItHint::CreateReplacement(Loc, "=="); 14422 } 14423 14424 /// \brief Redundant parentheses over an equality comparison can indicate 14425 /// that the user intended an assignment used as condition. 14426 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14427 // Don't warn if the parens came from a macro. 14428 SourceLocation parenLoc = ParenE->getLocStart(); 14429 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14430 return; 14431 // Don't warn for dependent expressions. 14432 if (ParenE->isTypeDependent()) 14433 return; 14434 14435 Expr *E = ParenE->IgnoreParens(); 14436 14437 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14438 if (opE->getOpcode() == BO_EQ && 14439 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14440 == Expr::MLV_Valid) { 14441 SourceLocation Loc = opE->getOperatorLoc(); 14442 14443 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14444 SourceRange ParenERange = ParenE->getSourceRange(); 14445 Diag(Loc, diag::note_equality_comparison_silence) 14446 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14447 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14448 Diag(Loc, diag::note_equality_comparison_to_assign) 14449 << FixItHint::CreateReplacement(Loc, "="); 14450 } 14451 } 14452 14453 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14454 bool IsConstexpr) { 14455 DiagnoseAssignmentAsCondition(E); 14456 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14457 DiagnoseEqualityWithExtraParens(parenE); 14458 14459 ExprResult result = CheckPlaceholderExpr(E); 14460 if (result.isInvalid()) return ExprError(); 14461 E = result.get(); 14462 14463 if (!E->isTypeDependent()) { 14464 if (getLangOpts().CPlusPlus) 14465 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14466 14467 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14468 if (ERes.isInvalid()) 14469 return ExprError(); 14470 E = ERes.get(); 14471 14472 QualType T = E->getType(); 14473 if (!T->isScalarType()) { // C99 6.8.4.1p1 14474 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14475 << T << E->getSourceRange(); 14476 return ExprError(); 14477 } 14478 CheckBoolLikeConversion(E, Loc); 14479 } 14480 14481 return E; 14482 } 14483 14484 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14485 Expr *SubExpr, ConditionKind CK) { 14486 // Empty conditions are valid in for-statements. 14487 if (!SubExpr) 14488 return ConditionResult(); 14489 14490 ExprResult Cond; 14491 switch (CK) { 14492 case ConditionKind::Boolean: 14493 Cond = CheckBooleanCondition(Loc, SubExpr); 14494 break; 14495 14496 case ConditionKind::ConstexprIf: 14497 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14498 break; 14499 14500 case ConditionKind::Switch: 14501 Cond = CheckSwitchCondition(Loc, SubExpr); 14502 break; 14503 } 14504 if (Cond.isInvalid()) 14505 return ConditionError(); 14506 14507 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14508 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14509 if (!FullExpr.get()) 14510 return ConditionError(); 14511 14512 return ConditionResult(*this, nullptr, FullExpr, 14513 CK == ConditionKind::ConstexprIf); 14514 } 14515 14516 namespace { 14517 /// A visitor for rebuilding a call to an __unknown_any expression 14518 /// to have an appropriate type. 14519 struct RebuildUnknownAnyFunction 14520 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14521 14522 Sema &S; 14523 14524 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14525 14526 ExprResult VisitStmt(Stmt *S) { 14527 llvm_unreachable("unexpected statement!"); 14528 } 14529 14530 ExprResult VisitExpr(Expr *E) { 14531 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14532 << E->getSourceRange(); 14533 return ExprError(); 14534 } 14535 14536 /// Rebuild an expression which simply semantically wraps another 14537 /// expression which it shares the type and value kind of. 14538 template <class T> ExprResult rebuildSugarExpr(T *E) { 14539 ExprResult SubResult = Visit(E->getSubExpr()); 14540 if (SubResult.isInvalid()) return ExprError(); 14541 14542 Expr *SubExpr = SubResult.get(); 14543 E->setSubExpr(SubExpr); 14544 E->setType(SubExpr->getType()); 14545 E->setValueKind(SubExpr->getValueKind()); 14546 assert(E->getObjectKind() == OK_Ordinary); 14547 return E; 14548 } 14549 14550 ExprResult VisitParenExpr(ParenExpr *E) { 14551 return rebuildSugarExpr(E); 14552 } 14553 14554 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14555 return rebuildSugarExpr(E); 14556 } 14557 14558 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14559 ExprResult SubResult = Visit(E->getSubExpr()); 14560 if (SubResult.isInvalid()) return ExprError(); 14561 14562 Expr *SubExpr = SubResult.get(); 14563 E->setSubExpr(SubExpr); 14564 E->setType(S.Context.getPointerType(SubExpr->getType())); 14565 assert(E->getValueKind() == VK_RValue); 14566 assert(E->getObjectKind() == OK_Ordinary); 14567 return E; 14568 } 14569 14570 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14571 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14572 14573 E->setType(VD->getType()); 14574 14575 assert(E->getValueKind() == VK_RValue); 14576 if (S.getLangOpts().CPlusPlus && 14577 !(isa<CXXMethodDecl>(VD) && 14578 cast<CXXMethodDecl>(VD)->isInstance())) 14579 E->setValueKind(VK_LValue); 14580 14581 return E; 14582 } 14583 14584 ExprResult VisitMemberExpr(MemberExpr *E) { 14585 return resolveDecl(E, E->getMemberDecl()); 14586 } 14587 14588 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14589 return resolveDecl(E, E->getDecl()); 14590 } 14591 }; 14592 } 14593 14594 /// Given a function expression of unknown-any type, try to rebuild it 14595 /// to have a function type. 14596 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14597 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14598 if (Result.isInvalid()) return ExprError(); 14599 return S.DefaultFunctionArrayConversion(Result.get()); 14600 } 14601 14602 namespace { 14603 /// A visitor for rebuilding an expression of type __unknown_anytype 14604 /// into one which resolves the type directly on the referring 14605 /// expression. Strict preservation of the original source 14606 /// structure is not a goal. 14607 struct RebuildUnknownAnyExpr 14608 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14609 14610 Sema &S; 14611 14612 /// The current destination type. 14613 QualType DestType; 14614 14615 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14616 : S(S), DestType(CastType) {} 14617 14618 ExprResult VisitStmt(Stmt *S) { 14619 llvm_unreachable("unexpected statement!"); 14620 } 14621 14622 ExprResult VisitExpr(Expr *E) { 14623 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14624 << E->getSourceRange(); 14625 return ExprError(); 14626 } 14627 14628 ExprResult VisitCallExpr(CallExpr *E); 14629 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14630 14631 /// Rebuild an expression which simply semantically wraps another 14632 /// expression which it shares the type and value kind of. 14633 template <class T> ExprResult rebuildSugarExpr(T *E) { 14634 ExprResult SubResult = Visit(E->getSubExpr()); 14635 if (SubResult.isInvalid()) return ExprError(); 14636 Expr *SubExpr = SubResult.get(); 14637 E->setSubExpr(SubExpr); 14638 E->setType(SubExpr->getType()); 14639 E->setValueKind(SubExpr->getValueKind()); 14640 assert(E->getObjectKind() == OK_Ordinary); 14641 return E; 14642 } 14643 14644 ExprResult VisitParenExpr(ParenExpr *E) { 14645 return rebuildSugarExpr(E); 14646 } 14647 14648 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14649 return rebuildSugarExpr(E); 14650 } 14651 14652 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14653 const PointerType *Ptr = DestType->getAs<PointerType>(); 14654 if (!Ptr) { 14655 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14656 << E->getSourceRange(); 14657 return ExprError(); 14658 } 14659 assert(E->getValueKind() == VK_RValue); 14660 assert(E->getObjectKind() == OK_Ordinary); 14661 E->setType(DestType); 14662 14663 // Build the sub-expression as if it were an object of the pointee type. 14664 DestType = Ptr->getPointeeType(); 14665 ExprResult SubResult = Visit(E->getSubExpr()); 14666 if (SubResult.isInvalid()) return ExprError(); 14667 E->setSubExpr(SubResult.get()); 14668 return E; 14669 } 14670 14671 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14672 14673 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14674 14675 ExprResult VisitMemberExpr(MemberExpr *E) { 14676 return resolveDecl(E, E->getMemberDecl()); 14677 } 14678 14679 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14680 return resolveDecl(E, E->getDecl()); 14681 } 14682 }; 14683 } 14684 14685 /// Rebuilds a call expression which yielded __unknown_anytype. 14686 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14687 Expr *CalleeExpr = E->getCallee(); 14688 14689 enum FnKind { 14690 FK_MemberFunction, 14691 FK_FunctionPointer, 14692 FK_BlockPointer 14693 }; 14694 14695 FnKind Kind; 14696 QualType CalleeType = CalleeExpr->getType(); 14697 if (CalleeType == S.Context.BoundMemberTy) { 14698 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14699 Kind = FK_MemberFunction; 14700 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14701 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14702 CalleeType = Ptr->getPointeeType(); 14703 Kind = FK_FunctionPointer; 14704 } else { 14705 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14706 Kind = FK_BlockPointer; 14707 } 14708 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14709 14710 // Verify that this is a legal result type of a function. 14711 if (DestType->isArrayType() || DestType->isFunctionType()) { 14712 unsigned diagID = diag::err_func_returning_array_function; 14713 if (Kind == FK_BlockPointer) 14714 diagID = diag::err_block_returning_array_function; 14715 14716 S.Diag(E->getExprLoc(), diagID) 14717 << DestType->isFunctionType() << DestType; 14718 return ExprError(); 14719 } 14720 14721 // Otherwise, go ahead and set DestType as the call's result. 14722 E->setType(DestType.getNonLValueExprType(S.Context)); 14723 E->setValueKind(Expr::getValueKindForType(DestType)); 14724 assert(E->getObjectKind() == OK_Ordinary); 14725 14726 // Rebuild the function type, replacing the result type with DestType. 14727 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14728 if (Proto) { 14729 // __unknown_anytype(...) is a special case used by the debugger when 14730 // it has no idea what a function's signature is. 14731 // 14732 // We want to build this call essentially under the K&R 14733 // unprototyped rules, but making a FunctionNoProtoType in C++ 14734 // would foul up all sorts of assumptions. However, we cannot 14735 // simply pass all arguments as variadic arguments, nor can we 14736 // portably just call the function under a non-variadic type; see 14737 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14738 // However, it turns out that in practice it is generally safe to 14739 // call a function declared as "A foo(B,C,D);" under the prototype 14740 // "A foo(B,C,D,...);". The only known exception is with the 14741 // Windows ABI, where any variadic function is implicitly cdecl 14742 // regardless of its normal CC. Therefore we change the parameter 14743 // types to match the types of the arguments. 14744 // 14745 // This is a hack, but it is far superior to moving the 14746 // corresponding target-specific code from IR-gen to Sema/AST. 14747 14748 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14749 SmallVector<QualType, 8> ArgTypes; 14750 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14751 ArgTypes.reserve(E->getNumArgs()); 14752 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14753 Expr *Arg = E->getArg(i); 14754 QualType ArgType = Arg->getType(); 14755 if (E->isLValue()) { 14756 ArgType = S.Context.getLValueReferenceType(ArgType); 14757 } else if (E->isXValue()) { 14758 ArgType = S.Context.getRValueReferenceType(ArgType); 14759 } 14760 ArgTypes.push_back(ArgType); 14761 } 14762 ParamTypes = ArgTypes; 14763 } 14764 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14765 Proto->getExtProtoInfo()); 14766 } else { 14767 DestType = S.Context.getFunctionNoProtoType(DestType, 14768 FnType->getExtInfo()); 14769 } 14770 14771 // Rebuild the appropriate pointer-to-function type. 14772 switch (Kind) { 14773 case FK_MemberFunction: 14774 // Nothing to do. 14775 break; 14776 14777 case FK_FunctionPointer: 14778 DestType = S.Context.getPointerType(DestType); 14779 break; 14780 14781 case FK_BlockPointer: 14782 DestType = S.Context.getBlockPointerType(DestType); 14783 break; 14784 } 14785 14786 // Finally, we can recurse. 14787 ExprResult CalleeResult = Visit(CalleeExpr); 14788 if (!CalleeResult.isUsable()) return ExprError(); 14789 E->setCallee(CalleeResult.get()); 14790 14791 // Bind a temporary if necessary. 14792 return S.MaybeBindToTemporary(E); 14793 } 14794 14795 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14796 // Verify that this is a legal result type of a call. 14797 if (DestType->isArrayType() || DestType->isFunctionType()) { 14798 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14799 << DestType->isFunctionType() << DestType; 14800 return ExprError(); 14801 } 14802 14803 // Rewrite the method result type if available. 14804 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14805 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14806 Method->setReturnType(DestType); 14807 } 14808 14809 // Change the type of the message. 14810 E->setType(DestType.getNonReferenceType()); 14811 E->setValueKind(Expr::getValueKindForType(DestType)); 14812 14813 return S.MaybeBindToTemporary(E); 14814 } 14815 14816 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14817 // The only case we should ever see here is a function-to-pointer decay. 14818 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14819 assert(E->getValueKind() == VK_RValue); 14820 assert(E->getObjectKind() == OK_Ordinary); 14821 14822 E->setType(DestType); 14823 14824 // Rebuild the sub-expression as the pointee (function) type. 14825 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14826 14827 ExprResult Result = Visit(E->getSubExpr()); 14828 if (!Result.isUsable()) return ExprError(); 14829 14830 E->setSubExpr(Result.get()); 14831 return E; 14832 } else if (E->getCastKind() == CK_LValueToRValue) { 14833 assert(E->getValueKind() == VK_RValue); 14834 assert(E->getObjectKind() == OK_Ordinary); 14835 14836 assert(isa<BlockPointerType>(E->getType())); 14837 14838 E->setType(DestType); 14839 14840 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14841 DestType = S.Context.getLValueReferenceType(DestType); 14842 14843 ExprResult Result = Visit(E->getSubExpr()); 14844 if (!Result.isUsable()) return ExprError(); 14845 14846 E->setSubExpr(Result.get()); 14847 return E; 14848 } else { 14849 llvm_unreachable("Unhandled cast type!"); 14850 } 14851 } 14852 14853 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14854 ExprValueKind ValueKind = VK_LValue; 14855 QualType Type = DestType; 14856 14857 // We know how to make this work for certain kinds of decls: 14858 14859 // - functions 14860 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14861 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14862 DestType = Ptr->getPointeeType(); 14863 ExprResult Result = resolveDecl(E, VD); 14864 if (Result.isInvalid()) return ExprError(); 14865 return S.ImpCastExprToType(Result.get(), Type, 14866 CK_FunctionToPointerDecay, VK_RValue); 14867 } 14868 14869 if (!Type->isFunctionType()) { 14870 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14871 << VD << E->getSourceRange(); 14872 return ExprError(); 14873 } 14874 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14875 // We must match the FunctionDecl's type to the hack introduced in 14876 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14877 // type. See the lengthy commentary in that routine. 14878 QualType FDT = FD->getType(); 14879 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14880 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14881 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14882 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14883 SourceLocation Loc = FD->getLocation(); 14884 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14885 FD->getDeclContext(), 14886 Loc, Loc, FD->getNameInfo().getName(), 14887 DestType, FD->getTypeSourceInfo(), 14888 SC_None, false/*isInlineSpecified*/, 14889 FD->hasPrototype(), 14890 false/*isConstexprSpecified*/); 14891 14892 if (FD->getQualifier()) 14893 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14894 14895 SmallVector<ParmVarDecl*, 16> Params; 14896 for (const auto &AI : FT->param_types()) { 14897 ParmVarDecl *Param = 14898 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14899 Param->setScopeInfo(0, Params.size()); 14900 Params.push_back(Param); 14901 } 14902 NewFD->setParams(Params); 14903 DRE->setDecl(NewFD); 14904 VD = DRE->getDecl(); 14905 } 14906 } 14907 14908 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14909 if (MD->isInstance()) { 14910 ValueKind = VK_RValue; 14911 Type = S.Context.BoundMemberTy; 14912 } 14913 14914 // Function references aren't l-values in C. 14915 if (!S.getLangOpts().CPlusPlus) 14916 ValueKind = VK_RValue; 14917 14918 // - variables 14919 } else if (isa<VarDecl>(VD)) { 14920 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14921 Type = RefTy->getPointeeType(); 14922 } else if (Type->isFunctionType()) { 14923 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14924 << VD << E->getSourceRange(); 14925 return ExprError(); 14926 } 14927 14928 // - nothing else 14929 } else { 14930 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14931 << VD << E->getSourceRange(); 14932 return ExprError(); 14933 } 14934 14935 // Modifying the declaration like this is friendly to IR-gen but 14936 // also really dangerous. 14937 VD->setType(DestType); 14938 E->setType(Type); 14939 E->setValueKind(ValueKind); 14940 return E; 14941 } 14942 14943 /// Check a cast of an unknown-any type. We intentionally only 14944 /// trigger this for C-style casts. 14945 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14946 Expr *CastExpr, CastKind &CastKind, 14947 ExprValueKind &VK, CXXCastPath &Path) { 14948 // The type we're casting to must be either void or complete. 14949 if (!CastType->isVoidType() && 14950 RequireCompleteType(TypeRange.getBegin(), CastType, 14951 diag::err_typecheck_cast_to_incomplete)) 14952 return ExprError(); 14953 14954 // Rewrite the casted expression from scratch. 14955 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14956 if (!result.isUsable()) return ExprError(); 14957 14958 CastExpr = result.get(); 14959 VK = CastExpr->getValueKind(); 14960 CastKind = CK_NoOp; 14961 14962 return CastExpr; 14963 } 14964 14965 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14966 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14967 } 14968 14969 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14970 Expr *arg, QualType ¶mType) { 14971 // If the syntactic form of the argument is not an explicit cast of 14972 // any sort, just do default argument promotion. 14973 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14974 if (!castArg) { 14975 ExprResult result = DefaultArgumentPromotion(arg); 14976 if (result.isInvalid()) return ExprError(); 14977 paramType = result.get()->getType(); 14978 return result; 14979 } 14980 14981 // Otherwise, use the type that was written in the explicit cast. 14982 assert(!arg->hasPlaceholderType()); 14983 paramType = castArg->getTypeAsWritten(); 14984 14985 // Copy-initialize a parameter of that type. 14986 InitializedEntity entity = 14987 InitializedEntity::InitializeParameter(Context, paramType, 14988 /*consumed*/ false); 14989 return PerformCopyInitialization(entity, callLoc, arg); 14990 } 14991 14992 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14993 Expr *orig = E; 14994 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14995 while (true) { 14996 E = E->IgnoreParenImpCasts(); 14997 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14998 E = call->getCallee(); 14999 diagID = diag::err_uncasted_call_of_unknown_any; 15000 } else { 15001 break; 15002 } 15003 } 15004 15005 SourceLocation loc; 15006 NamedDecl *d; 15007 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15008 loc = ref->getLocation(); 15009 d = ref->getDecl(); 15010 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15011 loc = mem->getMemberLoc(); 15012 d = mem->getMemberDecl(); 15013 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15014 diagID = diag::err_uncasted_call_of_unknown_any; 15015 loc = msg->getSelectorStartLoc(); 15016 d = msg->getMethodDecl(); 15017 if (!d) { 15018 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15019 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15020 << orig->getSourceRange(); 15021 return ExprError(); 15022 } 15023 } else { 15024 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15025 << E->getSourceRange(); 15026 return ExprError(); 15027 } 15028 15029 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15030 15031 // Never recoverable. 15032 return ExprError(); 15033 } 15034 15035 /// Check for operands with placeholder types and complain if found. 15036 /// Returns true if there was an error and no recovery was possible. 15037 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15038 if (!getLangOpts().CPlusPlus) { 15039 // C cannot handle TypoExpr nodes on either side of a binop because it 15040 // doesn't handle dependent types properly, so make sure any TypoExprs have 15041 // been dealt with before checking the operands. 15042 ExprResult Result = CorrectDelayedTyposInExpr(E); 15043 if (!Result.isUsable()) return ExprError(); 15044 E = Result.get(); 15045 } 15046 15047 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15048 if (!placeholderType) return E; 15049 15050 switch (placeholderType->getKind()) { 15051 15052 // Overloaded expressions. 15053 case BuiltinType::Overload: { 15054 // Try to resolve a single function template specialization. 15055 // This is obligatory. 15056 ExprResult Result = E; 15057 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15058 return Result; 15059 15060 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15061 // leaves Result unchanged on failure. 15062 Result = E; 15063 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15064 return Result; 15065 15066 // If that failed, try to recover with a call. 15067 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15068 /*complain*/ true); 15069 return Result; 15070 } 15071 15072 // Bound member functions. 15073 case BuiltinType::BoundMember: { 15074 ExprResult result = E; 15075 const Expr *BME = E->IgnoreParens(); 15076 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15077 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15078 if (isa<CXXPseudoDestructorExpr>(BME)) { 15079 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15080 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15081 if (ME->getMemberNameInfo().getName().getNameKind() == 15082 DeclarationName::CXXDestructorName) 15083 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15084 } 15085 tryToRecoverWithCall(result, PD, 15086 /*complain*/ true); 15087 return result; 15088 } 15089 15090 // ARC unbridged casts. 15091 case BuiltinType::ARCUnbridgedCast: { 15092 Expr *realCast = stripARCUnbridgedCast(E); 15093 diagnoseARCUnbridgedCast(realCast); 15094 return realCast; 15095 } 15096 15097 // Expressions of unknown type. 15098 case BuiltinType::UnknownAny: 15099 return diagnoseUnknownAnyExpr(*this, E); 15100 15101 // Pseudo-objects. 15102 case BuiltinType::PseudoObject: 15103 return checkPseudoObjectRValue(E); 15104 15105 case BuiltinType::BuiltinFn: { 15106 // Accept __noop without parens by implicitly converting it to a call expr. 15107 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15108 if (DRE) { 15109 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15110 if (FD->getBuiltinID() == Builtin::BI__noop) { 15111 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15112 CK_BuiltinFnToFnPtr).get(); 15113 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15114 VK_RValue, SourceLocation()); 15115 } 15116 } 15117 15118 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15119 return ExprError(); 15120 } 15121 15122 // Expressions of unknown type. 15123 case BuiltinType::OMPArraySection: 15124 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15125 return ExprError(); 15126 15127 // Everything else should be impossible. 15128 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15129 case BuiltinType::Id: 15130 #include "clang/Basic/OpenCLImageTypes.def" 15131 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15132 #define PLACEHOLDER_TYPE(Id, SingletonId) 15133 #include "clang/AST/BuiltinTypes.def" 15134 break; 15135 } 15136 15137 llvm_unreachable("invalid placeholder type!"); 15138 } 15139 15140 bool Sema::CheckCaseExpression(Expr *E) { 15141 if (E->isTypeDependent()) 15142 return true; 15143 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15144 return E->getType()->isIntegralOrEnumerationType(); 15145 return false; 15146 } 15147 15148 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15149 ExprResult 15150 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15151 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15152 "Unknown Objective-C Boolean value!"); 15153 QualType BoolT = Context.ObjCBuiltinBoolTy; 15154 if (!Context.getBOOLDecl()) { 15155 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15156 Sema::LookupOrdinaryName); 15157 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15158 NamedDecl *ND = Result.getFoundDecl(); 15159 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15160 Context.setBOOLDecl(TD); 15161 } 15162 } 15163 if (Context.getBOOLDecl()) 15164 BoolT = Context.getBOOLType(); 15165 return new (Context) 15166 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15167 } 15168 15169 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15170 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15171 SourceLocation RParen) { 15172 15173 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15174 15175 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15176 [&](const AvailabilitySpec &Spec) { 15177 return Spec.getPlatform() == Platform; 15178 }); 15179 15180 VersionTuple Version; 15181 if (Spec != AvailSpecs.end()) 15182 Version = Spec->getVersion(); 15183 else 15184 // This is the '*' case in @available. We should diagnose this; the 15185 // programmer should explicitly account for this case if they target this 15186 // platform. 15187 Diag(AtLoc, diag::warn_available_using_star_case) << RParen << Platform; 15188 15189 return new (Context) 15190 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15191 } 15192