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 "clang/Sema/SemaInternal.h" 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/ExprOpenMP.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.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) { 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 (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 (D->hasAttr<UnusedAttr>()) { 80 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 81 if (DC && !DC->hasAttr<UnusedAttr>()) 82 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 83 } 84 } 85 86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 87 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 88 if (!OMD) 89 return false; 90 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 91 if (!OID) 92 return false; 93 94 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 95 if (ObjCMethodDecl *CatMeth = 96 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 97 if (!CatMeth->hasAttr<AvailabilityAttr>()) 98 return true; 99 return false; 100 } 101 102 static AvailabilityResult 103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 104 const ObjCInterfaceDecl *UnknownObjCClass, 105 bool ObjCPropertyAccess) { 106 // See if this declaration is unavailable or deprecated. 107 std::string Message; 108 AvailabilityResult Result = D->getAvailability(&Message); 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); 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); 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); 136 } 137 138 const ObjCPropertyDecl *ObjCPDecl = nullptr; 139 if (Result == AR_Deprecated || Result == AR_Unavailable || 140 AR_NotYetIntroduced) { 141 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 142 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 143 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 144 if (PDeclResult == Result) 145 ObjCPDecl = PD; 146 } 147 } 148 } 149 150 switch (Result) { 151 case AR_Available: 152 break; 153 154 case AR_Deprecated: 155 if (S.getCurContextAvailability() != AR_Deprecated) 156 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 157 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 158 ObjCPropertyAccess); 159 break; 160 161 case AR_NotYetIntroduced: { 162 // Don't do this for enums, they can't be redeclared. 163 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 164 break; 165 166 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 167 // Objective-C method declarations in categories are not modelled as 168 // redeclarations, so manually look for a redeclaration in a category 169 // if necessary. 170 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 171 Warn = false; 172 // In general, D will point to the most recent redeclaration. However, 173 // for `@class A;` decls, this isn't true -- manually go through the 174 // redecl chain in that case. 175 if (Warn && isa<ObjCInterfaceDecl>(D)) 176 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 177 Redecl = Redecl->getPreviousDecl()) 178 if (!Redecl->hasAttr<AvailabilityAttr>() || 179 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 180 Warn = false; 181 182 if (Warn) 183 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 184 UnknownObjCClass, ObjCPDecl, 185 ObjCPropertyAccess); 186 break; 187 } 188 189 case AR_Unavailable: 190 if (S.getCurContextAvailability() != AR_Unavailable) 191 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 192 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 193 ObjCPropertyAccess); 194 break; 195 196 } 197 return Result; 198 } 199 200 /// \brief Emit a note explaining that this function is deleted. 201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 202 assert(Decl->isDeleted()); 203 204 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 205 206 if (Method && Method->isDeleted() && Method->isDefaulted()) { 207 // If the method was explicitly defaulted, point at that declaration. 208 if (!Method->isImplicit()) 209 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 210 211 // Try to diagnose why this special member function was implicitly 212 // deleted. This might fail, if that reason no longer applies. 213 CXXSpecialMember CSM = getSpecialMember(Method); 214 if (CSM != CXXInvalid) 215 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 216 217 return; 218 } 219 220 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 221 if (CXXConstructorDecl *BaseCD = 222 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 223 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 224 if (BaseCD->isDeleted()) { 225 NoteDeletedFunction(BaseCD); 226 } else { 227 // FIXME: An explanation of why exactly it can't be inherited 228 // would be nice. 229 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 230 } 231 return; 232 } 233 } 234 235 Diag(Decl->getLocation(), diag::note_availability_specified_here) 236 << Decl << true; 237 } 238 239 /// \brief Determine whether a FunctionDecl was ever declared with an 240 /// explicit storage class. 241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 242 for (auto I : D->redecls()) { 243 if (I->getStorageClass() != SC_None) 244 return true; 245 } 246 return false; 247 } 248 249 /// \brief Check whether we're in an extern inline function and referring to a 250 /// variable or function with internal linkage (C11 6.7.4p3). 251 /// 252 /// This is only a warning because we used to silently accept this code, but 253 /// in many cases it will not behave correctly. This is not enabled in C++ mode 254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 255 /// and so while there may still be user mistakes, most of the time we can't 256 /// prove that there are errors. 257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 258 const NamedDecl *D, 259 SourceLocation Loc) { 260 // This is disabled under C++; there are too many ways for this to fire in 261 // contexts where the warning is a false positive, or where it is technically 262 // correct but benign. 263 if (S.getLangOpts().CPlusPlus) 264 return; 265 266 // Check if this is an inlined function or method. 267 FunctionDecl *Current = S.getCurFunctionDecl(); 268 if (!Current) 269 return; 270 if (!Current->isInlined()) 271 return; 272 if (!Current->isExternallyVisible()) 273 return; 274 275 // Check if the decl has internal linkage. 276 if (D->getFormalLinkage() != InternalLinkage) 277 return; 278 279 // Downgrade from ExtWarn to Extension if 280 // (1) the supposedly external inline function is in the main file, 281 // and probably won't be included anywhere else. 282 // (2) the thing we're referencing is a pure function. 283 // (3) the thing we're referencing is another inline function. 284 // This last can give us false negatives, but it's better than warning on 285 // wrappers for simple C library functions. 286 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 287 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 288 if (!DowngradeWarning && UsedFn) 289 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 290 291 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 292 : diag::ext_internal_in_extern_inline) 293 << /*IsVar=*/!UsedFn << D; 294 295 S.MaybeSuggestAddingStaticToDecl(Current); 296 297 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 298 << D; 299 } 300 301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 302 const FunctionDecl *First = Cur->getFirstDecl(); 303 304 // Suggest "static" on the function, if possible. 305 if (!hasAnyExplicitStorageClass(First)) { 306 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 307 Diag(DeclBegin, diag::note_convert_inline_to_static) 308 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 309 } 310 } 311 312 /// \brief Determine whether the use of this declaration is valid, and 313 /// emit any corresponding diagnostics. 314 /// 315 /// This routine diagnoses various problems with referencing 316 /// declarations that can occur when using a declaration. For example, 317 /// it might warn if a deprecated or unavailable declaration is being 318 /// used, or produce an error (and return true) if a C++0x deleted 319 /// function is being used. 320 /// 321 /// \returns true if there was an error (this declaration cannot be 322 /// referenced), false otherwise. 323 /// 324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 325 const ObjCInterfaceDecl *UnknownObjCClass, 326 bool ObjCPropertyAccess) { 327 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 328 // If there were any diagnostics suppressed by template argument deduction, 329 // emit them now. 330 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 331 if (Pos != SuppressedDiagnostics.end()) { 332 for (const PartialDiagnosticAt &Suppressed : Pos->second) 333 Diag(Suppressed.first, Suppressed.second); 334 335 // Clear out the list of suppressed diagnostics, so that we don't emit 336 // them again for this specialization. However, we don't obsolete this 337 // entry from the table, because we want to avoid ever emitting these 338 // diagnostics again. 339 Pos->second.clear(); 340 } 341 342 // C++ [basic.start.main]p3: 343 // The function 'main' shall not be used within a program. 344 if (cast<FunctionDecl>(D)->isMain()) 345 Diag(Loc, diag::ext_main_used); 346 } 347 348 // See if this is an auto-typed variable whose initializer we are parsing. 349 if (ParsingInitForAutoVars.count(D)) { 350 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 351 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName() << (unsigned)AT->getKeyword(); 354 return true; 355 } 356 357 // See if this is a deleted function. 358 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 359 if (FD->isDeleted()) { 360 Diag(Loc, diag::err_deleted_function_use); 361 NoteDeletedFunction(FD); 362 return true; 363 } 364 365 // If the function has a deduced return type, and we can't deduce it, 366 // then we can't use it either. 367 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 368 DeduceReturnType(FD, Loc)) 369 return true; 370 } 371 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 372 ObjCPropertyAccess); 373 374 DiagnoseUnusedOfDecl(*this, D, Loc); 375 376 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 377 378 return false; 379 } 380 381 /// \brief Retrieve the message suffix that should be added to a 382 /// diagnostic complaining about the given function being deleted or 383 /// unavailable. 384 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 385 std::string Message; 386 if (FD->getAvailability(&Message)) 387 return ": " + Message; 388 389 return std::string(); 390 } 391 392 /// DiagnoseSentinelCalls - This routine checks whether a call or 393 /// message-send is to a declaration with the sentinel attribute, and 394 /// if so, it checks that the requirements of the sentinel are 395 /// satisfied. 396 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 397 ArrayRef<Expr *> Args) { 398 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 399 if (!attr) 400 return; 401 402 // The number of formal parameters of the declaration. 403 unsigned numFormalParams; 404 405 // The kind of declaration. This is also an index into a %select in 406 // the diagnostic. 407 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 408 409 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 410 numFormalParams = MD->param_size(); 411 calleeType = CT_Method; 412 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 413 numFormalParams = FD->param_size(); 414 calleeType = CT_Function; 415 } else if (isa<VarDecl>(D)) { 416 QualType type = cast<ValueDecl>(D)->getType(); 417 const FunctionType *fn = nullptr; 418 if (const PointerType *ptr = type->getAs<PointerType>()) { 419 fn = ptr->getPointeeType()->getAs<FunctionType>(); 420 if (!fn) return; 421 calleeType = CT_Function; 422 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 423 fn = ptr->getPointeeType()->castAs<FunctionType>(); 424 calleeType = CT_Block; 425 } else { 426 return; 427 } 428 429 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 430 numFormalParams = proto->getNumParams(); 431 } else { 432 numFormalParams = 0; 433 } 434 } else { 435 return; 436 } 437 438 // "nullPos" is the number of formal parameters at the end which 439 // effectively count as part of the variadic arguments. This is 440 // useful if you would prefer to not have *any* formal parameters, 441 // but the language forces you to have at least one. 442 unsigned nullPos = attr->getNullPos(); 443 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 444 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 445 446 // The number of arguments which should follow the sentinel. 447 unsigned numArgsAfterSentinel = attr->getSentinel(); 448 449 // If there aren't enough arguments for all the formal parameters, 450 // the sentinel, and the args after the sentinel, complain. 451 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 452 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 453 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 454 return; 455 } 456 457 // Otherwise, find the sentinel expression. 458 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 459 if (!sentinelExpr) return; 460 if (sentinelExpr->isValueDependent()) return; 461 if (Context.isSentinelNullExpr(sentinelExpr)) return; 462 463 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 464 // or 'NULL' if those are actually defined in the context. Only use 465 // 'nil' for ObjC methods, where it's much more likely that the 466 // variadic arguments form a list of object pointers. 467 SourceLocation MissingNilLoc 468 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 // If we are here, we are not calling a function but taking 510 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 511 if (getLangOpts().OpenCL) { 512 if (Diagnose) 513 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 514 return ExprError(); 515 } 516 517 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 518 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 519 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 520 return ExprError(); 521 522 E = ImpCastExprToType(E, Context.getPointerType(Ty), 523 CK_FunctionToPointerDecay).get(); 524 } else if (Ty->isArrayType()) { 525 // In C90 mode, arrays only promote to pointers if the array expression is 526 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 527 // type 'array of type' is converted to an expression that has type 'pointer 528 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 529 // that has type 'array of type' ...". The relevant change is "an lvalue" 530 // (C90) to "an expression" (C99). 531 // 532 // C++ 4.2p1: 533 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 534 // T" can be converted to an rvalue of type "pointer to T". 535 // 536 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 537 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 538 CK_ArrayToPointerDecay).get(); 539 } 540 return E; 541 } 542 543 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 544 // Check to see if we are dereferencing a null pointer. If so, 545 // and if not volatile-qualified, this is undefined behavior that the 546 // optimizer will delete, so warn about it. People sometimes try to use this 547 // to get a deterministic trap and are surprised by clang's behavior. This 548 // only handles the pattern "*null", which is a very syntactic check. 549 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 550 if (UO->getOpcode() == UO_Deref && 551 UO->getSubExpr()->IgnoreParenCasts()-> 552 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 553 !UO->getType().isVolatileQualified()) { 554 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 555 S.PDiag(diag::warn_indirection_through_null) 556 << UO->getSubExpr()->getSourceRange()); 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::note_indirection_through_null)); 559 } 560 } 561 562 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 563 SourceLocation AssignLoc, 564 const Expr* RHS) { 565 const ObjCIvarDecl *IV = OIRE->getDecl(); 566 if (!IV) 567 return; 568 569 DeclarationName MemberName = IV->getDeclName(); 570 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 571 if (!Member || !Member->isStr("isa")) 572 return; 573 574 const Expr *Base = OIRE->getBase(); 575 QualType BaseType = Base->getType(); 576 if (OIRE->isArrow()) 577 BaseType = BaseType->getPointeeType(); 578 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 579 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 580 ObjCInterfaceDecl *ClassDeclared = nullptr; 581 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 582 if (!ClassDeclared->getSuperClass() 583 && (*ClassDeclared->ivar_begin()) == IV) { 584 if (RHS) { 585 NamedDecl *ObjectSetClass = 586 S.LookupSingleName(S.TUScope, 587 &S.Context.Idents.get("object_setClass"), 588 SourceLocation(), S.LookupOrdinaryName); 589 if (ObjectSetClass) { 590 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 591 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 592 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 593 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 594 AssignLoc), ",") << 595 FixItHint::CreateInsertion(RHSLocEnd, ")"); 596 } 597 else 598 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 599 } else { 600 NamedDecl *ObjectGetClass = 601 S.LookupSingleName(S.TUScope, 602 &S.Context.Idents.get("object_getClass"), 603 SourceLocation(), S.LookupOrdinaryName); 604 if (ObjectGetClass) 605 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 606 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 607 FixItHint::CreateReplacement( 608 SourceRange(OIRE->getOpLoc(), 609 OIRE->getLocEnd()), ")"); 610 else 611 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 612 } 613 S.Diag(IV->getLocation(), diag::note_ivar_decl); 614 } 615 } 616 } 617 618 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 619 // Handle any placeholder expressions which made it here. 620 if (E->getType()->isPlaceholderType()) { 621 ExprResult result = CheckPlaceholderExpr(E); 622 if (result.isInvalid()) return ExprError(); 623 E = result.get(); 624 } 625 626 // C++ [conv.lval]p1: 627 // A glvalue of a non-function, non-array type T can be 628 // converted to a prvalue. 629 if (!E->isGLValue()) return E; 630 631 QualType T = E->getType(); 632 assert(!T.isNull() && "r-value conversion on typeless expression?"); 633 634 // We don't want to throw lvalue-to-rvalue casts on top of 635 // expressions of certain types in C++. 636 if (getLangOpts().CPlusPlus && 637 (E->getType() == Context.OverloadTy || 638 T->isDependentType() || 639 T->isRecordType())) 640 return E; 641 642 // The C standard is actually really unclear on this point, and 643 // DR106 tells us what the result should be but not why. It's 644 // generally best to say that void types just doesn't undergo 645 // lvalue-to-rvalue at all. Note that expressions of unqualified 646 // 'void' type are never l-values, but qualified void can be. 647 if (T->isVoidType()) 648 return E; 649 650 // OpenCL usually rejects direct accesses to values of 'half' type. 651 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 652 T->isHalfType()) { 653 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 654 << 0 << T; 655 return ExprError(); 656 } 657 658 CheckForNullPointerDereference(*this, E); 659 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 660 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 661 &Context.Idents.get("object_getClass"), 662 SourceLocation(), LookupOrdinaryName); 663 if (ObjectGetClass) 664 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 665 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 666 FixItHint::CreateReplacement( 667 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 668 else 669 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 670 } 671 else if (const ObjCIvarRefExpr *OIRE = 672 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 673 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 674 675 // C++ [conv.lval]p1: 676 // [...] If T is a non-class type, the type of the prvalue is the 677 // cv-unqualified version of T. Otherwise, the type of the 678 // rvalue is T. 679 // 680 // C99 6.3.2.1p2: 681 // If the lvalue has qualified type, the value has the unqualified 682 // version of the type of the lvalue; otherwise, the value has the 683 // type of the lvalue. 684 if (T.hasQualifiers()) 685 T = T.getUnqualifiedType(); 686 687 // Under the MS ABI, lock down the inheritance model now. 688 if (T->isMemberPointerType() && 689 Context.getTargetInfo().getCXXABI().isMicrosoft()) 690 (void)isCompleteType(E->getExprLoc(), T); 691 692 UpdateMarkingForLValueToRValue(E); 693 694 // Loading a __weak object implicitly retains the value, so we need a cleanup to 695 // balance that. 696 if (getLangOpts().ObjCAutoRefCount && 697 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 698 ExprNeedsCleanups = true; 699 700 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 701 nullptr, VK_RValue); 702 703 // C11 6.3.2.1p2: 704 // ... if the lvalue has atomic type, the value has the non-atomic version 705 // of the type of the lvalue ... 706 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 707 T = Atomic->getValueType().getUnqualifiedType(); 708 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 709 nullptr, VK_RValue); 710 } 711 712 return Res; 713 } 714 715 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 716 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 717 if (Res.isInvalid()) 718 return ExprError(); 719 Res = DefaultLvalueConversion(Res.get()); 720 if (Res.isInvalid()) 721 return ExprError(); 722 return Res; 723 } 724 725 /// CallExprUnaryConversions - a special case of an unary conversion 726 /// performed on a function designator of a call expression. 727 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 728 QualType Ty = E->getType(); 729 ExprResult Res = E; 730 // Only do implicit cast for a function type, but not for a pointer 731 // to function type. 732 if (Ty->isFunctionType()) { 733 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 734 CK_FunctionToPointerDecay).get(); 735 if (Res.isInvalid()) 736 return ExprError(); 737 } 738 Res = DefaultLvalueConversion(Res.get()); 739 if (Res.isInvalid()) 740 return ExprError(); 741 return Res.get(); 742 } 743 744 /// UsualUnaryConversions - Performs various conversions that are common to most 745 /// operators (C99 6.3). The conversions of array and function types are 746 /// sometimes suppressed. For example, the array->pointer conversion doesn't 747 /// apply if the array is an argument to the sizeof or address (&) operators. 748 /// In these instances, this routine should *not* be called. 749 ExprResult Sema::UsualUnaryConversions(Expr *E) { 750 // First, convert to an r-value. 751 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 752 if (Res.isInvalid()) 753 return ExprError(); 754 E = Res.get(); 755 756 QualType Ty = E->getType(); 757 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 758 759 // Half FP have to be promoted to float unless it is natively supported 760 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 761 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 762 763 // Try to perform integral promotions if the object has a theoretically 764 // promotable type. 765 if (Ty->isIntegralOrUnscopedEnumerationType()) { 766 // C99 6.3.1.1p2: 767 // 768 // The following may be used in an expression wherever an int or 769 // unsigned int may be used: 770 // - an object or expression with an integer type whose integer 771 // conversion rank is less than or equal to the rank of int 772 // and unsigned int. 773 // - A bit-field of type _Bool, int, signed int, or unsigned int. 774 // 775 // If an int can represent all values of the original type, the 776 // value is converted to an int; otherwise, it is converted to an 777 // unsigned int. These are called the integer promotions. All 778 // other types are unchanged by the integer promotions. 779 780 QualType PTy = Context.isPromotableBitField(E); 781 if (!PTy.isNull()) { 782 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 783 return E; 784 } 785 if (Ty->isPromotableIntegerType()) { 786 QualType PT = Context.getPromotedIntegerType(Ty); 787 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 788 return E; 789 } 790 } 791 return E; 792 } 793 794 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 795 /// do not have a prototype. Arguments that have type float or __fp16 796 /// are promoted to double. All other argument types are converted by 797 /// UsualUnaryConversions(). 798 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 799 QualType Ty = E->getType(); 800 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 801 802 ExprResult Res = UsualUnaryConversions(E); 803 if (Res.isInvalid()) 804 return ExprError(); 805 E = Res.get(); 806 807 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 808 // double. 809 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 810 if (BTy && (BTy->getKind() == BuiltinType::Half || 811 BTy->getKind() == BuiltinType::Float)) 812 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 813 814 // C++ performs lvalue-to-rvalue conversion as a default argument 815 // promotion, even on class types, but note: 816 // C++11 [conv.lval]p2: 817 // When an lvalue-to-rvalue conversion occurs in an unevaluated 818 // operand or a subexpression thereof the value contained in the 819 // referenced object is not accessed. Otherwise, if the glvalue 820 // has a class type, the conversion copy-initializes a temporary 821 // of type T from the glvalue and the result of the conversion 822 // is a prvalue for the temporary. 823 // FIXME: add some way to gate this entire thing for correctness in 824 // potentially potentially evaluated contexts. 825 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 826 ExprResult Temp = PerformCopyInitialization( 827 InitializedEntity::InitializeTemporary(E->getType()), 828 E->getExprLoc(), E); 829 if (Temp.isInvalid()) 830 return ExprError(); 831 E = Temp.get(); 832 } 833 834 return E; 835 } 836 837 /// Determine the degree of POD-ness for an expression. 838 /// Incomplete types are considered POD, since this check can be performed 839 /// when we're in an unevaluated context. 840 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 841 if (Ty->isIncompleteType()) { 842 // C++11 [expr.call]p7: 843 // After these conversions, if the argument does not have arithmetic, 844 // enumeration, pointer, pointer to member, or class type, the program 845 // is ill-formed. 846 // 847 // Since we've already performed array-to-pointer and function-to-pointer 848 // decay, the only such type in C++ is cv void. This also handles 849 // initializer lists as variadic arguments. 850 if (Ty->isVoidType()) 851 return VAK_Invalid; 852 853 if (Ty->isObjCObjectType()) 854 return VAK_Invalid; 855 return VAK_Valid; 856 } 857 858 if (Ty.isCXX98PODType(Context)) 859 return VAK_Valid; 860 861 // C++11 [expr.call]p7: 862 // Passing a potentially-evaluated argument of class type (Clause 9) 863 // having a non-trivial copy constructor, a non-trivial move constructor, 864 // or a non-trivial destructor, with no corresponding parameter, 865 // is conditionally-supported with implementation-defined semantics. 866 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 867 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 868 if (!Record->hasNonTrivialCopyConstructor() && 869 !Record->hasNonTrivialMoveConstructor() && 870 !Record->hasNonTrivialDestructor()) 871 return VAK_ValidInCXX11; 872 873 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 874 return VAK_Valid; 875 876 if (Ty->isObjCObjectType()) 877 return VAK_Invalid; 878 879 if (getLangOpts().MSVCCompat) 880 return VAK_MSVCUndefined; 881 882 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 883 // permitted to reject them. We should consider doing so. 884 return VAK_Undefined; 885 } 886 887 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 888 // Don't allow one to pass an Objective-C interface to a vararg. 889 const QualType &Ty = E->getType(); 890 VarArgKind VAK = isValidVarArgType(Ty); 891 892 // Complain about passing non-POD types through varargs. 893 switch (VAK) { 894 case VAK_ValidInCXX11: 895 DiagRuntimeBehavior( 896 E->getLocStart(), nullptr, 897 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 898 << Ty << CT); 899 // Fall through. 900 case VAK_Valid: 901 if (Ty->isRecordType()) { 902 // This is unlikely to be what the user intended. If the class has a 903 // 'c_str' member function, the user probably meant to call that. 904 DiagRuntimeBehavior(E->getLocStart(), nullptr, 905 PDiag(diag::warn_pass_class_arg_to_vararg) 906 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 907 } 908 break; 909 910 case VAK_Undefined: 911 case VAK_MSVCUndefined: 912 DiagRuntimeBehavior( 913 E->getLocStart(), nullptr, 914 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 915 << getLangOpts().CPlusPlus11 << Ty << CT); 916 break; 917 918 case VAK_Invalid: 919 if (Ty->isObjCObjectType()) 920 DiagRuntimeBehavior( 921 E->getLocStart(), nullptr, 922 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 923 << Ty << CT); 924 else 925 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 926 << isa<InitListExpr>(E) << Ty << CT; 927 break; 928 } 929 } 930 931 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 932 /// will create a trap if the resulting type is not a POD type. 933 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 934 FunctionDecl *FDecl) { 935 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 936 // Strip the unbridged-cast placeholder expression off, if applicable. 937 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 938 (CT == VariadicMethod || 939 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 940 E = stripARCUnbridgedCast(E); 941 942 // Otherwise, do normal placeholder checking. 943 } else { 944 ExprResult ExprRes = CheckPlaceholderExpr(E); 945 if (ExprRes.isInvalid()) 946 return ExprError(); 947 E = ExprRes.get(); 948 } 949 } 950 951 ExprResult ExprRes = DefaultArgumentPromotion(E); 952 if (ExprRes.isInvalid()) 953 return ExprError(); 954 E = ExprRes.get(); 955 956 // Diagnostics regarding non-POD argument types are 957 // emitted along with format string checking in Sema::CheckFunctionCall(). 958 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 959 // Turn this into a trap. 960 CXXScopeSpec SS; 961 SourceLocation TemplateKWLoc; 962 UnqualifiedId Name; 963 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 964 E->getLocStart()); 965 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 966 Name, true, false); 967 if (TrapFn.isInvalid()) 968 return ExprError(); 969 970 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 971 E->getLocStart(), None, 972 E->getLocEnd()); 973 if (Call.isInvalid()) 974 return ExprError(); 975 976 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 977 Call.get(), E); 978 if (Comma.isInvalid()) 979 return ExprError(); 980 return Comma.get(); 981 } 982 983 if (!getLangOpts().CPlusPlus && 984 RequireCompleteType(E->getExprLoc(), E->getType(), 985 diag::err_call_incomplete_argument)) 986 return ExprError(); 987 988 return E; 989 } 990 991 /// \brief Converts an integer to complex float type. Helper function of 992 /// UsualArithmeticConversions() 993 /// 994 /// \return false if the integer expression is an integer type and is 995 /// successfully converted to the complex type. 996 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 997 ExprResult &ComplexExpr, 998 QualType IntTy, 999 QualType ComplexTy, 1000 bool SkipCast) { 1001 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1002 if (SkipCast) return false; 1003 if (IntTy->isIntegerType()) { 1004 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1005 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1006 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1007 CK_FloatingRealToComplex); 1008 } else { 1009 assert(IntTy->isComplexIntegerType()); 1010 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1011 CK_IntegralComplexToFloatingComplex); 1012 } 1013 return false; 1014 } 1015 1016 /// \brief Handle arithmetic conversion with complex types. Helper function of 1017 /// UsualArithmeticConversions() 1018 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1019 ExprResult &RHS, QualType LHSType, 1020 QualType RHSType, 1021 bool IsCompAssign) { 1022 // if we have an integer operand, the result is the complex type. 1023 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1024 /*skipCast*/false)) 1025 return LHSType; 1026 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1027 /*skipCast*/IsCompAssign)) 1028 return RHSType; 1029 1030 // This handles complex/complex, complex/float, or float/complex. 1031 // When both operands are complex, the shorter operand is converted to the 1032 // type of the longer, and that is the type of the result. This corresponds 1033 // to what is done when combining two real floating-point operands. 1034 // The fun begins when size promotion occur across type domains. 1035 // From H&S 6.3.4: When one operand is complex and the other is a real 1036 // floating-point type, the less precise type is converted, within it's 1037 // real or complex domain, to the precision of the other type. For example, 1038 // when combining a "long double" with a "double _Complex", the 1039 // "double _Complex" is promoted to "long double _Complex". 1040 1041 // Compute the rank of the two types, regardless of whether they are complex. 1042 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1043 1044 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1045 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1046 QualType LHSElementType = 1047 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1048 QualType RHSElementType = 1049 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1050 1051 QualType ResultType = S.Context.getComplexType(LHSElementType); 1052 if (Order < 0) { 1053 // Promote the precision of the LHS if not an assignment. 1054 ResultType = S.Context.getComplexType(RHSElementType); 1055 if (!IsCompAssign) { 1056 if (LHSComplexType) 1057 LHS = 1058 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1059 else 1060 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1061 } 1062 } else if (Order > 0) { 1063 // Promote the precision of the RHS. 1064 if (RHSComplexType) 1065 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1066 else 1067 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1068 } 1069 return ResultType; 1070 } 1071 1072 /// \brief Hande arithmetic conversion from integer to float. Helper function 1073 /// of UsualArithmeticConversions() 1074 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1075 ExprResult &IntExpr, 1076 QualType FloatTy, QualType IntTy, 1077 bool ConvertFloat, bool ConvertInt) { 1078 if (IntTy->isIntegerType()) { 1079 if (ConvertInt) 1080 // Convert intExpr to the lhs floating point type. 1081 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1082 CK_IntegralToFloating); 1083 return FloatTy; 1084 } 1085 1086 // Convert both sides to the appropriate complex float. 1087 assert(IntTy->isComplexIntegerType()); 1088 QualType result = S.Context.getComplexType(FloatTy); 1089 1090 // _Complex int -> _Complex float 1091 if (ConvertInt) 1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1093 CK_IntegralComplexToFloatingComplex); 1094 1095 // float -> _Complex float 1096 if (ConvertFloat) 1097 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1098 CK_FloatingRealToComplex); 1099 1100 return result; 1101 } 1102 1103 /// \brief Handle arithmethic conversion with floating point types. Helper 1104 /// function of UsualArithmeticConversions() 1105 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1106 ExprResult &RHS, QualType LHSType, 1107 QualType RHSType, bool IsCompAssign) { 1108 bool LHSFloat = LHSType->isRealFloatingType(); 1109 bool RHSFloat = RHSType->isRealFloatingType(); 1110 1111 // If we have two real floating types, convert the smaller operand 1112 // to the bigger result. 1113 if (LHSFloat && RHSFloat) { 1114 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1115 if (order > 0) { 1116 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1117 return LHSType; 1118 } 1119 1120 assert(order < 0 && "illegal float comparison"); 1121 if (!IsCompAssign) 1122 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1123 return RHSType; 1124 } 1125 1126 if (LHSFloat) { 1127 // Half FP has to be promoted to float unless it is natively supported 1128 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1129 LHSType = S.Context.FloatTy; 1130 1131 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1132 /*convertFloat=*/!IsCompAssign, 1133 /*convertInt=*/ true); 1134 } 1135 assert(RHSFloat); 1136 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1137 /*convertInt=*/ true, 1138 /*convertFloat=*/!IsCompAssign); 1139 } 1140 1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1142 1143 namespace { 1144 /// These helper callbacks are placed in an anonymous namespace to 1145 /// permit their use as function template parameters. 1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1147 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1148 } 1149 1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1151 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1152 CK_IntegralComplexCast); 1153 } 1154 } 1155 1156 /// \brief Handle integer arithmetic conversions. Helper function of 1157 /// UsualArithmeticConversions() 1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1160 ExprResult &RHS, QualType LHSType, 1161 QualType RHSType, bool IsCompAssign) { 1162 // The rules for this case are in C99 6.3.1.8 1163 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1164 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1165 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1166 if (LHSSigned == RHSSigned) { 1167 // Same signedness; use the higher-ranked type 1168 if (order >= 0) { 1169 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1170 return LHSType; 1171 } else if (!IsCompAssign) 1172 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1173 return RHSType; 1174 } else if (order != (LHSSigned ? 1 : -1)) { 1175 // The unsigned type has greater than or equal rank to the 1176 // signed type, so use the unsigned type 1177 if (RHSSigned) { 1178 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1179 return LHSType; 1180 } else if (!IsCompAssign) 1181 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1182 return RHSType; 1183 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1184 // The two types are different widths; if we are here, that 1185 // means the signed type is larger than the unsigned type, so 1186 // use the signed type. 1187 if (LHSSigned) { 1188 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1189 return LHSType; 1190 } else if (!IsCompAssign) 1191 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1192 return RHSType; 1193 } else { 1194 // The signed type is higher-ranked than the unsigned type, 1195 // but isn't actually any bigger (like unsigned int and long 1196 // on most 32-bit systems). Use the unsigned type corresponding 1197 // to the signed type. 1198 QualType result = 1199 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1200 RHS = (*doRHSCast)(S, RHS.get(), result); 1201 if (!IsCompAssign) 1202 LHS = (*doLHSCast)(S, LHS.get(), result); 1203 return result; 1204 } 1205 } 1206 1207 /// \brief Handle conversions with GCC complex int extension. Helper function 1208 /// of UsualArithmeticConversions() 1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1210 ExprResult &RHS, QualType LHSType, 1211 QualType RHSType, 1212 bool IsCompAssign) { 1213 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1214 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1215 1216 if (LHSComplexInt && RHSComplexInt) { 1217 QualType LHSEltType = LHSComplexInt->getElementType(); 1218 QualType RHSEltType = RHSComplexInt->getElementType(); 1219 QualType ScalarType = 1220 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1221 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1222 1223 return S.Context.getComplexType(ScalarType); 1224 } 1225 1226 if (LHSComplexInt) { 1227 QualType LHSEltType = LHSComplexInt->getElementType(); 1228 QualType ScalarType = 1229 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1230 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1231 QualType ComplexType = S.Context.getComplexType(ScalarType); 1232 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1233 CK_IntegralRealToComplex); 1234 1235 return ComplexType; 1236 } 1237 1238 assert(RHSComplexInt); 1239 1240 QualType RHSEltType = RHSComplexInt->getElementType(); 1241 QualType ScalarType = 1242 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1243 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1244 QualType ComplexType = S.Context.getComplexType(ScalarType); 1245 1246 if (!IsCompAssign) 1247 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1248 CK_IntegralRealToComplex); 1249 return ComplexType; 1250 } 1251 1252 /// UsualArithmeticConversions - Performs various conversions that are common to 1253 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1254 /// routine returns the first non-arithmetic type found. The client is 1255 /// responsible for emitting appropriate error diagnostics. 1256 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1257 bool IsCompAssign) { 1258 if (!IsCompAssign) { 1259 LHS = UsualUnaryConversions(LHS.get()); 1260 if (LHS.isInvalid()) 1261 return QualType(); 1262 } 1263 1264 RHS = UsualUnaryConversions(RHS.get()); 1265 if (RHS.isInvalid()) 1266 return QualType(); 1267 1268 // For conversion purposes, we ignore any qualifiers. 1269 // For example, "const float" and "float" are equivalent. 1270 QualType LHSType = 1271 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1272 QualType RHSType = 1273 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1274 1275 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1276 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1277 LHSType = AtomicLHS->getValueType(); 1278 1279 // If both types are identical, no conversion is needed. 1280 if (LHSType == RHSType) 1281 return LHSType; 1282 1283 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1284 // The caller can deal with this (e.g. pointer + int). 1285 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1286 return QualType(); 1287 1288 // Apply unary and bitfield promotions to the LHS's type. 1289 QualType LHSUnpromotedType = LHSType; 1290 if (LHSType->isPromotableIntegerType()) 1291 LHSType = Context.getPromotedIntegerType(LHSType); 1292 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1293 if (!LHSBitfieldPromoteTy.isNull()) 1294 LHSType = LHSBitfieldPromoteTy; 1295 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1296 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1297 1298 // If both types are identical, no conversion is needed. 1299 if (LHSType == RHSType) 1300 return LHSType; 1301 1302 // At this point, we have two different arithmetic types. 1303 1304 // Handle complex types first (C99 6.3.1.8p1). 1305 if (LHSType->isComplexType() || RHSType->isComplexType()) 1306 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1307 IsCompAssign); 1308 1309 // Now handle "real" floating types (i.e. float, double, long double). 1310 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1311 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1312 IsCompAssign); 1313 1314 // Handle GCC complex int extension. 1315 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1316 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1317 IsCompAssign); 1318 1319 // Finally, we have two differing integer types. 1320 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1321 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1322 } 1323 1324 1325 //===----------------------------------------------------------------------===// 1326 // Semantic Analysis for various Expression Types 1327 //===----------------------------------------------------------------------===// 1328 1329 1330 ExprResult 1331 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1332 SourceLocation DefaultLoc, 1333 SourceLocation RParenLoc, 1334 Expr *ControllingExpr, 1335 ArrayRef<ParsedType> ArgTypes, 1336 ArrayRef<Expr *> ArgExprs) { 1337 unsigned NumAssocs = ArgTypes.size(); 1338 assert(NumAssocs == ArgExprs.size()); 1339 1340 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1341 for (unsigned i = 0; i < NumAssocs; ++i) { 1342 if (ArgTypes[i]) 1343 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1344 else 1345 Types[i] = nullptr; 1346 } 1347 1348 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1349 ControllingExpr, 1350 llvm::makeArrayRef(Types, NumAssocs), 1351 ArgExprs); 1352 delete [] Types; 1353 return ER; 1354 } 1355 1356 ExprResult 1357 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1358 SourceLocation DefaultLoc, 1359 SourceLocation RParenLoc, 1360 Expr *ControllingExpr, 1361 ArrayRef<TypeSourceInfo *> Types, 1362 ArrayRef<Expr *> Exprs) { 1363 unsigned NumAssocs = Types.size(); 1364 assert(NumAssocs == Exprs.size()); 1365 1366 // Decay and strip qualifiers for the controlling expression type, and handle 1367 // placeholder type replacement. See committee discussion from WG14 DR423. 1368 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1369 if (R.isInvalid()) 1370 return ExprError(); 1371 ControllingExpr = R.get(); 1372 1373 // The controlling expression is an unevaluated operand, so side effects are 1374 // likely unintended. 1375 if (ActiveTemplateInstantiations.empty() && 1376 ControllingExpr->HasSideEffects(Context, false)) 1377 Diag(ControllingExpr->getExprLoc(), 1378 diag::warn_side_effects_unevaluated_context); 1379 1380 bool TypeErrorFound = false, 1381 IsResultDependent = ControllingExpr->isTypeDependent(), 1382 ContainsUnexpandedParameterPack 1383 = ControllingExpr->containsUnexpandedParameterPack(); 1384 1385 for (unsigned i = 0; i < NumAssocs; ++i) { 1386 if (Exprs[i]->containsUnexpandedParameterPack()) 1387 ContainsUnexpandedParameterPack = true; 1388 1389 if (Types[i]) { 1390 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1391 ContainsUnexpandedParameterPack = true; 1392 1393 if (Types[i]->getType()->isDependentType()) { 1394 IsResultDependent = true; 1395 } else { 1396 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1397 // complete object type other than a variably modified type." 1398 unsigned D = 0; 1399 if (Types[i]->getType()->isIncompleteType()) 1400 D = diag::err_assoc_type_incomplete; 1401 else if (!Types[i]->getType()->isObjectType()) 1402 D = diag::err_assoc_type_nonobject; 1403 else if (Types[i]->getType()->isVariablyModifiedType()) 1404 D = diag::err_assoc_type_variably_modified; 1405 1406 if (D != 0) { 1407 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1408 << Types[i]->getTypeLoc().getSourceRange() 1409 << Types[i]->getType(); 1410 TypeErrorFound = true; 1411 } 1412 1413 // C11 6.5.1.1p2 "No two generic associations in the same generic 1414 // selection shall specify compatible types." 1415 for (unsigned j = i+1; j < NumAssocs; ++j) 1416 if (Types[j] && !Types[j]->getType()->isDependentType() && 1417 Context.typesAreCompatible(Types[i]->getType(), 1418 Types[j]->getType())) { 1419 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1420 diag::err_assoc_compatible_types) 1421 << Types[j]->getTypeLoc().getSourceRange() 1422 << Types[j]->getType() 1423 << Types[i]->getType(); 1424 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1425 diag::note_compat_assoc) 1426 << Types[i]->getTypeLoc().getSourceRange() 1427 << Types[i]->getType(); 1428 TypeErrorFound = true; 1429 } 1430 } 1431 } 1432 } 1433 if (TypeErrorFound) 1434 return ExprError(); 1435 1436 // If we determined that the generic selection is result-dependent, don't 1437 // try to compute the result expression. 1438 if (IsResultDependent) 1439 return new (Context) GenericSelectionExpr( 1440 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1441 ContainsUnexpandedParameterPack); 1442 1443 SmallVector<unsigned, 1> CompatIndices; 1444 unsigned DefaultIndex = -1U; 1445 for (unsigned i = 0; i < NumAssocs; ++i) { 1446 if (!Types[i]) 1447 DefaultIndex = i; 1448 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1449 Types[i]->getType())) 1450 CompatIndices.push_back(i); 1451 } 1452 1453 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1454 // type compatible with at most one of the types named in its generic 1455 // association list." 1456 if (CompatIndices.size() > 1) { 1457 // We strip parens here because the controlling expression is typically 1458 // parenthesized in macro definitions. 1459 ControllingExpr = ControllingExpr->IgnoreParens(); 1460 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1461 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1462 << (unsigned) CompatIndices.size(); 1463 for (unsigned I : CompatIndices) { 1464 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1465 diag::note_compat_assoc) 1466 << Types[I]->getTypeLoc().getSourceRange() 1467 << Types[I]->getType(); 1468 } 1469 return ExprError(); 1470 } 1471 1472 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1473 // its controlling expression shall have type compatible with exactly one of 1474 // the types named in its generic association list." 1475 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1476 // We strip parens here because the controlling expression is typically 1477 // parenthesized in macro definitions. 1478 ControllingExpr = ControllingExpr->IgnoreParens(); 1479 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1480 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1481 return ExprError(); 1482 } 1483 1484 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1485 // type name that is compatible with the type of the controlling expression, 1486 // then the result expression of the generic selection is the expression 1487 // in that generic association. Otherwise, the result expression of the 1488 // generic selection is the expression in the default generic association." 1489 unsigned ResultIndex = 1490 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1491 1492 return new (Context) GenericSelectionExpr( 1493 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1494 ContainsUnexpandedParameterPack, ResultIndex); 1495 } 1496 1497 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1498 /// location of the token and the offset of the ud-suffix within it. 1499 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1500 unsigned Offset) { 1501 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1502 S.getLangOpts()); 1503 } 1504 1505 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1506 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1507 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1508 IdentifierInfo *UDSuffix, 1509 SourceLocation UDSuffixLoc, 1510 ArrayRef<Expr*> Args, 1511 SourceLocation LitEndLoc) { 1512 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1513 1514 QualType ArgTy[2]; 1515 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1516 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1517 if (ArgTy[ArgIdx]->isArrayType()) 1518 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1519 } 1520 1521 DeclarationName OpName = 1522 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1523 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1524 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1525 1526 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1527 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1528 /*AllowRaw*/false, /*AllowTemplate*/false, 1529 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1530 return ExprError(); 1531 1532 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1533 } 1534 1535 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1536 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1537 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1538 /// multiple tokens. However, the common case is that StringToks points to one 1539 /// string. 1540 /// 1541 ExprResult 1542 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1543 assert(!StringToks.empty() && "Must have at least one string!"); 1544 1545 StringLiteralParser Literal(StringToks, PP); 1546 if (Literal.hadError) 1547 return ExprError(); 1548 1549 SmallVector<SourceLocation, 4> StringTokLocs; 1550 for (const Token &Tok : StringToks) 1551 StringTokLocs.push_back(Tok.getLocation()); 1552 1553 QualType CharTy = Context.CharTy; 1554 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1555 if (Literal.isWide()) { 1556 CharTy = Context.getWideCharType(); 1557 Kind = StringLiteral::Wide; 1558 } else if (Literal.isUTF8()) { 1559 Kind = StringLiteral::UTF8; 1560 } else if (Literal.isUTF16()) { 1561 CharTy = Context.Char16Ty; 1562 Kind = StringLiteral::UTF16; 1563 } else if (Literal.isUTF32()) { 1564 CharTy = Context.Char32Ty; 1565 Kind = StringLiteral::UTF32; 1566 } else if (Literal.isPascal()) { 1567 CharTy = Context.UnsignedCharTy; 1568 } 1569 1570 QualType CharTyConst = CharTy; 1571 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1572 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1573 CharTyConst.addConst(); 1574 1575 // Get an array type for the string, according to C99 6.4.5. This includes 1576 // the nul terminator character as well as the string length for pascal 1577 // strings. 1578 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1579 llvm::APInt(32, Literal.GetNumStringChars()+1), 1580 ArrayType::Normal, 0); 1581 1582 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1583 if (getLangOpts().OpenCL) { 1584 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1585 } 1586 1587 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1588 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1589 Kind, Literal.Pascal, StrTy, 1590 &StringTokLocs[0], 1591 StringTokLocs.size()); 1592 if (Literal.getUDSuffix().empty()) 1593 return Lit; 1594 1595 // We're building a user-defined literal. 1596 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1597 SourceLocation UDSuffixLoc = 1598 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1599 Literal.getUDSuffixOffset()); 1600 1601 // Make sure we're allowed user-defined literals here. 1602 if (!UDLScope) 1603 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1604 1605 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1606 // operator "" X (str, len) 1607 QualType SizeType = Context.getSizeType(); 1608 1609 DeclarationName OpName = 1610 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1611 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1612 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1613 1614 QualType ArgTy[] = { 1615 Context.getArrayDecayedType(StrTy), SizeType 1616 }; 1617 1618 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1619 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1620 /*AllowRaw*/false, /*AllowTemplate*/false, 1621 /*AllowStringTemplate*/true)) { 1622 1623 case LOLR_Cooked: { 1624 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1625 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1626 StringTokLocs[0]); 1627 Expr *Args[] = { Lit, LenArg }; 1628 1629 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1630 } 1631 1632 case LOLR_StringTemplate: { 1633 TemplateArgumentListInfo ExplicitArgs; 1634 1635 unsigned CharBits = Context.getIntWidth(CharTy); 1636 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1637 llvm::APSInt Value(CharBits, CharIsUnsigned); 1638 1639 TemplateArgument TypeArg(CharTy); 1640 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1641 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1642 1643 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1644 Value = Lit->getCodeUnit(I); 1645 TemplateArgument Arg(Context, Value, CharTy); 1646 TemplateArgumentLocInfo ArgInfo; 1647 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1648 } 1649 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1650 &ExplicitArgs); 1651 } 1652 case LOLR_Raw: 1653 case LOLR_Template: 1654 llvm_unreachable("unexpected literal operator lookup result"); 1655 case LOLR_Error: 1656 return ExprError(); 1657 } 1658 llvm_unreachable("unexpected literal operator lookup result"); 1659 } 1660 1661 ExprResult 1662 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1663 SourceLocation Loc, 1664 const CXXScopeSpec *SS) { 1665 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1666 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1667 } 1668 1669 /// BuildDeclRefExpr - Build an expression that references a 1670 /// declaration that does not require a closure capture. 1671 ExprResult 1672 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1673 const DeclarationNameInfo &NameInfo, 1674 const CXXScopeSpec *SS, NamedDecl *FoundD, 1675 const TemplateArgumentListInfo *TemplateArgs) { 1676 if (getLangOpts().CUDA) 1677 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1678 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1679 if (CheckCUDATarget(Caller, Callee)) { 1680 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1681 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1682 << IdentifyCUDATarget(Caller); 1683 Diag(D->getLocation(), diag::note_previous_decl) 1684 << D->getIdentifier(); 1685 return ExprError(); 1686 } 1687 } 1688 1689 bool RefersToCapturedVariable = 1690 isa<VarDecl>(D) && 1691 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1692 1693 DeclRefExpr *E; 1694 if (isa<VarTemplateSpecializationDecl>(D)) { 1695 VarTemplateSpecializationDecl *VarSpec = 1696 cast<VarTemplateSpecializationDecl>(D); 1697 1698 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1699 : NestedNameSpecifierLoc(), 1700 VarSpec->getTemplateKeywordLoc(), D, 1701 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1702 FoundD, TemplateArgs); 1703 } else { 1704 assert(!TemplateArgs && "No template arguments for non-variable" 1705 " template specialization references"); 1706 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1707 : NestedNameSpecifierLoc(), 1708 SourceLocation(), D, RefersToCapturedVariable, 1709 NameInfo, Ty, VK, FoundD); 1710 } 1711 1712 MarkDeclRefReferenced(E); 1713 1714 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1715 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1716 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1717 recordUseOfEvaluatedWeak(E); 1718 1719 // Just in case we're building an illegal pointer-to-member. 1720 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1721 if (FD && FD->isBitField()) 1722 E->setObjectKind(OK_BitField); 1723 1724 return E; 1725 } 1726 1727 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1728 /// possibly a list of template arguments. 1729 /// 1730 /// If this produces template arguments, it is permitted to call 1731 /// DecomposeTemplateName. 1732 /// 1733 /// This actually loses a lot of source location information for 1734 /// non-standard name kinds; we should consider preserving that in 1735 /// some way. 1736 void 1737 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1738 TemplateArgumentListInfo &Buffer, 1739 DeclarationNameInfo &NameInfo, 1740 const TemplateArgumentListInfo *&TemplateArgs) { 1741 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1742 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1743 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1744 1745 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1746 Id.TemplateId->NumArgs); 1747 translateTemplateArguments(TemplateArgsPtr, Buffer); 1748 1749 TemplateName TName = Id.TemplateId->Template.get(); 1750 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1751 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1752 TemplateArgs = &Buffer; 1753 } else { 1754 NameInfo = GetNameFromUnqualifiedId(Id); 1755 TemplateArgs = nullptr; 1756 } 1757 } 1758 1759 static void emitEmptyLookupTypoDiagnostic( 1760 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1761 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1762 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1763 DeclContext *Ctx = 1764 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1765 if (!TC) { 1766 // Emit a special diagnostic for failed member lookups. 1767 // FIXME: computing the declaration context might fail here (?) 1768 if (Ctx) 1769 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1770 << SS.getRange(); 1771 else 1772 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1773 return; 1774 } 1775 1776 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1777 bool DroppedSpecifier = 1778 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1779 unsigned NoteID = 1780 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl())) 1781 ? diag::note_implicit_param_decl 1782 : diag::note_previous_decl; 1783 if (!Ctx) 1784 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1785 SemaRef.PDiag(NoteID)); 1786 else 1787 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1788 << Typo << Ctx << DroppedSpecifier 1789 << SS.getRange(), 1790 SemaRef.PDiag(NoteID)); 1791 } 1792 1793 /// Diagnose an empty lookup. 1794 /// 1795 /// \return false if new lookup candidates were found 1796 bool 1797 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1798 std::unique_ptr<CorrectionCandidateCallback> CCC, 1799 TemplateArgumentListInfo *ExplicitTemplateArgs, 1800 ArrayRef<Expr *> Args, TypoExpr **Out) { 1801 DeclarationName Name = R.getLookupName(); 1802 1803 unsigned diagnostic = diag::err_undeclared_var_use; 1804 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1805 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1806 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1807 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1808 diagnostic = diag::err_undeclared_use; 1809 diagnostic_suggest = diag::err_undeclared_use_suggest; 1810 } 1811 1812 // If the original lookup was an unqualified lookup, fake an 1813 // unqualified lookup. This is useful when (for example) the 1814 // original lookup would not have found something because it was a 1815 // dependent name. 1816 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1817 while (DC) { 1818 if (isa<CXXRecordDecl>(DC)) { 1819 LookupQualifiedName(R, DC); 1820 1821 if (!R.empty()) { 1822 // Don't give errors about ambiguities in this lookup. 1823 R.suppressDiagnostics(); 1824 1825 // During a default argument instantiation the CurContext points 1826 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1827 // function parameter list, hence add an explicit check. 1828 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1829 ActiveTemplateInstantiations.back().Kind == 1830 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1831 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1832 bool isInstance = CurMethod && 1833 CurMethod->isInstance() && 1834 DC == CurMethod->getParent() && !isDefaultArgument; 1835 1836 // Give a code modification hint to insert 'this->'. 1837 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1838 // Actually quite difficult! 1839 if (getLangOpts().MSVCCompat) 1840 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1841 if (isInstance) { 1842 Diag(R.getNameLoc(), diagnostic) << Name 1843 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1844 CheckCXXThisCapture(R.getNameLoc()); 1845 } else { 1846 Diag(R.getNameLoc(), diagnostic) << Name; 1847 } 1848 1849 // Do we really want to note all of these? 1850 for (NamedDecl *D : R) 1851 Diag(D->getLocation(), diag::note_dependent_var_use); 1852 1853 // Return true if we are inside a default argument instantiation 1854 // and the found name refers to an instance member function, otherwise 1855 // the function calling DiagnoseEmptyLookup will try to create an 1856 // implicit member call and this is wrong for default argument. 1857 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1858 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1859 return true; 1860 } 1861 1862 // Tell the callee to try to recover. 1863 return false; 1864 } 1865 1866 R.clear(); 1867 } 1868 1869 // In Microsoft mode, if we are performing lookup from within a friend 1870 // function definition declared at class scope then we must set 1871 // DC to the lexical parent to be able to search into the parent 1872 // class. 1873 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1874 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1875 DC->getLexicalParent()->isRecord()) 1876 DC = DC->getLexicalParent(); 1877 else 1878 DC = DC->getParent(); 1879 } 1880 1881 // We didn't find anything, so try to correct for a typo. 1882 TypoCorrection Corrected; 1883 if (S && Out) { 1884 SourceLocation TypoLoc = R.getNameLoc(); 1885 assert(!ExplicitTemplateArgs && 1886 "Diagnosing an empty lookup with explicit template args!"); 1887 *Out = CorrectTypoDelayed( 1888 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1889 [=](const TypoCorrection &TC) { 1890 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1891 diagnostic, diagnostic_suggest); 1892 }, 1893 nullptr, CTK_ErrorRecovery); 1894 if (*Out) 1895 return true; 1896 } else if (S && (Corrected = 1897 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1898 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1899 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1900 bool DroppedSpecifier = 1901 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1902 R.setLookupName(Corrected.getCorrection()); 1903 1904 bool AcceptableWithRecovery = false; 1905 bool AcceptableWithoutRecovery = false; 1906 NamedDecl *ND = Corrected.getCorrectionDecl(); 1907 if (ND) { 1908 if (Corrected.isOverloaded()) { 1909 OverloadCandidateSet OCS(R.getNameLoc(), 1910 OverloadCandidateSet::CSK_Normal); 1911 OverloadCandidateSet::iterator Best; 1912 for (NamedDecl *CD : Corrected) { 1913 if (FunctionTemplateDecl *FTD = 1914 dyn_cast<FunctionTemplateDecl>(CD)) 1915 AddTemplateOverloadCandidate( 1916 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1917 Args, OCS); 1918 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1919 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1920 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1921 Args, OCS); 1922 } 1923 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1924 case OR_Success: 1925 ND = Best->Function; 1926 Corrected.setCorrectionDecl(ND); 1927 break; 1928 default: 1929 // FIXME: Arbitrarily pick the first declaration for the note. 1930 Corrected.setCorrectionDecl(ND); 1931 break; 1932 } 1933 } 1934 R.addDecl(ND); 1935 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1936 CXXRecordDecl *Record = nullptr; 1937 if (Corrected.getCorrectionSpecifier()) { 1938 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1939 Record = Ty->getAsCXXRecordDecl(); 1940 } 1941 if (!Record) 1942 Record = cast<CXXRecordDecl>( 1943 ND->getDeclContext()->getRedeclContext()); 1944 R.setNamingClass(Record); 1945 } 1946 1947 AcceptableWithRecovery = 1948 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1949 // FIXME: If we ended up with a typo for a type name or 1950 // Objective-C class name, we're in trouble because the parser 1951 // is in the wrong place to recover. Suggest the typo 1952 // correction, but don't make it a fix-it since we're not going 1953 // to recover well anyway. 1954 AcceptableWithoutRecovery = 1955 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1956 } else { 1957 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1958 // because we aren't able to recover. 1959 AcceptableWithoutRecovery = true; 1960 } 1961 1962 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1963 unsigned NoteID = (Corrected.getCorrectionDecl() && 1964 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1965 ? diag::note_implicit_param_decl 1966 : diag::note_previous_decl; 1967 if (SS.isEmpty()) 1968 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1969 PDiag(NoteID), AcceptableWithRecovery); 1970 else 1971 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1972 << Name << computeDeclContext(SS, false) 1973 << DroppedSpecifier << SS.getRange(), 1974 PDiag(NoteID), AcceptableWithRecovery); 1975 1976 // Tell the callee whether to try to recover. 1977 return !AcceptableWithRecovery; 1978 } 1979 } 1980 R.clear(); 1981 1982 // Emit a special diagnostic for failed member lookups. 1983 // FIXME: computing the declaration context might fail here (?) 1984 if (!SS.isEmpty()) { 1985 Diag(R.getNameLoc(), diag::err_no_member) 1986 << Name << computeDeclContext(SS, false) 1987 << SS.getRange(); 1988 return true; 1989 } 1990 1991 // Give up, we can't recover. 1992 Diag(R.getNameLoc(), diagnostic) << Name; 1993 return true; 1994 } 1995 1996 /// In Microsoft mode, if we are inside a template class whose parent class has 1997 /// dependent base classes, and we can't resolve an unqualified identifier, then 1998 /// assume the identifier is a member of a dependent base class. We can only 1999 /// recover successfully in static methods, instance methods, and other contexts 2000 /// where 'this' is available. This doesn't precisely match MSVC's 2001 /// instantiation model, but it's close enough. 2002 static Expr * 2003 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2004 DeclarationNameInfo &NameInfo, 2005 SourceLocation TemplateKWLoc, 2006 const TemplateArgumentListInfo *TemplateArgs) { 2007 // Only try to recover from lookup into dependent bases in static methods or 2008 // contexts where 'this' is available. 2009 QualType ThisType = S.getCurrentThisType(); 2010 const CXXRecordDecl *RD = nullptr; 2011 if (!ThisType.isNull()) 2012 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2013 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2014 RD = MD->getParent(); 2015 if (!RD || !RD->hasAnyDependentBases()) 2016 return nullptr; 2017 2018 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2019 // is available, suggest inserting 'this->' as a fixit. 2020 SourceLocation Loc = NameInfo.getLoc(); 2021 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2022 DB << NameInfo.getName() << RD; 2023 2024 if (!ThisType.isNull()) { 2025 DB << FixItHint::CreateInsertion(Loc, "this->"); 2026 return CXXDependentScopeMemberExpr::Create( 2027 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2028 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2029 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2030 } 2031 2032 // Synthesize a fake NNS that points to the derived class. This will 2033 // perform name lookup during template instantiation. 2034 CXXScopeSpec SS; 2035 auto *NNS = 2036 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2037 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2038 return DependentScopeDeclRefExpr::Create( 2039 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2040 TemplateArgs); 2041 } 2042 2043 ExprResult 2044 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2045 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2046 bool HasTrailingLParen, bool IsAddressOfOperand, 2047 std::unique_ptr<CorrectionCandidateCallback> CCC, 2048 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2049 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2050 "cannot be direct & operand and have a trailing lparen"); 2051 if (SS.isInvalid()) 2052 return ExprError(); 2053 2054 TemplateArgumentListInfo TemplateArgsBuffer; 2055 2056 // Decompose the UnqualifiedId into the following data. 2057 DeclarationNameInfo NameInfo; 2058 const TemplateArgumentListInfo *TemplateArgs; 2059 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2060 2061 DeclarationName Name = NameInfo.getName(); 2062 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2063 SourceLocation NameLoc = NameInfo.getLoc(); 2064 2065 // C++ [temp.dep.expr]p3: 2066 // An id-expression is type-dependent if it contains: 2067 // -- an identifier that was declared with a dependent type, 2068 // (note: handled after lookup) 2069 // -- a template-id that is dependent, 2070 // (note: handled in BuildTemplateIdExpr) 2071 // -- a conversion-function-id that specifies a dependent type, 2072 // -- a nested-name-specifier that contains a class-name that 2073 // names a dependent type. 2074 // Determine whether this is a member of an unknown specialization; 2075 // we need to handle these differently. 2076 bool DependentID = false; 2077 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2078 Name.getCXXNameType()->isDependentType()) { 2079 DependentID = true; 2080 } else if (SS.isSet()) { 2081 if (DeclContext *DC = computeDeclContext(SS, false)) { 2082 if (RequireCompleteDeclContext(SS, DC)) 2083 return ExprError(); 2084 } else { 2085 DependentID = true; 2086 } 2087 } 2088 2089 if (DependentID) 2090 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2091 IsAddressOfOperand, TemplateArgs); 2092 2093 // Perform the required lookup. 2094 LookupResult R(*this, NameInfo, 2095 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2096 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2097 if (TemplateArgs) { 2098 // Lookup the template name again to correctly establish the context in 2099 // which it was found. This is really unfortunate as we already did the 2100 // lookup to determine that it was a template name in the first place. If 2101 // this becomes a performance hit, we can work harder to preserve those 2102 // results until we get here but it's likely not worth it. 2103 bool MemberOfUnknownSpecialization; 2104 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2105 MemberOfUnknownSpecialization); 2106 2107 if (MemberOfUnknownSpecialization || 2108 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2109 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2110 IsAddressOfOperand, TemplateArgs); 2111 } else { 2112 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2113 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2114 2115 // If the result might be in a dependent base class, this is a dependent 2116 // id-expression. 2117 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2118 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2119 IsAddressOfOperand, TemplateArgs); 2120 2121 // If this reference is in an Objective-C method, then we need to do 2122 // some special Objective-C lookup, too. 2123 if (IvarLookupFollowUp) { 2124 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2125 if (E.isInvalid()) 2126 return ExprError(); 2127 2128 if (Expr *Ex = E.getAs<Expr>()) 2129 return Ex; 2130 } 2131 } 2132 2133 if (R.isAmbiguous()) 2134 return ExprError(); 2135 2136 // This could be an implicitly declared function reference (legal in C90, 2137 // extension in C99, forbidden in C++). 2138 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2139 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2140 if (D) R.addDecl(D); 2141 } 2142 2143 // Determine whether this name might be a candidate for 2144 // argument-dependent lookup. 2145 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2146 2147 if (R.empty() && !ADL) { 2148 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2149 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2150 TemplateKWLoc, TemplateArgs)) 2151 return E; 2152 } 2153 2154 // Don't diagnose an empty lookup for inline assembly. 2155 if (IsInlineAsmIdentifier) 2156 return ExprError(); 2157 2158 // If this name wasn't predeclared and if this is not a function 2159 // call, diagnose the problem. 2160 TypoExpr *TE = nullptr; 2161 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2162 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2163 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2164 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2165 "Typo correction callback misconfigured"); 2166 if (CCC) { 2167 // Make sure the callback knows what the typo being diagnosed is. 2168 CCC->setTypoName(II); 2169 if (SS.isValid()) 2170 CCC->setTypoNNS(SS.getScopeRep()); 2171 } 2172 if (DiagnoseEmptyLookup(S, SS, R, 2173 CCC ? std::move(CCC) : std::move(DefaultValidator), 2174 nullptr, None, &TE)) { 2175 if (TE && KeywordReplacement) { 2176 auto &State = getTypoExprState(TE); 2177 auto BestTC = State.Consumer->getNextCorrection(); 2178 if (BestTC.isKeyword()) { 2179 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2180 if (State.DiagHandler) 2181 State.DiagHandler(BestTC); 2182 KeywordReplacement->startToken(); 2183 KeywordReplacement->setKind(II->getTokenID()); 2184 KeywordReplacement->setIdentifierInfo(II); 2185 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2186 // Clean up the state associated with the TypoExpr, since it has 2187 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2188 clearDelayedTypo(TE); 2189 // Signal that a correction to a keyword was performed by returning a 2190 // valid-but-null ExprResult. 2191 return (Expr*)nullptr; 2192 } 2193 State.Consumer->resetCorrectionStream(); 2194 } 2195 return TE ? TE : ExprError(); 2196 } 2197 2198 assert(!R.empty() && 2199 "DiagnoseEmptyLookup returned false but added no results"); 2200 2201 // If we found an Objective-C instance variable, let 2202 // LookupInObjCMethod build the appropriate expression to 2203 // reference the ivar. 2204 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2205 R.clear(); 2206 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2207 // In a hopelessly buggy code, Objective-C instance variable 2208 // lookup fails and no expression will be built to reference it. 2209 if (!E.isInvalid() && !E.get()) 2210 return ExprError(); 2211 return E; 2212 } 2213 } 2214 2215 // This is guaranteed from this point on. 2216 assert(!R.empty() || ADL); 2217 2218 // Check whether this might be a C++ implicit instance member access. 2219 // C++ [class.mfct.non-static]p3: 2220 // When an id-expression that is not part of a class member access 2221 // syntax and not used to form a pointer to member is used in the 2222 // body of a non-static member function of class X, if name lookup 2223 // resolves the name in the id-expression to a non-static non-type 2224 // member of some class C, the id-expression is transformed into a 2225 // class member access expression using (*this) as the 2226 // postfix-expression to the left of the . operator. 2227 // 2228 // But we don't actually need to do this for '&' operands if R 2229 // resolved to a function or overloaded function set, because the 2230 // expression is ill-formed if it actually works out to be a 2231 // non-static member function: 2232 // 2233 // C++ [expr.ref]p4: 2234 // Otherwise, if E1.E2 refers to a non-static member function. . . 2235 // [t]he expression can be used only as the left-hand operand of a 2236 // member function call. 2237 // 2238 // There are other safeguards against such uses, but it's important 2239 // to get this right here so that we don't end up making a 2240 // spuriously dependent expression if we're inside a dependent 2241 // instance method. 2242 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2243 bool MightBeImplicitMember; 2244 if (!IsAddressOfOperand) 2245 MightBeImplicitMember = true; 2246 else if (!SS.isEmpty()) 2247 MightBeImplicitMember = false; 2248 else if (R.isOverloadedResult()) 2249 MightBeImplicitMember = false; 2250 else if (R.isUnresolvableResult()) 2251 MightBeImplicitMember = true; 2252 else 2253 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2254 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2255 isa<MSPropertyDecl>(R.getFoundDecl()); 2256 2257 if (MightBeImplicitMember) 2258 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2259 R, TemplateArgs, S); 2260 } 2261 2262 if (TemplateArgs || TemplateKWLoc.isValid()) { 2263 2264 // In C++1y, if this is a variable template id, then check it 2265 // in BuildTemplateIdExpr(). 2266 // The single lookup result must be a variable template declaration. 2267 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2268 Id.TemplateId->Kind == TNK_Var_template) { 2269 assert(R.getAsSingle<VarTemplateDecl>() && 2270 "There should only be one declaration found."); 2271 } 2272 2273 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2274 } 2275 2276 return BuildDeclarationNameExpr(SS, R, ADL); 2277 } 2278 2279 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2280 /// declaration name, generally during template instantiation. 2281 /// There's a large number of things which don't need to be done along 2282 /// this path. 2283 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2284 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2285 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2286 DeclContext *DC = computeDeclContext(SS, false); 2287 if (!DC) 2288 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2289 NameInfo, /*TemplateArgs=*/nullptr); 2290 2291 if (RequireCompleteDeclContext(SS, DC)) 2292 return ExprError(); 2293 2294 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2295 LookupQualifiedName(R, DC); 2296 2297 if (R.isAmbiguous()) 2298 return ExprError(); 2299 2300 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2301 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2302 NameInfo, /*TemplateArgs=*/nullptr); 2303 2304 if (R.empty()) { 2305 Diag(NameInfo.getLoc(), diag::err_no_member) 2306 << NameInfo.getName() << DC << SS.getRange(); 2307 return ExprError(); 2308 } 2309 2310 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2311 // Diagnose a missing typename if this resolved unambiguously to a type in 2312 // a dependent context. If we can recover with a type, downgrade this to 2313 // a warning in Microsoft compatibility mode. 2314 unsigned DiagID = diag::err_typename_missing; 2315 if (RecoveryTSI && getLangOpts().MSVCCompat) 2316 DiagID = diag::ext_typename_missing; 2317 SourceLocation Loc = SS.getBeginLoc(); 2318 auto D = Diag(Loc, DiagID); 2319 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2320 << SourceRange(Loc, NameInfo.getEndLoc()); 2321 2322 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2323 // context. 2324 if (!RecoveryTSI) 2325 return ExprError(); 2326 2327 // Only issue the fixit if we're prepared to recover. 2328 D << FixItHint::CreateInsertion(Loc, "typename "); 2329 2330 // Recover by pretending this was an elaborated type. 2331 QualType Ty = Context.getTypeDeclType(TD); 2332 TypeLocBuilder TLB; 2333 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2334 2335 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2336 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2337 QTL.setElaboratedKeywordLoc(SourceLocation()); 2338 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2339 2340 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2341 2342 return ExprEmpty(); 2343 } 2344 2345 // Defend against this resolving to an implicit member access. We usually 2346 // won't get here if this might be a legitimate a class member (we end up in 2347 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2348 // a pointer-to-member or in an unevaluated context in C++11. 2349 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2350 return BuildPossibleImplicitMemberExpr(SS, 2351 /*TemplateKWLoc=*/SourceLocation(), 2352 R, /*TemplateArgs=*/nullptr, S); 2353 2354 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2355 } 2356 2357 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2358 /// detected that we're currently inside an ObjC method. Perform some 2359 /// additional lookup. 2360 /// 2361 /// Ideally, most of this would be done by lookup, but there's 2362 /// actually quite a lot of extra work involved. 2363 /// 2364 /// Returns a null sentinel to indicate trivial success. 2365 ExprResult 2366 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2367 IdentifierInfo *II, bool AllowBuiltinCreation) { 2368 SourceLocation Loc = Lookup.getNameLoc(); 2369 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2370 2371 // Check for error condition which is already reported. 2372 if (!CurMethod) 2373 return ExprError(); 2374 2375 // There are two cases to handle here. 1) scoped lookup could have failed, 2376 // in which case we should look for an ivar. 2) scoped lookup could have 2377 // found a decl, but that decl is outside the current instance method (i.e. 2378 // a global variable). In these two cases, we do a lookup for an ivar with 2379 // this name, if the lookup sucedes, we replace it our current decl. 2380 2381 // If we're in a class method, we don't normally want to look for 2382 // ivars. But if we don't find anything else, and there's an 2383 // ivar, that's an error. 2384 bool IsClassMethod = CurMethod->isClassMethod(); 2385 2386 bool LookForIvars; 2387 if (Lookup.empty()) 2388 LookForIvars = true; 2389 else if (IsClassMethod) 2390 LookForIvars = false; 2391 else 2392 LookForIvars = (Lookup.isSingleResult() && 2393 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2394 ObjCInterfaceDecl *IFace = nullptr; 2395 if (LookForIvars) { 2396 IFace = CurMethod->getClassInterface(); 2397 ObjCInterfaceDecl *ClassDeclared; 2398 ObjCIvarDecl *IV = nullptr; 2399 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2400 // Diagnose using an ivar in a class method. 2401 if (IsClassMethod) 2402 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2403 << IV->getDeclName()); 2404 2405 // If we're referencing an invalid decl, just return this as a silent 2406 // error node. The error diagnostic was already emitted on the decl. 2407 if (IV->isInvalidDecl()) 2408 return ExprError(); 2409 2410 // Check if referencing a field with __attribute__((deprecated)). 2411 if (DiagnoseUseOfDecl(IV, Loc)) 2412 return ExprError(); 2413 2414 // Diagnose the use of an ivar outside of the declaring class. 2415 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2416 !declaresSameEntity(ClassDeclared, IFace) && 2417 !getLangOpts().DebuggerSupport) 2418 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2419 2420 // FIXME: This should use a new expr for a direct reference, don't 2421 // turn this into Self->ivar, just return a BareIVarExpr or something. 2422 IdentifierInfo &II = Context.Idents.get("self"); 2423 UnqualifiedId SelfName; 2424 SelfName.setIdentifier(&II, SourceLocation()); 2425 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2426 CXXScopeSpec SelfScopeSpec; 2427 SourceLocation TemplateKWLoc; 2428 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2429 SelfName, false, false); 2430 if (SelfExpr.isInvalid()) 2431 return ExprError(); 2432 2433 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2434 if (SelfExpr.isInvalid()) 2435 return ExprError(); 2436 2437 MarkAnyDeclReferenced(Loc, IV, true); 2438 2439 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2440 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2441 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2442 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2443 2444 ObjCIvarRefExpr *Result = new (Context) 2445 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2446 IV->getLocation(), SelfExpr.get(), true, true); 2447 2448 if (getLangOpts().ObjCAutoRefCount) { 2449 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2450 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2451 recordUseOfEvaluatedWeak(Result); 2452 } 2453 if (CurContext->isClosure()) 2454 Diag(Loc, diag::warn_implicitly_retains_self) 2455 << FixItHint::CreateInsertion(Loc, "self->"); 2456 } 2457 2458 return Result; 2459 } 2460 } else if (CurMethod->isInstanceMethod()) { 2461 // We should warn if a local variable hides an ivar. 2462 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2463 ObjCInterfaceDecl *ClassDeclared; 2464 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2465 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2466 declaresSameEntity(IFace, ClassDeclared)) 2467 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2468 } 2469 } 2470 } else if (Lookup.isSingleResult() && 2471 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2472 // If accessing a stand-alone ivar in a class method, this is an error. 2473 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2474 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2475 << IV->getDeclName()); 2476 } 2477 2478 if (Lookup.empty() && II && AllowBuiltinCreation) { 2479 // FIXME. Consolidate this with similar code in LookupName. 2480 if (unsigned BuiltinID = II->getBuiltinID()) { 2481 if (!(getLangOpts().CPlusPlus && 2482 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2483 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2484 S, Lookup.isForRedeclaration(), 2485 Lookup.getNameLoc()); 2486 if (D) Lookup.addDecl(D); 2487 } 2488 } 2489 } 2490 // Sentinel value saying that we didn't do anything special. 2491 return ExprResult((Expr *)nullptr); 2492 } 2493 2494 /// \brief Cast a base object to a member's actual type. 2495 /// 2496 /// Logically this happens in three phases: 2497 /// 2498 /// * First we cast from the base type to the naming class. 2499 /// The naming class is the class into which we were looking 2500 /// when we found the member; it's the qualifier type if a 2501 /// qualifier was provided, and otherwise it's the base type. 2502 /// 2503 /// * Next we cast from the naming class to the declaring class. 2504 /// If the member we found was brought into a class's scope by 2505 /// a using declaration, this is that class; otherwise it's 2506 /// the class declaring the member. 2507 /// 2508 /// * Finally we cast from the declaring class to the "true" 2509 /// declaring class of the member. This conversion does not 2510 /// obey access control. 2511 ExprResult 2512 Sema::PerformObjectMemberConversion(Expr *From, 2513 NestedNameSpecifier *Qualifier, 2514 NamedDecl *FoundDecl, 2515 NamedDecl *Member) { 2516 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2517 if (!RD) 2518 return From; 2519 2520 QualType DestRecordType; 2521 QualType DestType; 2522 QualType FromRecordType; 2523 QualType FromType = From->getType(); 2524 bool PointerConversions = false; 2525 if (isa<FieldDecl>(Member)) { 2526 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2527 2528 if (FromType->getAs<PointerType>()) { 2529 DestType = Context.getPointerType(DestRecordType); 2530 FromRecordType = FromType->getPointeeType(); 2531 PointerConversions = true; 2532 } else { 2533 DestType = DestRecordType; 2534 FromRecordType = FromType; 2535 } 2536 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2537 if (Method->isStatic()) 2538 return From; 2539 2540 DestType = Method->getThisType(Context); 2541 DestRecordType = DestType->getPointeeType(); 2542 2543 if (FromType->getAs<PointerType>()) { 2544 FromRecordType = FromType->getPointeeType(); 2545 PointerConversions = true; 2546 } else { 2547 FromRecordType = FromType; 2548 DestType = DestRecordType; 2549 } 2550 } else { 2551 // No conversion necessary. 2552 return From; 2553 } 2554 2555 if (DestType->isDependentType() || FromType->isDependentType()) 2556 return From; 2557 2558 // If the unqualified types are the same, no conversion is necessary. 2559 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2560 return From; 2561 2562 SourceRange FromRange = From->getSourceRange(); 2563 SourceLocation FromLoc = FromRange.getBegin(); 2564 2565 ExprValueKind VK = From->getValueKind(); 2566 2567 // C++ [class.member.lookup]p8: 2568 // [...] Ambiguities can often be resolved by qualifying a name with its 2569 // class name. 2570 // 2571 // If the member was a qualified name and the qualified referred to a 2572 // specific base subobject type, we'll cast to that intermediate type 2573 // first and then to the object in which the member is declared. That allows 2574 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2575 // 2576 // class Base { public: int x; }; 2577 // class Derived1 : public Base { }; 2578 // class Derived2 : public Base { }; 2579 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2580 // 2581 // void VeryDerived::f() { 2582 // x = 17; // error: ambiguous base subobjects 2583 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2584 // } 2585 if (Qualifier && Qualifier->getAsType()) { 2586 QualType QType = QualType(Qualifier->getAsType(), 0); 2587 assert(QType->isRecordType() && "lookup done with non-record type"); 2588 2589 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2590 2591 // In C++98, the qualifier type doesn't actually have to be a base 2592 // type of the object type, in which case we just ignore it. 2593 // Otherwise build the appropriate casts. 2594 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2595 CXXCastPath BasePath; 2596 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2597 FromLoc, FromRange, &BasePath)) 2598 return ExprError(); 2599 2600 if (PointerConversions) 2601 QType = Context.getPointerType(QType); 2602 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2603 VK, &BasePath).get(); 2604 2605 FromType = QType; 2606 FromRecordType = QRecordType; 2607 2608 // If the qualifier type was the same as the destination type, 2609 // we're done. 2610 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2611 return From; 2612 } 2613 } 2614 2615 bool IgnoreAccess = false; 2616 2617 // If we actually found the member through a using declaration, cast 2618 // down to the using declaration's type. 2619 // 2620 // Pointer equality is fine here because only one declaration of a 2621 // class ever has member declarations. 2622 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2623 assert(isa<UsingShadowDecl>(FoundDecl)); 2624 QualType URecordType = Context.getTypeDeclType( 2625 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2626 2627 // We only need to do this if the naming-class to declaring-class 2628 // conversion is non-trivial. 2629 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2630 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2631 CXXCastPath BasePath; 2632 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2633 FromLoc, FromRange, &BasePath)) 2634 return ExprError(); 2635 2636 QualType UType = URecordType; 2637 if (PointerConversions) 2638 UType = Context.getPointerType(UType); 2639 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2640 VK, &BasePath).get(); 2641 FromType = UType; 2642 FromRecordType = URecordType; 2643 } 2644 2645 // We don't do access control for the conversion from the 2646 // declaring class to the true declaring class. 2647 IgnoreAccess = true; 2648 } 2649 2650 CXXCastPath BasePath; 2651 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2652 FromLoc, FromRange, &BasePath, 2653 IgnoreAccess)) 2654 return ExprError(); 2655 2656 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2657 VK, &BasePath); 2658 } 2659 2660 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2661 const LookupResult &R, 2662 bool HasTrailingLParen) { 2663 // Only when used directly as the postfix-expression of a call. 2664 if (!HasTrailingLParen) 2665 return false; 2666 2667 // Never if a scope specifier was provided. 2668 if (SS.isSet()) 2669 return false; 2670 2671 // Only in C++ or ObjC++. 2672 if (!getLangOpts().CPlusPlus) 2673 return false; 2674 2675 // Turn off ADL when we find certain kinds of declarations during 2676 // normal lookup: 2677 for (NamedDecl *D : R) { 2678 // C++0x [basic.lookup.argdep]p3: 2679 // -- a declaration of a class member 2680 // Since using decls preserve this property, we check this on the 2681 // original decl. 2682 if (D->isCXXClassMember()) 2683 return false; 2684 2685 // C++0x [basic.lookup.argdep]p3: 2686 // -- a block-scope function declaration that is not a 2687 // using-declaration 2688 // NOTE: we also trigger this for function templates (in fact, we 2689 // don't check the decl type at all, since all other decl types 2690 // turn off ADL anyway). 2691 if (isa<UsingShadowDecl>(D)) 2692 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2693 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2694 return false; 2695 2696 // C++0x [basic.lookup.argdep]p3: 2697 // -- a declaration that is neither a function or a function 2698 // template 2699 // And also for builtin functions. 2700 if (isa<FunctionDecl>(D)) { 2701 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2702 2703 // But also builtin functions. 2704 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2705 return false; 2706 } else if (!isa<FunctionTemplateDecl>(D)) 2707 return false; 2708 } 2709 2710 return true; 2711 } 2712 2713 2714 /// Diagnoses obvious problems with the use of the given declaration 2715 /// as an expression. This is only actually called for lookups that 2716 /// were not overloaded, and it doesn't promise that the declaration 2717 /// will in fact be used. 2718 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2719 if (isa<TypedefNameDecl>(D)) { 2720 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2721 return true; 2722 } 2723 2724 if (isa<ObjCInterfaceDecl>(D)) { 2725 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2726 return true; 2727 } 2728 2729 if (isa<NamespaceDecl>(D)) { 2730 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2731 return true; 2732 } 2733 2734 return false; 2735 } 2736 2737 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2738 LookupResult &R, bool NeedsADL, 2739 bool AcceptInvalidDecl) { 2740 // If this is a single, fully-resolved result and we don't need ADL, 2741 // just build an ordinary singleton decl ref. 2742 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2743 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2744 R.getRepresentativeDecl(), nullptr, 2745 AcceptInvalidDecl); 2746 2747 // We only need to check the declaration if there's exactly one 2748 // result, because in the overloaded case the results can only be 2749 // functions and function templates. 2750 if (R.isSingleResult() && 2751 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2752 return ExprError(); 2753 2754 // Otherwise, just build an unresolved lookup expression. Suppress 2755 // any lookup-related diagnostics; we'll hash these out later, when 2756 // we've picked a target. 2757 R.suppressDiagnostics(); 2758 2759 UnresolvedLookupExpr *ULE 2760 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2761 SS.getWithLocInContext(Context), 2762 R.getLookupNameInfo(), 2763 NeedsADL, R.isOverloadedResult(), 2764 R.begin(), R.end()); 2765 2766 return ULE; 2767 } 2768 2769 /// \brief Complete semantic analysis for a reference to the given declaration. 2770 ExprResult Sema::BuildDeclarationNameExpr( 2771 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2772 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2773 bool AcceptInvalidDecl) { 2774 assert(D && "Cannot refer to a NULL declaration"); 2775 assert(!isa<FunctionTemplateDecl>(D) && 2776 "Cannot refer unambiguously to a function template"); 2777 2778 SourceLocation Loc = NameInfo.getLoc(); 2779 if (CheckDeclInExpr(*this, Loc, D)) 2780 return ExprError(); 2781 2782 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2783 // Specifically diagnose references to class templates that are missing 2784 // a template argument list. 2785 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2786 << Template << SS.getRange(); 2787 Diag(Template->getLocation(), diag::note_template_decl_here); 2788 return ExprError(); 2789 } 2790 2791 // Make sure that we're referring to a value. 2792 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2793 if (!VD) { 2794 Diag(Loc, diag::err_ref_non_value) 2795 << D << SS.getRange(); 2796 Diag(D->getLocation(), diag::note_declared_at); 2797 return ExprError(); 2798 } 2799 2800 // Check whether this declaration can be used. Note that we suppress 2801 // this check when we're going to perform argument-dependent lookup 2802 // on this function name, because this might not be the function 2803 // that overload resolution actually selects. 2804 if (DiagnoseUseOfDecl(VD, Loc)) 2805 return ExprError(); 2806 2807 // Only create DeclRefExpr's for valid Decl's. 2808 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2809 return ExprError(); 2810 2811 // Handle members of anonymous structs and unions. If we got here, 2812 // and the reference is to a class member indirect field, then this 2813 // must be the subject of a pointer-to-member expression. 2814 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2815 if (!indirectField->isCXXClassMember()) 2816 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2817 indirectField); 2818 2819 { 2820 QualType type = VD->getType(); 2821 ExprValueKind valueKind = VK_RValue; 2822 2823 switch (D->getKind()) { 2824 // Ignore all the non-ValueDecl kinds. 2825 #define ABSTRACT_DECL(kind) 2826 #define VALUE(type, base) 2827 #define DECL(type, base) \ 2828 case Decl::type: 2829 #include "clang/AST/DeclNodes.inc" 2830 llvm_unreachable("invalid value decl kind"); 2831 2832 // These shouldn't make it here. 2833 case Decl::ObjCAtDefsField: 2834 case Decl::ObjCIvar: 2835 llvm_unreachable("forming non-member reference to ivar?"); 2836 2837 // Enum constants are always r-values and never references. 2838 // Unresolved using declarations are dependent. 2839 case Decl::EnumConstant: 2840 case Decl::UnresolvedUsingValue: 2841 valueKind = VK_RValue; 2842 break; 2843 2844 // Fields and indirect fields that got here must be for 2845 // pointer-to-member expressions; we just call them l-values for 2846 // internal consistency, because this subexpression doesn't really 2847 // exist in the high-level semantics. 2848 case Decl::Field: 2849 case Decl::IndirectField: 2850 assert(getLangOpts().CPlusPlus && 2851 "building reference to field in C?"); 2852 2853 // These can't have reference type in well-formed programs, but 2854 // for internal consistency we do this anyway. 2855 type = type.getNonReferenceType(); 2856 valueKind = VK_LValue; 2857 break; 2858 2859 // Non-type template parameters are either l-values or r-values 2860 // depending on the type. 2861 case Decl::NonTypeTemplateParm: { 2862 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2863 type = reftype->getPointeeType(); 2864 valueKind = VK_LValue; // even if the parameter is an r-value reference 2865 break; 2866 } 2867 2868 // For non-references, we need to strip qualifiers just in case 2869 // the template parameter was declared as 'const int' or whatever. 2870 valueKind = VK_RValue; 2871 type = type.getUnqualifiedType(); 2872 break; 2873 } 2874 2875 case Decl::Var: 2876 case Decl::VarTemplateSpecialization: 2877 case Decl::VarTemplatePartialSpecialization: 2878 // In C, "extern void blah;" is valid and is an r-value. 2879 if (!getLangOpts().CPlusPlus && 2880 !type.hasQualifiers() && 2881 type->isVoidType()) { 2882 valueKind = VK_RValue; 2883 break; 2884 } 2885 // fallthrough 2886 2887 case Decl::ImplicitParam: 2888 case Decl::ParmVar: { 2889 // These are always l-values. 2890 valueKind = VK_LValue; 2891 type = type.getNonReferenceType(); 2892 2893 // FIXME: Does the addition of const really only apply in 2894 // potentially-evaluated contexts? Since the variable isn't actually 2895 // captured in an unevaluated context, it seems that the answer is no. 2896 if (!isUnevaluatedContext()) { 2897 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2898 if (!CapturedType.isNull()) 2899 type = CapturedType; 2900 } 2901 2902 break; 2903 } 2904 2905 case Decl::Function: { 2906 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2907 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2908 type = Context.BuiltinFnTy; 2909 valueKind = VK_RValue; 2910 break; 2911 } 2912 } 2913 2914 const FunctionType *fty = type->castAs<FunctionType>(); 2915 2916 // If we're referring to a function with an __unknown_anytype 2917 // result type, make the entire expression __unknown_anytype. 2918 if (fty->getReturnType() == Context.UnknownAnyTy) { 2919 type = Context.UnknownAnyTy; 2920 valueKind = VK_RValue; 2921 break; 2922 } 2923 2924 // Functions are l-values in C++. 2925 if (getLangOpts().CPlusPlus) { 2926 valueKind = VK_LValue; 2927 break; 2928 } 2929 2930 // C99 DR 316 says that, if a function type comes from a 2931 // function definition (without a prototype), that type is only 2932 // used for checking compatibility. Therefore, when referencing 2933 // the function, we pretend that we don't have the full function 2934 // type. 2935 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2936 isa<FunctionProtoType>(fty)) 2937 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2938 fty->getExtInfo()); 2939 2940 // Functions are r-values in C. 2941 valueKind = VK_RValue; 2942 break; 2943 } 2944 2945 case Decl::MSProperty: 2946 valueKind = VK_LValue; 2947 break; 2948 2949 case Decl::CXXMethod: 2950 // If we're referring to a method with an __unknown_anytype 2951 // result type, make the entire expression __unknown_anytype. 2952 // This should only be possible with a type written directly. 2953 if (const FunctionProtoType *proto 2954 = dyn_cast<FunctionProtoType>(VD->getType())) 2955 if (proto->getReturnType() == Context.UnknownAnyTy) { 2956 type = Context.UnknownAnyTy; 2957 valueKind = VK_RValue; 2958 break; 2959 } 2960 2961 // C++ methods are l-values if static, r-values if non-static. 2962 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2963 valueKind = VK_LValue; 2964 break; 2965 } 2966 // fallthrough 2967 2968 case Decl::CXXConversion: 2969 case Decl::CXXDestructor: 2970 case Decl::CXXConstructor: 2971 valueKind = VK_RValue; 2972 break; 2973 } 2974 2975 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2976 TemplateArgs); 2977 } 2978 } 2979 2980 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2981 SmallString<32> &Target) { 2982 Target.resize(CharByteWidth * (Source.size() + 1)); 2983 char *ResultPtr = &Target[0]; 2984 const UTF8 *ErrorPtr; 2985 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2986 (void)success; 2987 assert(success); 2988 Target.resize(ResultPtr - &Target[0]); 2989 } 2990 2991 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2992 PredefinedExpr::IdentType IT) { 2993 // Pick the current block, lambda, captured statement or function. 2994 Decl *currentDecl = nullptr; 2995 if (const BlockScopeInfo *BSI = getCurBlock()) 2996 currentDecl = BSI->TheDecl; 2997 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2998 currentDecl = LSI->CallOperator; 2999 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3000 currentDecl = CSI->TheCapturedDecl; 3001 else 3002 currentDecl = getCurFunctionOrMethodDecl(); 3003 3004 if (!currentDecl) { 3005 Diag(Loc, diag::ext_predef_outside_function); 3006 currentDecl = Context.getTranslationUnitDecl(); 3007 } 3008 3009 QualType ResTy; 3010 StringLiteral *SL = nullptr; 3011 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3012 ResTy = Context.DependentTy; 3013 else { 3014 // Pre-defined identifiers are of type char[x], where x is the length of 3015 // the string. 3016 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3017 unsigned Length = Str.length(); 3018 3019 llvm::APInt LengthI(32, Length + 1); 3020 if (IT == PredefinedExpr::LFunction) { 3021 ResTy = Context.WideCharTy.withConst(); 3022 SmallString<32> RawChars; 3023 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3024 Str, RawChars); 3025 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3026 /*IndexTypeQuals*/ 0); 3027 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3028 /*Pascal*/ false, ResTy, Loc); 3029 } else { 3030 ResTy = Context.CharTy.withConst(); 3031 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3032 /*IndexTypeQuals*/ 0); 3033 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3034 /*Pascal*/ false, ResTy, Loc); 3035 } 3036 } 3037 3038 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3039 } 3040 3041 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3042 PredefinedExpr::IdentType IT; 3043 3044 switch (Kind) { 3045 default: llvm_unreachable("Unknown simple primary expr!"); 3046 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3047 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3048 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3049 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3050 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3051 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3052 } 3053 3054 return BuildPredefinedExpr(Loc, IT); 3055 } 3056 3057 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3058 SmallString<16> CharBuffer; 3059 bool Invalid = false; 3060 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3061 if (Invalid) 3062 return ExprError(); 3063 3064 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3065 PP, Tok.getKind()); 3066 if (Literal.hadError()) 3067 return ExprError(); 3068 3069 QualType Ty; 3070 if (Literal.isWide()) 3071 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3072 else if (Literal.isUTF16()) 3073 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3074 else if (Literal.isUTF32()) 3075 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3076 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3077 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3078 else 3079 Ty = Context.CharTy; // 'x' -> char in C++ 3080 3081 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3082 if (Literal.isWide()) 3083 Kind = CharacterLiteral::Wide; 3084 else if (Literal.isUTF16()) 3085 Kind = CharacterLiteral::UTF16; 3086 else if (Literal.isUTF32()) 3087 Kind = CharacterLiteral::UTF32; 3088 3089 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3090 Tok.getLocation()); 3091 3092 if (Literal.getUDSuffix().empty()) 3093 return Lit; 3094 3095 // We're building a user-defined literal. 3096 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3097 SourceLocation UDSuffixLoc = 3098 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3099 3100 // Make sure we're allowed user-defined literals here. 3101 if (!UDLScope) 3102 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3103 3104 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3105 // operator "" X (ch) 3106 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3107 Lit, Tok.getLocation()); 3108 } 3109 3110 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3111 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3112 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3113 Context.IntTy, Loc); 3114 } 3115 3116 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3117 QualType Ty, SourceLocation Loc) { 3118 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3119 3120 using llvm::APFloat; 3121 APFloat Val(Format); 3122 3123 APFloat::opStatus result = Literal.GetFloatValue(Val); 3124 3125 // Overflow is always an error, but underflow is only an error if 3126 // we underflowed to zero (APFloat reports denormals as underflow). 3127 if ((result & APFloat::opOverflow) || 3128 ((result & APFloat::opUnderflow) && Val.isZero())) { 3129 unsigned diagnostic; 3130 SmallString<20> buffer; 3131 if (result & APFloat::opOverflow) { 3132 diagnostic = diag::warn_float_overflow; 3133 APFloat::getLargest(Format).toString(buffer); 3134 } else { 3135 diagnostic = diag::warn_float_underflow; 3136 APFloat::getSmallest(Format).toString(buffer); 3137 } 3138 3139 S.Diag(Loc, diagnostic) 3140 << Ty 3141 << StringRef(buffer.data(), buffer.size()); 3142 } 3143 3144 bool isExact = (result == APFloat::opOK); 3145 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3146 } 3147 3148 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3149 assert(E && "Invalid expression"); 3150 3151 if (E->isValueDependent()) 3152 return false; 3153 3154 QualType QT = E->getType(); 3155 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3156 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3157 return true; 3158 } 3159 3160 llvm::APSInt ValueAPS; 3161 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3162 3163 if (R.isInvalid()) 3164 return true; 3165 3166 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3167 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3168 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3169 << ValueAPS.toString(10) << ValueIsPositive; 3170 return true; 3171 } 3172 3173 return false; 3174 } 3175 3176 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3177 // Fast path for a single digit (which is quite common). A single digit 3178 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3179 if (Tok.getLength() == 1) { 3180 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3181 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3182 } 3183 3184 SmallString<128> SpellingBuffer; 3185 // NumericLiteralParser wants to overread by one character. Add padding to 3186 // the buffer in case the token is copied to the buffer. If getSpelling() 3187 // returns a StringRef to the memory buffer, it should have a null char at 3188 // the EOF, so it is also safe. 3189 SpellingBuffer.resize(Tok.getLength() + 1); 3190 3191 // Get the spelling of the token, which eliminates trigraphs, etc. 3192 bool Invalid = false; 3193 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3194 if (Invalid) 3195 return ExprError(); 3196 3197 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3198 if (Literal.hadError) 3199 return ExprError(); 3200 3201 if (Literal.hasUDSuffix()) { 3202 // We're building a user-defined literal. 3203 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3204 SourceLocation UDSuffixLoc = 3205 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3206 3207 // Make sure we're allowed user-defined literals here. 3208 if (!UDLScope) 3209 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3210 3211 QualType CookedTy; 3212 if (Literal.isFloatingLiteral()) { 3213 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3214 // long double, the literal is treated as a call of the form 3215 // operator "" X (f L) 3216 CookedTy = Context.LongDoubleTy; 3217 } else { 3218 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3219 // unsigned long long, the literal is treated as a call of the form 3220 // operator "" X (n ULL) 3221 CookedTy = Context.UnsignedLongLongTy; 3222 } 3223 3224 DeclarationName OpName = 3225 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3226 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3227 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3228 3229 SourceLocation TokLoc = Tok.getLocation(); 3230 3231 // Perform literal operator lookup to determine if we're building a raw 3232 // literal or a cooked one. 3233 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3234 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3235 /*AllowRaw*/true, /*AllowTemplate*/true, 3236 /*AllowStringTemplate*/false)) { 3237 case LOLR_Error: 3238 return ExprError(); 3239 3240 case LOLR_Cooked: { 3241 Expr *Lit; 3242 if (Literal.isFloatingLiteral()) { 3243 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3244 } else { 3245 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3246 if (Literal.GetIntegerValue(ResultVal)) 3247 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3248 << /* Unsigned */ 1; 3249 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3250 Tok.getLocation()); 3251 } 3252 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3253 } 3254 3255 case LOLR_Raw: { 3256 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3257 // literal is treated as a call of the form 3258 // operator "" X ("n") 3259 unsigned Length = Literal.getUDSuffixOffset(); 3260 QualType StrTy = Context.getConstantArrayType( 3261 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3262 ArrayType::Normal, 0); 3263 Expr *Lit = StringLiteral::Create( 3264 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3265 /*Pascal*/false, StrTy, &TokLoc, 1); 3266 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3267 } 3268 3269 case LOLR_Template: { 3270 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3271 // template), L is treated as a call fo the form 3272 // operator "" X <'c1', 'c2', ... 'ck'>() 3273 // where n is the source character sequence c1 c2 ... ck. 3274 TemplateArgumentListInfo ExplicitArgs; 3275 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3276 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3277 llvm::APSInt Value(CharBits, CharIsUnsigned); 3278 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3279 Value = TokSpelling[I]; 3280 TemplateArgument Arg(Context, Value, Context.CharTy); 3281 TemplateArgumentLocInfo ArgInfo; 3282 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3283 } 3284 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3285 &ExplicitArgs); 3286 } 3287 case LOLR_StringTemplate: 3288 llvm_unreachable("unexpected literal operator lookup result"); 3289 } 3290 } 3291 3292 Expr *Res; 3293 3294 if (Literal.isFloatingLiteral()) { 3295 QualType Ty; 3296 if (Literal.isFloat) 3297 Ty = Context.FloatTy; 3298 else if (!Literal.isLong) 3299 Ty = Context.DoubleTy; 3300 else 3301 Ty = Context.LongDoubleTy; 3302 3303 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3304 3305 if (Ty == Context.DoubleTy) { 3306 if (getLangOpts().SinglePrecisionConstants) { 3307 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3308 } else if (getLangOpts().OpenCL && 3309 !((getLangOpts().OpenCLVersion >= 120) || 3310 getOpenCLOptions().cl_khr_fp64)) { 3311 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3312 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3313 } 3314 } 3315 } else if (!Literal.isIntegerLiteral()) { 3316 return ExprError(); 3317 } else { 3318 QualType Ty; 3319 3320 // 'long long' is a C99 or C++11 feature. 3321 if (!getLangOpts().C99 && Literal.isLongLong) { 3322 if (getLangOpts().CPlusPlus) 3323 Diag(Tok.getLocation(), 3324 getLangOpts().CPlusPlus11 ? 3325 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3326 else 3327 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3328 } 3329 3330 // Get the value in the widest-possible width. 3331 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3332 llvm::APInt ResultVal(MaxWidth, 0); 3333 3334 if (Literal.GetIntegerValue(ResultVal)) { 3335 // If this value didn't fit into uintmax_t, error and force to ull. 3336 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3337 << /* Unsigned */ 1; 3338 Ty = Context.UnsignedLongLongTy; 3339 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3340 "long long is not intmax_t?"); 3341 } else { 3342 // If this value fits into a ULL, try to figure out what else it fits into 3343 // according to the rules of C99 6.4.4.1p5. 3344 3345 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3346 // be an unsigned int. 3347 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3348 3349 // Check from smallest to largest, picking the smallest type we can. 3350 unsigned Width = 0; 3351 3352 // Microsoft specific integer suffixes are explicitly sized. 3353 if (Literal.MicrosoftInteger) { 3354 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3355 Width = 8; 3356 Ty = Context.CharTy; 3357 } else { 3358 Width = Literal.MicrosoftInteger; 3359 Ty = Context.getIntTypeForBitwidth(Width, 3360 /*Signed=*/!Literal.isUnsigned); 3361 } 3362 } 3363 3364 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3365 // Are int/unsigned possibilities? 3366 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3367 3368 // Does it fit in a unsigned int? 3369 if (ResultVal.isIntN(IntSize)) { 3370 // Does it fit in a signed int? 3371 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3372 Ty = Context.IntTy; 3373 else if (AllowUnsigned) 3374 Ty = Context.UnsignedIntTy; 3375 Width = IntSize; 3376 } 3377 } 3378 3379 // Are long/unsigned long possibilities? 3380 if (Ty.isNull() && !Literal.isLongLong) { 3381 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3382 3383 // Does it fit in a unsigned long? 3384 if (ResultVal.isIntN(LongSize)) { 3385 // Does it fit in a signed long? 3386 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3387 Ty = Context.LongTy; 3388 else if (AllowUnsigned) 3389 Ty = Context.UnsignedLongTy; 3390 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3391 // is compatible. 3392 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3393 const unsigned LongLongSize = 3394 Context.getTargetInfo().getLongLongWidth(); 3395 Diag(Tok.getLocation(), 3396 getLangOpts().CPlusPlus 3397 ? Literal.isLong 3398 ? diag::warn_old_implicitly_unsigned_long_cxx 3399 : /*C++98 UB*/ diag:: 3400 ext_old_implicitly_unsigned_long_cxx 3401 : diag::warn_old_implicitly_unsigned_long) 3402 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3403 : /*will be ill-formed*/ 1); 3404 Ty = Context.UnsignedLongTy; 3405 } 3406 Width = LongSize; 3407 } 3408 } 3409 3410 // Check long long if needed. 3411 if (Ty.isNull()) { 3412 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3413 3414 // Does it fit in a unsigned long long? 3415 if (ResultVal.isIntN(LongLongSize)) { 3416 // Does it fit in a signed long long? 3417 // To be compatible with MSVC, hex integer literals ending with the 3418 // LL or i64 suffix are always signed in Microsoft mode. 3419 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3420 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3421 Ty = Context.LongLongTy; 3422 else if (AllowUnsigned) 3423 Ty = Context.UnsignedLongLongTy; 3424 Width = LongLongSize; 3425 } 3426 } 3427 3428 // If we still couldn't decide a type, we probably have something that 3429 // does not fit in a signed long long, but has no U suffix. 3430 if (Ty.isNull()) { 3431 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3432 Ty = Context.UnsignedLongLongTy; 3433 Width = Context.getTargetInfo().getLongLongWidth(); 3434 } 3435 3436 if (ResultVal.getBitWidth() != Width) 3437 ResultVal = ResultVal.trunc(Width); 3438 } 3439 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3440 } 3441 3442 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3443 if (Literal.isImaginary) 3444 Res = new (Context) ImaginaryLiteral(Res, 3445 Context.getComplexType(Res->getType())); 3446 3447 return Res; 3448 } 3449 3450 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3451 assert(E && "ActOnParenExpr() missing expr"); 3452 return new (Context) ParenExpr(L, R, E); 3453 } 3454 3455 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3456 SourceLocation Loc, 3457 SourceRange ArgRange) { 3458 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3459 // scalar or vector data type argument..." 3460 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3461 // type (C99 6.2.5p18) or void. 3462 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3463 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3464 << T << ArgRange; 3465 return true; 3466 } 3467 3468 assert((T->isVoidType() || !T->isIncompleteType()) && 3469 "Scalar types should always be complete"); 3470 return false; 3471 } 3472 3473 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3474 SourceLocation Loc, 3475 SourceRange ArgRange, 3476 UnaryExprOrTypeTrait TraitKind) { 3477 // Invalid types must be hard errors for SFINAE in C++. 3478 if (S.LangOpts.CPlusPlus) 3479 return true; 3480 3481 // C99 6.5.3.4p1: 3482 if (T->isFunctionType() && 3483 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3484 // sizeof(function)/alignof(function) is allowed as an extension. 3485 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3486 << TraitKind << ArgRange; 3487 return false; 3488 } 3489 3490 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3491 // this is an error (OpenCL v1.1 s6.3.k) 3492 if (T->isVoidType()) { 3493 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3494 : diag::ext_sizeof_alignof_void_type; 3495 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3496 return false; 3497 } 3498 3499 return true; 3500 } 3501 3502 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3503 SourceLocation Loc, 3504 SourceRange ArgRange, 3505 UnaryExprOrTypeTrait TraitKind) { 3506 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3507 // runtime doesn't allow it. 3508 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3509 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3510 << T << (TraitKind == UETT_SizeOf) 3511 << ArgRange; 3512 return true; 3513 } 3514 3515 return false; 3516 } 3517 3518 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3519 /// pointer type is equal to T) and emit a warning if it is. 3520 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3521 Expr *E) { 3522 // Don't warn if the operation changed the type. 3523 if (T != E->getType()) 3524 return; 3525 3526 // Now look for array decays. 3527 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3528 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3529 return; 3530 3531 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3532 << ICE->getType() 3533 << ICE->getSubExpr()->getType(); 3534 } 3535 3536 /// \brief Check the constraints on expression operands to unary type expression 3537 /// and type traits. 3538 /// 3539 /// Completes any types necessary and validates the constraints on the operand 3540 /// expression. The logic mostly mirrors the type-based overload, but may modify 3541 /// the expression as it completes the type for that expression through template 3542 /// instantiation, etc. 3543 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3544 UnaryExprOrTypeTrait ExprKind) { 3545 QualType ExprTy = E->getType(); 3546 assert(!ExprTy->isReferenceType()); 3547 3548 if (ExprKind == UETT_VecStep) 3549 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3550 E->getSourceRange()); 3551 3552 // Whitelist some types as extensions 3553 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3554 E->getSourceRange(), ExprKind)) 3555 return false; 3556 3557 // 'alignof' applied to an expression only requires the base element type of 3558 // the expression to be complete. 'sizeof' requires the expression's type to 3559 // be complete (and will attempt to complete it if it's an array of unknown 3560 // bound). 3561 if (ExprKind == UETT_AlignOf) { 3562 if (RequireCompleteType(E->getExprLoc(), 3563 Context.getBaseElementType(E->getType()), 3564 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3565 E->getSourceRange())) 3566 return true; 3567 } else { 3568 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3569 ExprKind, E->getSourceRange())) 3570 return true; 3571 } 3572 3573 // Completing the expression's type may have changed it. 3574 ExprTy = E->getType(); 3575 assert(!ExprTy->isReferenceType()); 3576 3577 if (ExprTy->isFunctionType()) { 3578 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3579 << ExprKind << E->getSourceRange(); 3580 return true; 3581 } 3582 3583 // The operand for sizeof and alignof is in an unevaluated expression context, 3584 // so side effects could result in unintended consequences. 3585 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3586 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3587 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3588 3589 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3590 E->getSourceRange(), ExprKind)) 3591 return true; 3592 3593 if (ExprKind == UETT_SizeOf) { 3594 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3595 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3596 QualType OType = PVD->getOriginalType(); 3597 QualType Type = PVD->getType(); 3598 if (Type->isPointerType() && OType->isArrayType()) { 3599 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3600 << Type << OType; 3601 Diag(PVD->getLocation(), diag::note_declared_at); 3602 } 3603 } 3604 } 3605 3606 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3607 // decays into a pointer and returns an unintended result. This is most 3608 // likely a typo for "sizeof(array) op x". 3609 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3610 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3611 BO->getLHS()); 3612 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3613 BO->getRHS()); 3614 } 3615 } 3616 3617 return false; 3618 } 3619 3620 /// \brief Check the constraints on operands to unary expression and type 3621 /// traits. 3622 /// 3623 /// This will complete any types necessary, and validate the various constraints 3624 /// on those operands. 3625 /// 3626 /// The UsualUnaryConversions() function is *not* called by this routine. 3627 /// C99 6.3.2.1p[2-4] all state: 3628 /// Except when it is the operand of the sizeof operator ... 3629 /// 3630 /// C++ [expr.sizeof]p4 3631 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3632 /// standard conversions are not applied to the operand of sizeof. 3633 /// 3634 /// This policy is followed for all of the unary trait expressions. 3635 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3636 SourceLocation OpLoc, 3637 SourceRange ExprRange, 3638 UnaryExprOrTypeTrait ExprKind) { 3639 if (ExprType->isDependentType()) 3640 return false; 3641 3642 // C++ [expr.sizeof]p2: 3643 // When applied to a reference or a reference type, the result 3644 // is the size of the referenced type. 3645 // C++11 [expr.alignof]p3: 3646 // When alignof is applied to a reference type, the result 3647 // shall be the alignment of the referenced type. 3648 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3649 ExprType = Ref->getPointeeType(); 3650 3651 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3652 // When alignof or _Alignof is applied to an array type, the result 3653 // is the alignment of the element type. 3654 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3655 ExprType = Context.getBaseElementType(ExprType); 3656 3657 if (ExprKind == UETT_VecStep) 3658 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3659 3660 // Whitelist some types as extensions 3661 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3662 ExprKind)) 3663 return false; 3664 3665 if (RequireCompleteType(OpLoc, ExprType, 3666 diag::err_sizeof_alignof_incomplete_type, 3667 ExprKind, ExprRange)) 3668 return true; 3669 3670 if (ExprType->isFunctionType()) { 3671 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3672 << ExprKind << ExprRange; 3673 return true; 3674 } 3675 3676 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3677 ExprKind)) 3678 return true; 3679 3680 return false; 3681 } 3682 3683 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3684 E = E->IgnoreParens(); 3685 3686 // Cannot know anything else if the expression is dependent. 3687 if (E->isTypeDependent()) 3688 return false; 3689 3690 if (E->getObjectKind() == OK_BitField) { 3691 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3692 << 1 << E->getSourceRange(); 3693 return true; 3694 } 3695 3696 ValueDecl *D = nullptr; 3697 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3698 D = DRE->getDecl(); 3699 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3700 D = ME->getMemberDecl(); 3701 } 3702 3703 // If it's a field, require the containing struct to have a 3704 // complete definition so that we can compute the layout. 3705 // 3706 // This can happen in C++11 onwards, either by naming the member 3707 // in a way that is not transformed into a member access expression 3708 // (in an unevaluated operand, for instance), or by naming the member 3709 // in a trailing-return-type. 3710 // 3711 // For the record, since __alignof__ on expressions is a GCC 3712 // extension, GCC seems to permit this but always gives the 3713 // nonsensical answer 0. 3714 // 3715 // We don't really need the layout here --- we could instead just 3716 // directly check for all the appropriate alignment-lowing 3717 // attributes --- but that would require duplicating a lot of 3718 // logic that just isn't worth duplicating for such a marginal 3719 // use-case. 3720 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3721 // Fast path this check, since we at least know the record has a 3722 // definition if we can find a member of it. 3723 if (!FD->getParent()->isCompleteDefinition()) { 3724 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3725 << E->getSourceRange(); 3726 return true; 3727 } 3728 3729 // Otherwise, if it's a field, and the field doesn't have 3730 // reference type, then it must have a complete type (or be a 3731 // flexible array member, which we explicitly want to 3732 // white-list anyway), which makes the following checks trivial. 3733 if (!FD->getType()->isReferenceType()) 3734 return false; 3735 } 3736 3737 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3738 } 3739 3740 bool Sema::CheckVecStepExpr(Expr *E) { 3741 E = E->IgnoreParens(); 3742 3743 // Cannot know anything else if the expression is dependent. 3744 if (E->isTypeDependent()) 3745 return false; 3746 3747 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3748 } 3749 3750 /// \brief Build a sizeof or alignof expression given a type operand. 3751 ExprResult 3752 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3753 SourceLocation OpLoc, 3754 UnaryExprOrTypeTrait ExprKind, 3755 SourceRange R) { 3756 if (!TInfo) 3757 return ExprError(); 3758 3759 QualType T = TInfo->getType(); 3760 3761 if (!T->isDependentType() && 3762 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3763 return ExprError(); 3764 3765 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3766 return new (Context) UnaryExprOrTypeTraitExpr( 3767 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3768 } 3769 3770 /// \brief Build a sizeof or alignof expression given an expression 3771 /// operand. 3772 ExprResult 3773 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3774 UnaryExprOrTypeTrait ExprKind) { 3775 ExprResult PE = CheckPlaceholderExpr(E); 3776 if (PE.isInvalid()) 3777 return ExprError(); 3778 3779 E = PE.get(); 3780 3781 // Verify that the operand is valid. 3782 bool isInvalid = false; 3783 if (E->isTypeDependent()) { 3784 // Delay type-checking for type-dependent expressions. 3785 } else if (ExprKind == UETT_AlignOf) { 3786 isInvalid = CheckAlignOfExpr(*this, E); 3787 } else if (ExprKind == UETT_VecStep) { 3788 isInvalid = CheckVecStepExpr(E); 3789 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3790 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3791 isInvalid = true; 3792 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3793 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3794 isInvalid = true; 3795 } else { 3796 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3797 } 3798 3799 if (isInvalid) 3800 return ExprError(); 3801 3802 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3803 PE = TransformToPotentiallyEvaluated(E); 3804 if (PE.isInvalid()) return ExprError(); 3805 E = PE.get(); 3806 } 3807 3808 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3809 return new (Context) UnaryExprOrTypeTraitExpr( 3810 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3811 } 3812 3813 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3814 /// expr and the same for @c alignof and @c __alignof 3815 /// Note that the ArgRange is invalid if isType is false. 3816 ExprResult 3817 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3818 UnaryExprOrTypeTrait ExprKind, bool IsType, 3819 void *TyOrEx, SourceRange ArgRange) { 3820 // If error parsing type, ignore. 3821 if (!TyOrEx) return ExprError(); 3822 3823 if (IsType) { 3824 TypeSourceInfo *TInfo; 3825 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3826 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3827 } 3828 3829 Expr *ArgEx = (Expr *)TyOrEx; 3830 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3831 return Result; 3832 } 3833 3834 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3835 bool IsReal) { 3836 if (V.get()->isTypeDependent()) 3837 return S.Context.DependentTy; 3838 3839 // _Real and _Imag are only l-values for normal l-values. 3840 if (V.get()->getObjectKind() != OK_Ordinary) { 3841 V = S.DefaultLvalueConversion(V.get()); 3842 if (V.isInvalid()) 3843 return QualType(); 3844 } 3845 3846 // These operators return the element type of a complex type. 3847 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3848 return CT->getElementType(); 3849 3850 // Otherwise they pass through real integer and floating point types here. 3851 if (V.get()->getType()->isArithmeticType()) 3852 return V.get()->getType(); 3853 3854 // Test for placeholders. 3855 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3856 if (PR.isInvalid()) return QualType(); 3857 if (PR.get() != V.get()) { 3858 V = PR; 3859 return CheckRealImagOperand(S, V, Loc, IsReal); 3860 } 3861 3862 // Reject anything else. 3863 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3864 << (IsReal ? "__real" : "__imag"); 3865 return QualType(); 3866 } 3867 3868 3869 3870 ExprResult 3871 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3872 tok::TokenKind Kind, Expr *Input) { 3873 UnaryOperatorKind Opc; 3874 switch (Kind) { 3875 default: llvm_unreachable("Unknown unary op!"); 3876 case tok::plusplus: Opc = UO_PostInc; break; 3877 case tok::minusminus: Opc = UO_PostDec; break; 3878 } 3879 3880 // Since this might is a postfix expression, get rid of ParenListExprs. 3881 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3882 if (Result.isInvalid()) return ExprError(); 3883 Input = Result.get(); 3884 3885 return BuildUnaryOp(S, OpLoc, Opc, Input); 3886 } 3887 3888 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3889 /// 3890 /// \return true on error 3891 static bool checkArithmeticOnObjCPointer(Sema &S, 3892 SourceLocation opLoc, 3893 Expr *op) { 3894 assert(op->getType()->isObjCObjectPointerType()); 3895 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3896 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3897 return false; 3898 3899 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3900 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3901 << op->getSourceRange(); 3902 return true; 3903 } 3904 3905 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 3906 auto *BaseNoParens = Base->IgnoreParens(); 3907 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 3908 return MSProp->getPropertyDecl()->getType()->isArrayType(); 3909 return isa<MSPropertySubscriptExpr>(BaseNoParens); 3910 } 3911 3912 ExprResult 3913 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3914 Expr *idx, SourceLocation rbLoc) { 3915 if (base && !base->getType().isNull() && 3916 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 3917 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 3918 /*Length=*/nullptr, rbLoc); 3919 3920 // Since this might be a postfix expression, get rid of ParenListExprs. 3921 if (isa<ParenListExpr>(base)) { 3922 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3923 if (result.isInvalid()) return ExprError(); 3924 base = result.get(); 3925 } 3926 3927 // Handle any non-overload placeholder types in the base and index 3928 // expressions. We can't handle overloads here because the other 3929 // operand might be an overloadable type, in which case the overload 3930 // resolution for the operator overload should get the first crack 3931 // at the overload. 3932 bool IsMSPropertySubscript = false; 3933 if (base->getType()->isNonOverloadPlaceholderType()) { 3934 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 3935 if (!IsMSPropertySubscript) { 3936 ExprResult result = CheckPlaceholderExpr(base); 3937 if (result.isInvalid()) 3938 return ExprError(); 3939 base = result.get(); 3940 } 3941 } 3942 if (idx->getType()->isNonOverloadPlaceholderType()) { 3943 ExprResult result = CheckPlaceholderExpr(idx); 3944 if (result.isInvalid()) return ExprError(); 3945 idx = result.get(); 3946 } 3947 3948 // Build an unanalyzed expression if either operand is type-dependent. 3949 if (getLangOpts().CPlusPlus && 3950 (base->isTypeDependent() || idx->isTypeDependent())) { 3951 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3952 VK_LValue, OK_Ordinary, rbLoc); 3953 } 3954 3955 // MSDN, property (C++) 3956 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 3957 // This attribute can also be used in the declaration of an empty array in a 3958 // class or structure definition. For example: 3959 // __declspec(property(get=GetX, put=PutX)) int x[]; 3960 // The above statement indicates that x[] can be used with one or more array 3961 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 3962 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 3963 if (IsMSPropertySubscript) { 3964 // Build MS property subscript expression if base is MS property reference 3965 // or MS property subscript. 3966 return new (Context) MSPropertySubscriptExpr( 3967 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 3968 } 3969 3970 // Use C++ overloaded-operator rules if either operand has record 3971 // type. The spec says to do this if either type is *overloadable*, 3972 // but enum types can't declare subscript operators or conversion 3973 // operators, so there's nothing interesting for overload resolution 3974 // to do if there aren't any record types involved. 3975 // 3976 // ObjC pointers have their own subscripting logic that is not tied 3977 // to overload resolution and so should not take this path. 3978 if (getLangOpts().CPlusPlus && 3979 (base->getType()->isRecordType() || 3980 (!base->getType()->isObjCObjectPointerType() && 3981 idx->getType()->isRecordType()))) { 3982 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3983 } 3984 3985 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3986 } 3987 3988 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 3989 Expr *LowerBound, 3990 SourceLocation ColonLoc, Expr *Length, 3991 SourceLocation RBLoc) { 3992 if (Base->getType()->isPlaceholderType() && 3993 !Base->getType()->isSpecificPlaceholderType( 3994 BuiltinType::OMPArraySection)) { 3995 ExprResult Result = CheckPlaceholderExpr(Base); 3996 if (Result.isInvalid()) 3997 return ExprError(); 3998 Base = Result.get(); 3999 } 4000 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4001 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4002 if (Result.isInvalid()) 4003 return ExprError(); 4004 LowerBound = Result.get(); 4005 } 4006 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4007 ExprResult Result = CheckPlaceholderExpr(Length); 4008 if (Result.isInvalid()) 4009 return ExprError(); 4010 Length = Result.get(); 4011 } 4012 4013 // Build an unanalyzed expression if either operand is type-dependent. 4014 if (Base->isTypeDependent() || 4015 (LowerBound && 4016 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4017 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4018 return new (Context) 4019 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4020 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4021 } 4022 4023 // Perform default conversions. 4024 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4025 QualType ResultTy; 4026 if (OriginalTy->isAnyPointerType()) { 4027 ResultTy = OriginalTy->getPointeeType(); 4028 } else if (OriginalTy->isArrayType()) { 4029 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4030 } else { 4031 return ExprError( 4032 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4033 << Base->getSourceRange()); 4034 } 4035 // C99 6.5.2.1p1 4036 if (LowerBound) { 4037 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4038 LowerBound); 4039 if (Res.isInvalid()) 4040 return ExprError(Diag(LowerBound->getExprLoc(), 4041 diag::err_omp_typecheck_section_not_integer) 4042 << 0 << LowerBound->getSourceRange()); 4043 LowerBound = Res.get(); 4044 4045 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4046 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4047 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4048 << 0 << LowerBound->getSourceRange(); 4049 } 4050 if (Length) { 4051 auto Res = 4052 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4053 if (Res.isInvalid()) 4054 return ExprError(Diag(Length->getExprLoc(), 4055 diag::err_omp_typecheck_section_not_integer) 4056 << 1 << Length->getSourceRange()); 4057 Length = Res.get(); 4058 4059 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4060 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4061 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4062 << 1 << Length->getSourceRange(); 4063 } 4064 4065 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4066 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4067 // type. Note that functions are not objects, and that (in C99 parlance) 4068 // incomplete types are not object types. 4069 if (ResultTy->isFunctionType()) { 4070 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4071 << ResultTy << Base->getSourceRange(); 4072 return ExprError(); 4073 } 4074 4075 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4076 diag::err_omp_section_incomplete_type, Base)) 4077 return ExprError(); 4078 4079 if (LowerBound) { 4080 llvm::APSInt LowerBoundValue; 4081 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4082 // OpenMP 4.0, [2.4 Array Sections] 4083 // The lower-bound and length must evaluate to non-negative integers. 4084 if (LowerBoundValue.isNegative()) { 4085 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4086 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4087 << LowerBound->getSourceRange(); 4088 return ExprError(); 4089 } 4090 } 4091 } 4092 4093 if (Length) { 4094 llvm::APSInt LengthValue; 4095 if (Length->EvaluateAsInt(LengthValue, Context)) { 4096 // OpenMP 4.0, [2.4 Array Sections] 4097 // The lower-bound and length must evaluate to non-negative integers. 4098 if (LengthValue.isNegative()) { 4099 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4100 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4101 << Length->getSourceRange(); 4102 return ExprError(); 4103 } 4104 } 4105 } else if (ColonLoc.isValid() && 4106 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4107 !OriginalTy->isVariableArrayType()))) { 4108 // OpenMP 4.0, [2.4 Array Sections] 4109 // When the size of the array dimension is not known, the length must be 4110 // specified explicitly. 4111 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4112 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4113 return ExprError(); 4114 } 4115 4116 return new (Context) 4117 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4118 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4119 } 4120 4121 ExprResult 4122 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4123 Expr *Idx, SourceLocation RLoc) { 4124 Expr *LHSExp = Base; 4125 Expr *RHSExp = Idx; 4126 4127 // Perform default conversions. 4128 if (!LHSExp->getType()->getAs<VectorType>()) { 4129 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4130 if (Result.isInvalid()) 4131 return ExprError(); 4132 LHSExp = Result.get(); 4133 } 4134 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4135 if (Result.isInvalid()) 4136 return ExprError(); 4137 RHSExp = Result.get(); 4138 4139 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4140 ExprValueKind VK = VK_LValue; 4141 ExprObjectKind OK = OK_Ordinary; 4142 4143 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4144 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4145 // in the subscript position. As a result, we need to derive the array base 4146 // and index from the expression types. 4147 Expr *BaseExpr, *IndexExpr; 4148 QualType ResultType; 4149 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4150 BaseExpr = LHSExp; 4151 IndexExpr = RHSExp; 4152 ResultType = Context.DependentTy; 4153 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4154 BaseExpr = LHSExp; 4155 IndexExpr = RHSExp; 4156 ResultType = PTy->getPointeeType(); 4157 } else if (const ObjCObjectPointerType *PTy = 4158 LHSTy->getAs<ObjCObjectPointerType>()) { 4159 BaseExpr = LHSExp; 4160 IndexExpr = RHSExp; 4161 4162 // Use custom logic if this should be the pseudo-object subscript 4163 // expression. 4164 if (!LangOpts.isSubscriptPointerArithmetic()) 4165 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4166 nullptr); 4167 4168 ResultType = PTy->getPointeeType(); 4169 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4170 // Handle the uncommon case of "123[Ptr]". 4171 BaseExpr = RHSExp; 4172 IndexExpr = LHSExp; 4173 ResultType = PTy->getPointeeType(); 4174 } else if (const ObjCObjectPointerType *PTy = 4175 RHSTy->getAs<ObjCObjectPointerType>()) { 4176 // Handle the uncommon case of "123[Ptr]". 4177 BaseExpr = RHSExp; 4178 IndexExpr = LHSExp; 4179 ResultType = PTy->getPointeeType(); 4180 if (!LangOpts.isSubscriptPointerArithmetic()) { 4181 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4182 << ResultType << BaseExpr->getSourceRange(); 4183 return ExprError(); 4184 } 4185 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4186 BaseExpr = LHSExp; // vectors: V[123] 4187 IndexExpr = RHSExp; 4188 VK = LHSExp->getValueKind(); 4189 if (VK != VK_RValue) 4190 OK = OK_VectorComponent; 4191 4192 // FIXME: need to deal with const... 4193 ResultType = VTy->getElementType(); 4194 } else if (LHSTy->isArrayType()) { 4195 // If we see an array that wasn't promoted by 4196 // DefaultFunctionArrayLvalueConversion, it must be an array that 4197 // wasn't promoted because of the C90 rule that doesn't 4198 // allow promoting non-lvalue arrays. Warn, then 4199 // force the promotion here. 4200 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4201 LHSExp->getSourceRange(); 4202 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4203 CK_ArrayToPointerDecay).get(); 4204 LHSTy = LHSExp->getType(); 4205 4206 BaseExpr = LHSExp; 4207 IndexExpr = RHSExp; 4208 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4209 } else if (RHSTy->isArrayType()) { 4210 // Same as previous, except for 123[f().a] case 4211 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4212 RHSExp->getSourceRange(); 4213 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4214 CK_ArrayToPointerDecay).get(); 4215 RHSTy = RHSExp->getType(); 4216 4217 BaseExpr = RHSExp; 4218 IndexExpr = LHSExp; 4219 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4220 } else { 4221 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4222 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4223 } 4224 // C99 6.5.2.1p1 4225 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4226 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4227 << IndexExpr->getSourceRange()); 4228 4229 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4230 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4231 && !IndexExpr->isTypeDependent()) 4232 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4233 4234 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4235 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4236 // type. Note that Functions are not objects, and that (in C99 parlance) 4237 // incomplete types are not object types. 4238 if (ResultType->isFunctionType()) { 4239 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4240 << ResultType << BaseExpr->getSourceRange(); 4241 return ExprError(); 4242 } 4243 4244 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4245 // GNU extension: subscripting on pointer to void 4246 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4247 << BaseExpr->getSourceRange(); 4248 4249 // C forbids expressions of unqualified void type from being l-values. 4250 // See IsCForbiddenLValueType. 4251 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4252 } else if (!ResultType->isDependentType() && 4253 RequireCompleteType(LLoc, ResultType, 4254 diag::err_subscript_incomplete_type, BaseExpr)) 4255 return ExprError(); 4256 4257 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4258 !ResultType.isCForbiddenLValueType()); 4259 4260 return new (Context) 4261 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4262 } 4263 4264 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4265 FunctionDecl *FD, 4266 ParmVarDecl *Param) { 4267 if (Param->hasUnparsedDefaultArg()) { 4268 Diag(CallLoc, 4269 diag::err_use_of_default_argument_to_function_declared_later) << 4270 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4271 Diag(UnparsedDefaultArgLocs[Param], 4272 diag::note_default_argument_declared_here); 4273 return ExprError(); 4274 } 4275 4276 if (Param->hasUninstantiatedDefaultArg()) { 4277 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4278 4279 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4280 Param); 4281 4282 // Instantiate the expression. 4283 MultiLevelTemplateArgumentList MutiLevelArgList 4284 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4285 4286 InstantiatingTemplate Inst(*this, CallLoc, Param, 4287 MutiLevelArgList.getInnermost()); 4288 if (Inst.isInvalid()) 4289 return ExprError(); 4290 4291 ExprResult Result; 4292 { 4293 // C++ [dcl.fct.default]p5: 4294 // The names in the [default argument] expression are bound, and 4295 // the semantic constraints are checked, at the point where the 4296 // default argument expression appears. 4297 ContextRAII SavedContext(*this, FD); 4298 LocalInstantiationScope Local(*this); 4299 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4300 } 4301 if (Result.isInvalid()) 4302 return ExprError(); 4303 4304 // Check the expression as an initializer for the parameter. 4305 InitializedEntity Entity 4306 = InitializedEntity::InitializeParameter(Context, Param); 4307 InitializationKind Kind 4308 = InitializationKind::CreateCopy(Param->getLocation(), 4309 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4310 Expr *ResultE = Result.getAs<Expr>(); 4311 4312 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4313 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4314 if (Result.isInvalid()) 4315 return ExprError(); 4316 4317 Expr *Arg = Result.getAs<Expr>(); 4318 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4319 // Build the default argument expression. 4320 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4321 } 4322 4323 // If the default expression creates temporaries, we need to 4324 // push them to the current stack of expression temporaries so they'll 4325 // be properly destroyed. 4326 // FIXME: We should really be rebuilding the default argument with new 4327 // bound temporaries; see the comment in PR5810. 4328 // We don't need to do that with block decls, though, because 4329 // blocks in default argument expression can never capture anything. 4330 if (isa<ExprWithCleanups>(Param->getInit())) { 4331 // Set the "needs cleanups" bit regardless of whether there are 4332 // any explicit objects. 4333 ExprNeedsCleanups = true; 4334 4335 // Append all the objects to the cleanup list. Right now, this 4336 // should always be a no-op, because blocks in default argument 4337 // expressions should never be able to capture anything. 4338 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4339 "default argument expression has capturing blocks?"); 4340 } 4341 4342 // We already type-checked the argument, so we know it works. 4343 // Just mark all of the declarations in this potentially-evaluated expression 4344 // as being "referenced". 4345 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4346 /*SkipLocalVariables=*/true); 4347 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4348 } 4349 4350 4351 Sema::VariadicCallType 4352 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4353 Expr *Fn) { 4354 if (Proto && Proto->isVariadic()) { 4355 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4356 return VariadicConstructor; 4357 else if (Fn && Fn->getType()->isBlockPointerType()) 4358 return VariadicBlock; 4359 else if (FDecl) { 4360 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4361 if (Method->isInstance()) 4362 return VariadicMethod; 4363 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4364 return VariadicMethod; 4365 return VariadicFunction; 4366 } 4367 return VariadicDoesNotApply; 4368 } 4369 4370 namespace { 4371 class FunctionCallCCC : public FunctionCallFilterCCC { 4372 public: 4373 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4374 unsigned NumArgs, MemberExpr *ME) 4375 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4376 FunctionName(FuncName) {} 4377 4378 bool ValidateCandidate(const TypoCorrection &candidate) override { 4379 if (!candidate.getCorrectionSpecifier() || 4380 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4381 return false; 4382 } 4383 4384 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4385 } 4386 4387 private: 4388 const IdentifierInfo *const FunctionName; 4389 }; 4390 } 4391 4392 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4393 FunctionDecl *FDecl, 4394 ArrayRef<Expr *> Args) { 4395 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4396 DeclarationName FuncName = FDecl->getDeclName(); 4397 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4398 4399 if (TypoCorrection Corrected = S.CorrectTypo( 4400 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4401 S.getScopeForContext(S.CurContext), nullptr, 4402 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4403 Args.size(), ME), 4404 Sema::CTK_ErrorRecovery)) { 4405 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4406 if (Corrected.isOverloaded()) { 4407 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4408 OverloadCandidateSet::iterator Best; 4409 for (NamedDecl *CD : Corrected) { 4410 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4411 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4412 OCS); 4413 } 4414 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4415 case OR_Success: 4416 ND = Best->Function; 4417 Corrected.setCorrectionDecl(ND); 4418 break; 4419 default: 4420 break; 4421 } 4422 } 4423 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4424 return Corrected; 4425 } 4426 } 4427 } 4428 return TypoCorrection(); 4429 } 4430 4431 /// ConvertArgumentsForCall - Converts the arguments specified in 4432 /// Args/NumArgs to the parameter types of the function FDecl with 4433 /// function prototype Proto. Call is the call expression itself, and 4434 /// Fn is the function expression. For a C++ member function, this 4435 /// routine does not attempt to convert the object argument. Returns 4436 /// true if the call is ill-formed. 4437 bool 4438 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4439 FunctionDecl *FDecl, 4440 const FunctionProtoType *Proto, 4441 ArrayRef<Expr *> Args, 4442 SourceLocation RParenLoc, 4443 bool IsExecConfig) { 4444 // Bail out early if calling a builtin with custom typechecking. 4445 if (FDecl) 4446 if (unsigned ID = FDecl->getBuiltinID()) 4447 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4448 return false; 4449 4450 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4451 // assignment, to the types of the corresponding parameter, ... 4452 unsigned NumParams = Proto->getNumParams(); 4453 bool Invalid = false; 4454 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4455 unsigned FnKind = Fn->getType()->isBlockPointerType() 4456 ? 1 /* block */ 4457 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4458 : 0 /* function */); 4459 4460 // If too few arguments are available (and we don't have default 4461 // arguments for the remaining parameters), don't make the call. 4462 if (Args.size() < NumParams) { 4463 if (Args.size() < MinArgs) { 4464 TypoCorrection TC; 4465 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4466 unsigned diag_id = 4467 MinArgs == NumParams && !Proto->isVariadic() 4468 ? diag::err_typecheck_call_too_few_args_suggest 4469 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4470 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4471 << static_cast<unsigned>(Args.size()) 4472 << TC.getCorrectionRange()); 4473 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4474 Diag(RParenLoc, 4475 MinArgs == NumParams && !Proto->isVariadic() 4476 ? diag::err_typecheck_call_too_few_args_one 4477 : diag::err_typecheck_call_too_few_args_at_least_one) 4478 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4479 else 4480 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4481 ? diag::err_typecheck_call_too_few_args 4482 : diag::err_typecheck_call_too_few_args_at_least) 4483 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4484 << Fn->getSourceRange(); 4485 4486 // Emit the location of the prototype. 4487 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4488 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4489 << FDecl; 4490 4491 return true; 4492 } 4493 Call->setNumArgs(Context, NumParams); 4494 } 4495 4496 // If too many are passed and not variadic, error on the extras and drop 4497 // them. 4498 if (Args.size() > NumParams) { 4499 if (!Proto->isVariadic()) { 4500 TypoCorrection TC; 4501 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4502 unsigned diag_id = 4503 MinArgs == NumParams && !Proto->isVariadic() 4504 ? diag::err_typecheck_call_too_many_args_suggest 4505 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4506 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4507 << static_cast<unsigned>(Args.size()) 4508 << TC.getCorrectionRange()); 4509 } else if (NumParams == 1 && FDecl && 4510 FDecl->getParamDecl(0)->getDeclName()) 4511 Diag(Args[NumParams]->getLocStart(), 4512 MinArgs == NumParams 4513 ? diag::err_typecheck_call_too_many_args_one 4514 : diag::err_typecheck_call_too_many_args_at_most_one) 4515 << FnKind << FDecl->getParamDecl(0) 4516 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4517 << SourceRange(Args[NumParams]->getLocStart(), 4518 Args.back()->getLocEnd()); 4519 else 4520 Diag(Args[NumParams]->getLocStart(), 4521 MinArgs == NumParams 4522 ? diag::err_typecheck_call_too_many_args 4523 : diag::err_typecheck_call_too_many_args_at_most) 4524 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4525 << Fn->getSourceRange() 4526 << SourceRange(Args[NumParams]->getLocStart(), 4527 Args.back()->getLocEnd()); 4528 4529 // Emit the location of the prototype. 4530 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4531 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4532 << FDecl; 4533 4534 // This deletes the extra arguments. 4535 Call->setNumArgs(Context, NumParams); 4536 return true; 4537 } 4538 } 4539 SmallVector<Expr *, 8> AllArgs; 4540 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4541 4542 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4543 Proto, 0, Args, AllArgs, CallType); 4544 if (Invalid) 4545 return true; 4546 unsigned TotalNumArgs = AllArgs.size(); 4547 for (unsigned i = 0; i < TotalNumArgs; ++i) 4548 Call->setArg(i, AllArgs[i]); 4549 4550 return false; 4551 } 4552 4553 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4554 const FunctionProtoType *Proto, 4555 unsigned FirstParam, ArrayRef<Expr *> Args, 4556 SmallVectorImpl<Expr *> &AllArgs, 4557 VariadicCallType CallType, bool AllowExplicit, 4558 bool IsListInitialization) { 4559 unsigned NumParams = Proto->getNumParams(); 4560 bool Invalid = false; 4561 size_t ArgIx = 0; 4562 // Continue to check argument types (even if we have too few/many args). 4563 for (unsigned i = FirstParam; i < NumParams; i++) { 4564 QualType ProtoArgType = Proto->getParamType(i); 4565 4566 Expr *Arg; 4567 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4568 if (ArgIx < Args.size()) { 4569 Arg = Args[ArgIx++]; 4570 4571 if (RequireCompleteType(Arg->getLocStart(), 4572 ProtoArgType, 4573 diag::err_call_incomplete_argument, Arg)) 4574 return true; 4575 4576 // Strip the unbridged-cast placeholder expression off, if applicable. 4577 bool CFAudited = false; 4578 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4579 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4580 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4581 Arg = stripARCUnbridgedCast(Arg); 4582 else if (getLangOpts().ObjCAutoRefCount && 4583 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4584 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4585 CFAudited = true; 4586 4587 InitializedEntity Entity = 4588 Param ? InitializedEntity::InitializeParameter(Context, Param, 4589 ProtoArgType) 4590 : InitializedEntity::InitializeParameter( 4591 Context, ProtoArgType, Proto->isParamConsumed(i)); 4592 4593 // Remember that parameter belongs to a CF audited API. 4594 if (CFAudited) 4595 Entity.setParameterCFAudited(); 4596 4597 ExprResult ArgE = PerformCopyInitialization( 4598 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4599 if (ArgE.isInvalid()) 4600 return true; 4601 4602 Arg = ArgE.getAs<Expr>(); 4603 } else { 4604 assert(Param && "can't use default arguments without a known callee"); 4605 4606 ExprResult ArgExpr = 4607 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4608 if (ArgExpr.isInvalid()) 4609 return true; 4610 4611 Arg = ArgExpr.getAs<Expr>(); 4612 } 4613 4614 // Check for array bounds violations for each argument to the call. This 4615 // check only triggers warnings when the argument isn't a more complex Expr 4616 // with its own checking, such as a BinaryOperator. 4617 CheckArrayAccess(Arg); 4618 4619 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4620 CheckStaticArrayArgument(CallLoc, Param, Arg); 4621 4622 AllArgs.push_back(Arg); 4623 } 4624 4625 // If this is a variadic call, handle args passed through "...". 4626 if (CallType != VariadicDoesNotApply) { 4627 // Assume that extern "C" functions with variadic arguments that 4628 // return __unknown_anytype aren't *really* variadic. 4629 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4630 FDecl->isExternC()) { 4631 for (Expr *A : Args.slice(ArgIx)) { 4632 QualType paramType; // ignored 4633 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4634 Invalid |= arg.isInvalid(); 4635 AllArgs.push_back(arg.get()); 4636 } 4637 4638 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4639 } else { 4640 for (Expr *A : Args.slice(ArgIx)) { 4641 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4642 Invalid |= Arg.isInvalid(); 4643 AllArgs.push_back(Arg.get()); 4644 } 4645 } 4646 4647 // Check for array bounds violations. 4648 for (Expr *A : Args.slice(ArgIx)) 4649 CheckArrayAccess(A); 4650 } 4651 return Invalid; 4652 } 4653 4654 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4655 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4656 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4657 TL = DTL.getOriginalLoc();