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/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/AnalysisBasedWarnings.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/DelayedDiagnostic.h" 36 #include "clang/Sema/Designator.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/Lookup.h" 39 #include "clang/Sema/ParsedTemplate.h" 40 #include "clang/Sema/Scope.h" 41 #include "clang/Sema/ScopeInfo.h" 42 #include "clang/Sema/SemaFixItUtils.h" 43 #include "clang/Sema/Template.h" 44 using namespace clang; 45 using namespace sema; 46 47 /// \brief Determine whether the use of this declaration is valid, without 48 /// emitting diagnostics. 49 bool Sema::CanUseDecl(NamedDecl *D) { 50 // See if this is an auto-typed variable whose initializer we are parsing. 51 if (ParsingInitForAutoVars.count(D)) 52 return false; 53 54 // See if this is a deleted function. 55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 56 if (FD->isDeleted()) 57 return false; 58 59 // If the function has a deduced return type, and we can't deduce it, 60 // then we can't use it either. 61 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 62 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false)) 63 return false; 64 } 65 66 // See if this function is unavailable. 67 if (D->getAvailability() == AR_Unavailable && 68 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 69 return false; 70 71 return true; 72 } 73 74 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 75 // Warn if this is used but marked unused. 76 if (D->hasAttr<UnusedAttr>()) { 77 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 78 if (!DC->hasAttr<UnusedAttr>()) 79 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 80 } 81 } 82 83 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 84 NamedDecl *D, SourceLocation Loc, 85 const ObjCInterfaceDecl *UnknownObjCClass) { 86 // See if this declaration is unavailable or deprecated. 87 std::string Message; 88 AvailabilityResult Result = D->getAvailability(&Message); 89 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 90 if (Result == AR_Available) { 91 const DeclContext *DC = ECD->getDeclContext(); 92 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 93 Result = TheEnumDecl->getAvailability(&Message); 94 } 95 96 const ObjCPropertyDecl *ObjCPDecl = 0; 97 if (Result == AR_Deprecated || Result == AR_Unavailable) { 98 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 99 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 100 AvailabilityResult PDeclResult = PD->getAvailability(0); 101 if (PDeclResult == Result) 102 ObjCPDecl = PD; 103 } 104 } 105 } 106 107 switch (Result) { 108 case AR_Available: 109 case AR_NotYetIntroduced: 110 break; 111 112 case AR_Deprecated: 113 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 114 break; 115 116 case AR_Unavailable: 117 if (S.getCurContextAvailability() != AR_Unavailable) { 118 if (Message.empty()) { 119 if (!UnknownObjCClass) { 120 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 121 if (ObjCPDecl) 122 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 123 << ObjCPDecl->getDeclName() << 1; 124 } 125 else 126 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 127 << D->getDeclName(); 128 } 129 else 130 S.Diag(Loc, diag::err_unavailable_message) 131 << D->getDeclName() << Message; 132 S.Diag(D->getLocation(), diag::note_unavailable_here) 133 << isa<FunctionDecl>(D) << false; 134 if (ObjCPDecl) 135 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 136 << ObjCPDecl->getDeclName() << 1; 137 } 138 break; 139 } 140 return Result; 141 } 142 143 /// \brief Emit a note explaining that this function is deleted. 144 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 145 assert(Decl->isDeleted()); 146 147 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 148 149 if (Method && Method->isDeleted() && Method->isDefaulted()) { 150 // If the method was explicitly defaulted, point at that declaration. 151 if (!Method->isImplicit()) 152 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 153 154 // Try to diagnose why this special member function was implicitly 155 // deleted. This might fail, if that reason no longer applies. 156 CXXSpecialMember CSM = getSpecialMember(Method); 157 if (CSM != CXXInvalid) 158 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 159 160 return; 161 } 162 163 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 164 if (CXXConstructorDecl *BaseCD = 165 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 166 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 167 if (BaseCD->isDeleted()) { 168 NoteDeletedFunction(BaseCD); 169 } else { 170 // FIXME: An explanation of why exactly it can't be inherited 171 // would be nice. 172 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 173 } 174 return; 175 } 176 } 177 178 Diag(Decl->getLocation(), diag::note_unavailable_here) 179 << 1 << true; 180 } 181 182 /// \brief Determine whether a FunctionDecl was ever declared with an 183 /// explicit storage class. 184 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 185 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 186 E = D->redecls_end(); 187 I != E; ++I) { 188 if (I->getStorageClass() != SC_None) 189 return true; 190 } 191 return false; 192 } 193 194 /// \brief Check whether we're in an extern inline function and referring to a 195 /// variable or function with internal linkage (C11 6.7.4p3). 196 /// 197 /// This is only a warning because we used to silently accept this code, but 198 /// in many cases it will not behave correctly. This is not enabled in C++ mode 199 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 200 /// and so while there may still be user mistakes, most of the time we can't 201 /// prove that there are errors. 202 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 203 const NamedDecl *D, 204 SourceLocation Loc) { 205 // This is disabled under C++; there are too many ways for this to fire in 206 // contexts where the warning is a false positive, or where it is technically 207 // correct but benign. 208 if (S.getLangOpts().CPlusPlus) 209 return; 210 211 // Check if this is an inlined function or method. 212 FunctionDecl *Current = S.getCurFunctionDecl(); 213 if (!Current) 214 return; 215 if (!Current->isInlined()) 216 return; 217 if (!Current->isExternallyVisible()) 218 return; 219 220 // Check if the decl has internal linkage. 221 if (D->getFormalLinkage() != InternalLinkage) 222 return; 223 224 // Downgrade from ExtWarn to Extension if 225 // (1) the supposedly external inline function is in the main file, 226 // and probably won't be included anywhere else. 227 // (2) the thing we're referencing is a pure function. 228 // (3) the thing we're referencing is another inline function. 229 // This last can give us false negatives, but it's better than warning on 230 // wrappers for simple C library functions. 231 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 232 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 233 if (!DowngradeWarning && UsedFn) 234 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 235 236 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 237 : diag::warn_internal_in_extern_inline) 238 << /*IsVar=*/!UsedFn << D; 239 240 S.MaybeSuggestAddingStaticToDecl(Current); 241 242 S.Diag(D->getCanonicalDecl()->getLocation(), 243 diag::note_internal_decl_declared_here) 244 << D; 245 } 246 247 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 248 const FunctionDecl *First = Cur->getFirstDeclaration(); 249 250 // Suggest "static" on the function, if possible. 251 if (!hasAnyExplicitStorageClass(First)) { 252 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 253 Diag(DeclBegin, diag::note_convert_inline_to_static) 254 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 255 } 256 } 257 258 /// \brief Determine whether the use of this declaration is valid, and 259 /// emit any corresponding diagnostics. 260 /// 261 /// This routine diagnoses various problems with referencing 262 /// declarations that can occur when using a declaration. For example, 263 /// it might warn if a deprecated or unavailable declaration is being 264 /// used, or produce an error (and return true) if a C++0x deleted 265 /// function is being used. 266 /// 267 /// \returns true if there was an error (this declaration cannot be 268 /// referenced), false otherwise. 269 /// 270 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 271 const ObjCInterfaceDecl *UnknownObjCClass) { 272 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 273 // If there were any diagnostics suppressed by template argument deduction, 274 // emit them now. 275 SuppressedDiagnosticsMap::iterator 276 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 277 if (Pos != SuppressedDiagnostics.end()) { 278 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 279 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 280 Diag(Suppressed[I].first, Suppressed[I].second); 281 282 // Clear out the list of suppressed diagnostics, so that we don't emit 283 // them again for this specialization. However, we don't obsolete this 284 // entry from the table, because we want to avoid ever emitting these 285 // diagnostics again. 286 Suppressed.clear(); 287 } 288 } 289 290 // See if this is an auto-typed variable whose initializer we are parsing. 291 if (ParsingInitForAutoVars.count(D)) { 292 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 293 << D->getDeclName(); 294 return true; 295 } 296 297 // See if this is a deleted function. 298 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 299 if (FD->isDeleted()) { 300 Diag(Loc, diag::err_deleted_function_use); 301 NoteDeletedFunction(FD); 302 return true; 303 } 304 305 // If the function has a deduced return type, and we can't deduce it, 306 // then we can't use it either. 307 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 308 DeduceReturnType(FD, Loc)) 309 return true; 310 } 311 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 312 313 DiagnoseUnusedOfDecl(*this, D, Loc); 314 315 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 316 317 return false; 318 } 319 320 /// \brief Retrieve the message suffix that should be added to a 321 /// diagnostic complaining about the given function being deleted or 322 /// unavailable. 323 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 324 std::string Message; 325 if (FD->getAvailability(&Message)) 326 return ": " + Message; 327 328 return std::string(); 329 } 330 331 /// DiagnoseSentinelCalls - This routine checks whether a call or 332 /// message-send is to a declaration with the sentinel attribute, and 333 /// if so, it checks that the requirements of the sentinel are 334 /// satisfied. 335 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 336 ArrayRef<Expr *> Args) { 337 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 338 if (!attr) 339 return; 340 341 // The number of formal parameters of the declaration. 342 unsigned numFormalParams; 343 344 // The kind of declaration. This is also an index into a %select in 345 // the diagnostic. 346 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 347 348 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 349 numFormalParams = MD->param_size(); 350 calleeType = CT_Method; 351 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 352 numFormalParams = FD->param_size(); 353 calleeType = CT_Function; 354 } else if (isa<VarDecl>(D)) { 355 QualType type = cast<ValueDecl>(D)->getType(); 356 const FunctionType *fn = 0; 357 if (const PointerType *ptr = type->getAs<PointerType>()) { 358 fn = ptr->getPointeeType()->getAs<FunctionType>(); 359 if (!fn) return; 360 calleeType = CT_Function; 361 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 362 fn = ptr->getPointeeType()->castAs<FunctionType>(); 363 calleeType = CT_Block; 364 } else { 365 return; 366 } 367 368 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 369 numFormalParams = proto->getNumArgs(); 370 } else { 371 numFormalParams = 0; 372 } 373 } else { 374 return; 375 } 376 377 // "nullPos" is the number of formal parameters at the end which 378 // effectively count as part of the variadic arguments. This is 379 // useful if you would prefer to not have *any* formal parameters, 380 // but the language forces you to have at least one. 381 unsigned nullPos = attr->getNullPos(); 382 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 383 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 384 385 // The number of arguments which should follow the sentinel. 386 unsigned numArgsAfterSentinel = attr->getSentinel(); 387 388 // If there aren't enough arguments for all the formal parameters, 389 // the sentinel, and the args after the sentinel, complain. 390 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 391 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 392 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 393 return; 394 } 395 396 // Otherwise, find the sentinel expression. 397 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 398 if (!sentinelExpr) return; 399 if (sentinelExpr->isValueDependent()) return; 400 if (Context.isSentinelNullExpr(sentinelExpr)) return; 401 402 // Pick a reasonable string to insert. Optimistically use 'nil' or 403 // 'NULL' if those are actually defined in the context. Only use 404 // 'nil' for ObjC methods, where it's much more likely that the 405 // variadic arguments form a list of object pointers. 406 SourceLocation MissingNilLoc 407 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 408 std::string NullValue; 409 if (calleeType == CT_Method && 410 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 411 NullValue = "nil"; 412 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 413 NullValue = "NULL"; 414 else 415 NullValue = "(void*) 0"; 416 417 if (MissingNilLoc.isInvalid()) 418 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 419 else 420 Diag(MissingNilLoc, diag::warn_missing_sentinel) 421 << int(calleeType) 422 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 423 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 424 } 425 426 SourceRange Sema::getExprRange(Expr *E) const { 427 return E ? E->getSourceRange() : SourceRange(); 428 } 429 430 //===----------------------------------------------------------------------===// 431 // Standard Promotions and Conversions 432 //===----------------------------------------------------------------------===// 433 434 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 435 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 436 // Handle any placeholder expressions which made it here. 437 if (E->getType()->isPlaceholderType()) { 438 ExprResult result = CheckPlaceholderExpr(E); 439 if (result.isInvalid()) return ExprError(); 440 E = result.take(); 441 } 442 443 QualType Ty = E->getType(); 444 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 445 446 if (Ty->isFunctionType()) 447 E = ImpCastExprToType(E, Context.getPointerType(Ty), 448 CK_FunctionToPointerDecay).take(); 449 else if (Ty->isArrayType()) { 450 // In C90 mode, arrays only promote to pointers if the array expression is 451 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 452 // type 'array of type' is converted to an expression that has type 'pointer 453 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 454 // that has type 'array of type' ...". The relevant change is "an lvalue" 455 // (C90) to "an expression" (C99). 456 // 457 // C++ 4.2p1: 458 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 459 // T" can be converted to an rvalue of type "pointer to T". 460 // 461 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 462 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 463 CK_ArrayToPointerDecay).take(); 464 } 465 return Owned(E); 466 } 467 468 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 469 // Check to see if we are dereferencing a null pointer. If so, 470 // and if not volatile-qualified, this is undefined behavior that the 471 // optimizer will delete, so warn about it. People sometimes try to use this 472 // to get a deterministic trap and are surprised by clang's behavior. This 473 // only handles the pattern "*null", which is a very syntactic check. 474 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 475 if (UO->getOpcode() == UO_Deref && 476 UO->getSubExpr()->IgnoreParenCasts()-> 477 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 478 !UO->getType().isVolatileQualified()) { 479 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 480 S.PDiag(diag::warn_indirection_through_null) 481 << UO->getSubExpr()->getSourceRange()); 482 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 483 S.PDiag(diag::note_indirection_through_null)); 484 } 485 } 486 487 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 488 SourceLocation AssignLoc, 489 const Expr* RHS) { 490 const ObjCIvarDecl *IV = OIRE->getDecl(); 491 if (!IV) 492 return; 493 494 DeclarationName MemberName = IV->getDeclName(); 495 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 496 if (!Member || !Member->isStr("isa")) 497 return; 498 499 const Expr *Base = OIRE->getBase(); 500 QualType BaseType = Base->getType(); 501 if (OIRE->isArrow()) 502 BaseType = BaseType->getPointeeType(); 503 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 504 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 505 ObjCInterfaceDecl *ClassDeclared = 0; 506 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 507 if (!ClassDeclared->getSuperClass() 508 && (*ClassDeclared->ivar_begin()) == IV) { 509 if (RHS) { 510 NamedDecl *ObjectSetClass = 511 S.LookupSingleName(S.TUScope, 512 &S.Context.Idents.get("object_setClass"), 513 SourceLocation(), S.LookupOrdinaryName); 514 if (ObjectSetClass) { 515 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 516 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 517 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 518 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 519 AssignLoc), ",") << 520 FixItHint::CreateInsertion(RHSLocEnd, ")"); 521 } 522 else 523 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 524 } else { 525 NamedDecl *ObjectGetClass = 526 S.LookupSingleName(S.TUScope, 527 &S.Context.Idents.get("object_getClass"), 528 SourceLocation(), S.LookupOrdinaryName); 529 if (ObjectGetClass) 530 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 531 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 532 FixItHint::CreateReplacement( 533 SourceRange(OIRE->getOpLoc(), 534 OIRE->getLocEnd()), ")"); 535 else 536 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 537 } 538 S.Diag(IV->getLocation(), diag::note_ivar_decl); 539 } 540 } 541 } 542 543 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 544 // Handle any placeholder expressions which made it here. 545 if (E->getType()->isPlaceholderType()) { 546 ExprResult result = CheckPlaceholderExpr(E); 547 if (result.isInvalid()) return ExprError(); 548 E = result.take(); 549 } 550 551 // C++ [conv.lval]p1: 552 // A glvalue of a non-function, non-array type T can be 553 // converted to a prvalue. 554 if (!E->isGLValue()) return Owned(E); 555 556 QualType T = E->getType(); 557 assert(!T.isNull() && "r-value conversion on typeless expression?"); 558 559 // We don't want to throw lvalue-to-rvalue casts on top of 560 // expressions of certain types in C++. 561 if (getLangOpts().CPlusPlus && 562 (E->getType() == Context.OverloadTy || 563 T->isDependentType() || 564 T->isRecordType())) 565 return Owned(E); 566 567 // The C standard is actually really unclear on this point, and 568 // DR106 tells us what the result should be but not why. It's 569 // generally best to say that void types just doesn't undergo 570 // lvalue-to-rvalue at all. Note that expressions of unqualified 571 // 'void' type are never l-values, but qualified void can be. 572 if (T->isVoidType()) 573 return Owned(E); 574 575 // OpenCL usually rejects direct accesses to values of 'half' type. 576 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 577 T->isHalfType()) { 578 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 579 << 0 << T; 580 return ExprError(); 581 } 582 583 CheckForNullPointerDereference(*this, E); 584 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 585 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 586 &Context.Idents.get("object_getClass"), 587 SourceLocation(), LookupOrdinaryName); 588 if (ObjectGetClass) 589 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 590 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 591 FixItHint::CreateReplacement( 592 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 593 else 594 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 595 } 596 else if (const ObjCIvarRefExpr *OIRE = 597 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 598 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 599 600 // C++ [conv.lval]p1: 601 // [...] If T is a non-class type, the type of the prvalue is the 602 // cv-unqualified version of T. Otherwise, the type of the 603 // rvalue is T. 604 // 605 // C99 6.3.2.1p2: 606 // If the lvalue has qualified type, the value has the unqualified 607 // version of the type of the lvalue; otherwise, the value has the 608 // type of the lvalue. 609 if (T.hasQualifiers()) 610 T = T.getUnqualifiedType(); 611 612 UpdateMarkingForLValueToRValue(E); 613 614 // Loading a __weak object implicitly retains the value, so we need a cleanup to 615 // balance that. 616 if (getLangOpts().ObjCAutoRefCount && 617 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 618 ExprNeedsCleanups = true; 619 620 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 621 E, 0, VK_RValue)); 622 623 // C11 6.3.2.1p2: 624 // ... if the lvalue has atomic type, the value has the non-atomic version 625 // of the type of the lvalue ... 626 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 627 T = Atomic->getValueType().getUnqualifiedType(); 628 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 629 Res.get(), 0, VK_RValue)); 630 } 631 632 return Res; 633 } 634 635 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 636 ExprResult Res = DefaultFunctionArrayConversion(E); 637 if (Res.isInvalid()) 638 return ExprError(); 639 Res = DefaultLvalueConversion(Res.take()); 640 if (Res.isInvalid()) 641 return ExprError(); 642 return Res; 643 } 644 645 646 /// UsualUnaryConversions - Performs various conversions that are common to most 647 /// operators (C99 6.3). The conversions of array and function types are 648 /// sometimes suppressed. For example, the array->pointer conversion doesn't 649 /// apply if the array is an argument to the sizeof or address (&) operators. 650 /// In these instances, this routine should *not* be called. 651 ExprResult Sema::UsualUnaryConversions(Expr *E) { 652 // First, convert to an r-value. 653 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 654 if (Res.isInvalid()) 655 return ExprError(); 656 E = Res.take(); 657 658 QualType Ty = E->getType(); 659 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 660 661 // Half FP have to be promoted to float unless it is natively supported 662 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 663 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 664 665 // Try to perform integral promotions if the object has a theoretically 666 // promotable type. 667 if (Ty->isIntegralOrUnscopedEnumerationType()) { 668 // C99 6.3.1.1p2: 669 // 670 // The following may be used in an expression wherever an int or 671 // unsigned int may be used: 672 // - an object or expression with an integer type whose integer 673 // conversion rank is less than or equal to the rank of int 674 // and unsigned int. 675 // - A bit-field of type _Bool, int, signed int, or unsigned int. 676 // 677 // If an int can represent all values of the original type, the 678 // value is converted to an int; otherwise, it is converted to an 679 // unsigned int. These are called the integer promotions. All 680 // other types are unchanged by the integer promotions. 681 682 QualType PTy = Context.isPromotableBitField(E); 683 if (!PTy.isNull()) { 684 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 685 return Owned(E); 686 } 687 if (Ty->isPromotableIntegerType()) { 688 QualType PT = Context.getPromotedIntegerType(Ty); 689 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 690 return Owned(E); 691 } 692 } 693 return Owned(E); 694 } 695 696 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 697 /// do not have a prototype. Arguments that have type float or __fp16 698 /// are promoted to double. All other argument types are converted by 699 /// UsualUnaryConversions(). 700 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 701 QualType Ty = E->getType(); 702 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 703 704 ExprResult Res = UsualUnaryConversions(E); 705 if (Res.isInvalid()) 706 return ExprError(); 707 E = Res.take(); 708 709 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 710 // double. 711 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 712 if (BTy && (BTy->getKind() == BuiltinType::Half || 713 BTy->getKind() == BuiltinType::Float)) 714 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 715 716 // C++ performs lvalue-to-rvalue conversion as a default argument 717 // promotion, even on class types, but note: 718 // C++11 [conv.lval]p2: 719 // When an lvalue-to-rvalue conversion occurs in an unevaluated 720 // operand or a subexpression thereof the value contained in the 721 // referenced object is not accessed. Otherwise, if the glvalue 722 // has a class type, the conversion copy-initializes a temporary 723 // of type T from the glvalue and the result of the conversion 724 // is a prvalue for the temporary. 725 // FIXME: add some way to gate this entire thing for correctness in 726 // potentially potentially evaluated contexts. 727 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 728 ExprResult Temp = PerformCopyInitialization( 729 InitializedEntity::InitializeTemporary(E->getType()), 730 E->getExprLoc(), 731 Owned(E)); 732 if (Temp.isInvalid()) 733 return ExprError(); 734 E = Temp.get(); 735 } 736 737 return Owned(E); 738 } 739 740 /// Determine the degree of POD-ness for an expression. 741 /// Incomplete types are considered POD, since this check can be performed 742 /// when we're in an unevaluated context. 743 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 744 if (Ty->isIncompleteType()) { 745 // C++11 [expr.call]p7: 746 // After these conversions, if the argument does not have arithmetic, 747 // enumeration, pointer, pointer to member, or class type, the program 748 // is ill-formed. 749 // 750 // Since we've already performed array-to-pointer and function-to-pointer 751 // decay, the only such type in C++ is cv void. This also handles 752 // initializer lists as variadic arguments. 753 if (Ty->isVoidType()) 754 return VAK_Invalid; 755 756 if (Ty->isObjCObjectType()) 757 return VAK_Invalid; 758 return VAK_Valid; 759 } 760 761 if (Ty.isCXX98PODType(Context)) 762 return VAK_Valid; 763 764 // C++11 [expr.call]p7: 765 // Passing a potentially-evaluated argument of class type (Clause 9) 766 // having a non-trivial copy constructor, a non-trivial move constructor, 767 // or a non-trivial destructor, with no corresponding parameter, 768 // is conditionally-supported with implementation-defined semantics. 769 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 770 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 771 if (!Record->hasNonTrivialCopyConstructor() && 772 !Record->hasNonTrivialMoveConstructor() && 773 !Record->hasNonTrivialDestructor()) 774 return VAK_ValidInCXX11; 775 776 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 777 return VAK_Valid; 778 779 if (Ty->isObjCObjectType()) 780 return VAK_Invalid; 781 782 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 783 // permitted to reject them. We should consider doing so. 784 return VAK_Undefined; 785 } 786 787 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 788 // Don't allow one to pass an Objective-C interface to a vararg. 789 const QualType &Ty = E->getType(); 790 VarArgKind VAK = isValidVarArgType(Ty); 791 792 // Complain about passing non-POD types through varargs. 793 switch (VAK) { 794 case VAK_Valid: 795 break; 796 797 case VAK_ValidInCXX11: 798 DiagRuntimeBehavior( 799 E->getLocStart(), 0, 800 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 801 << E->getType() << CT); 802 break; 803 804 case VAK_Undefined: 805 DiagRuntimeBehavior( 806 E->getLocStart(), 0, 807 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 808 << getLangOpts().CPlusPlus11 << Ty << CT); 809 break; 810 811 case VAK_Invalid: 812 if (Ty->isObjCObjectType()) 813 DiagRuntimeBehavior( 814 E->getLocStart(), 0, 815 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 816 << Ty << CT); 817 else 818 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 819 << isa<InitListExpr>(E) << Ty << CT; 820 break; 821 } 822 } 823 824 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 825 /// will create a trap if the resulting type is not a POD type. 826 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 827 FunctionDecl *FDecl) { 828 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 829 // Strip the unbridged-cast placeholder expression off, if applicable. 830 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 831 (CT == VariadicMethod || 832 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 833 E = stripARCUnbridgedCast(E); 834 835 // Otherwise, do normal placeholder checking. 836 } else { 837 ExprResult ExprRes = CheckPlaceholderExpr(E); 838 if (ExprRes.isInvalid()) 839 return ExprError(); 840 E = ExprRes.take(); 841 } 842 } 843 844 ExprResult ExprRes = DefaultArgumentPromotion(E); 845 if (ExprRes.isInvalid()) 846 return ExprError(); 847 E = ExprRes.take(); 848 849 // Diagnostics regarding non-POD argument types are 850 // emitted along with format string checking in Sema::CheckFunctionCall(). 851 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 852 // Turn this into a trap. 853 CXXScopeSpec SS; 854 SourceLocation TemplateKWLoc; 855 UnqualifiedId Name; 856 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 857 E->getLocStart()); 858 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 859 Name, true, false); 860 if (TrapFn.isInvalid()) 861 return ExprError(); 862 863 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 864 E->getLocStart(), None, 865 E->getLocEnd()); 866 if (Call.isInvalid()) 867 return ExprError(); 868 869 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 870 Call.get(), E); 871 if (Comma.isInvalid()) 872 return ExprError(); 873 return Comma.get(); 874 } 875 876 if (!getLangOpts().CPlusPlus && 877 RequireCompleteType(E->getExprLoc(), E->getType(), 878 diag::err_call_incomplete_argument)) 879 return ExprError(); 880 881 return Owned(E); 882 } 883 884 /// \brief Converts an integer to complex float type. Helper function of 885 /// UsualArithmeticConversions() 886 /// 887 /// \return false if the integer expression is an integer type and is 888 /// successfully converted to the complex type. 889 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 890 ExprResult &ComplexExpr, 891 QualType IntTy, 892 QualType ComplexTy, 893 bool SkipCast) { 894 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 895 if (SkipCast) return false; 896 if (IntTy->isIntegerType()) { 897 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 898 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 899 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 900 CK_FloatingRealToComplex); 901 } else { 902 assert(IntTy->isComplexIntegerType()); 903 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 904 CK_IntegralComplexToFloatingComplex); 905 } 906 return false; 907 } 908 909 /// \brief Takes two complex float types and converts them to the same type. 910 /// Helper function of UsualArithmeticConversions() 911 static QualType 912 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 913 ExprResult &RHS, QualType LHSType, 914 QualType RHSType, 915 bool IsCompAssign) { 916 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 917 918 if (order < 0) { 919 // _Complex float -> _Complex double 920 if (!IsCompAssign) 921 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 922 return RHSType; 923 } 924 if (order > 0) 925 // _Complex float -> _Complex double 926 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 927 return LHSType; 928 } 929 930 /// \brief Converts otherExpr to complex float and promotes complexExpr if 931 /// necessary. Helper function of UsualArithmeticConversions() 932 static QualType handleOtherComplexFloatConversion(Sema &S, 933 ExprResult &ComplexExpr, 934 ExprResult &OtherExpr, 935 QualType ComplexTy, 936 QualType OtherTy, 937 bool ConvertComplexExpr, 938 bool ConvertOtherExpr) { 939 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 940 941 // If just the complexExpr is complex, the otherExpr needs to be converted, 942 // and the complexExpr might need to be promoted. 943 if (order > 0) { // complexExpr is wider 944 // float -> _Complex double 945 if (ConvertOtherExpr) { 946 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 947 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 948 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 949 CK_FloatingRealToComplex); 950 } 951 return ComplexTy; 952 } 953 954 // otherTy is at least as wide. Find its corresponding complex type. 955 QualType result = (order == 0 ? ComplexTy : 956 S.Context.getComplexType(OtherTy)); 957 958 // double -> _Complex double 959 if (ConvertOtherExpr) 960 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 961 CK_FloatingRealToComplex); 962 963 // _Complex float -> _Complex double 964 if (ConvertComplexExpr && order < 0) 965 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 966 CK_FloatingComplexCast); 967 968 return result; 969 } 970 971 /// \brief Handle arithmetic conversion with complex types. Helper function of 972 /// UsualArithmeticConversions() 973 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 974 ExprResult &RHS, QualType LHSType, 975 QualType RHSType, 976 bool IsCompAssign) { 977 // if we have an integer operand, the result is the complex type. 978 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 979 /*skipCast*/false)) 980 return LHSType; 981 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 982 /*skipCast*/IsCompAssign)) 983 return RHSType; 984 985 // This handles complex/complex, complex/float, or float/complex. 986 // When both operands are complex, the shorter operand is converted to the 987 // type of the longer, and that is the type of the result. This corresponds 988 // to what is done when combining two real floating-point operands. 989 // The fun begins when size promotion occur across type domains. 990 // From H&S 6.3.4: When one operand is complex and the other is a real 991 // floating-point type, the less precise type is converted, within it's 992 // real or complex domain, to the precision of the other type. For example, 993 // when combining a "long double" with a "double _Complex", the 994 // "double _Complex" is promoted to "long double _Complex". 995 996 bool LHSComplexFloat = LHSType->isComplexType(); 997 bool RHSComplexFloat = RHSType->isComplexType(); 998 999 // If both are complex, just cast to the more precise type. 1000 if (LHSComplexFloat && RHSComplexFloat) 1001 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1002 LHSType, RHSType, 1003 IsCompAssign); 1004 1005 // If only one operand is complex, promote it if necessary and convert the 1006 // other operand to complex. 1007 if (LHSComplexFloat) 1008 return handleOtherComplexFloatConversion( 1009 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1010 /*convertOtherExpr*/ true); 1011 1012 assert(RHSComplexFloat); 1013 return handleOtherComplexFloatConversion( 1014 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1015 /*convertOtherExpr*/ !IsCompAssign); 1016 } 1017 1018 /// \brief Hande arithmetic conversion from integer to float. Helper function 1019 /// of UsualArithmeticConversions() 1020 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1021 ExprResult &IntExpr, 1022 QualType FloatTy, QualType IntTy, 1023 bool ConvertFloat, bool ConvertInt) { 1024 if (IntTy->isIntegerType()) { 1025 if (ConvertInt) 1026 // Convert intExpr to the lhs floating point type. 1027 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 1028 CK_IntegralToFloating); 1029 return FloatTy; 1030 } 1031 1032 // Convert both sides to the appropriate complex float. 1033 assert(IntTy->isComplexIntegerType()); 1034 QualType result = S.Context.getComplexType(FloatTy); 1035 1036 // _Complex int -> _Complex float 1037 if (ConvertInt) 1038 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 1039 CK_IntegralComplexToFloatingComplex); 1040 1041 // float -> _Complex float 1042 if (ConvertFloat) 1043 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1044 CK_FloatingRealToComplex); 1045 1046 return result; 1047 } 1048 1049 /// \brief Handle arithmethic conversion with floating point types. Helper 1050 /// function of UsualArithmeticConversions() 1051 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1052 ExprResult &RHS, QualType LHSType, 1053 QualType RHSType, bool IsCompAssign) { 1054 bool LHSFloat = LHSType->isRealFloatingType(); 1055 bool RHSFloat = RHSType->isRealFloatingType(); 1056 1057 // If we have two real floating types, convert the smaller operand 1058 // to the bigger result. 1059 if (LHSFloat && RHSFloat) { 1060 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1061 if (order > 0) { 1062 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1063 return LHSType; 1064 } 1065 1066 assert(order < 0 && "illegal float comparison"); 1067 if (!IsCompAssign) 1068 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1069 return RHSType; 1070 } 1071 1072 if (LHSFloat) 1073 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1074 /*convertFloat=*/!IsCompAssign, 1075 /*convertInt=*/ true); 1076 assert(RHSFloat); 1077 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1078 /*convertInt=*/ true, 1079 /*convertFloat=*/!IsCompAssign); 1080 } 1081 1082 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1083 1084 namespace { 1085 /// These helper callbacks are placed in an anonymous namespace to 1086 /// permit their use as function template parameters. 1087 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1088 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1089 } 1090 1091 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1092 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1093 CK_IntegralComplexCast); 1094 } 1095 } 1096 1097 /// \brief Handle integer arithmetic conversions. Helper function of 1098 /// UsualArithmeticConversions() 1099 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1100 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1101 ExprResult &RHS, QualType LHSType, 1102 QualType RHSType, bool IsCompAssign) { 1103 // The rules for this case are in C99 6.3.1.8 1104 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1105 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1106 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1107 if (LHSSigned == RHSSigned) { 1108 // Same signedness; use the higher-ranked type 1109 if (order >= 0) { 1110 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1111 return LHSType; 1112 } else if (!IsCompAssign) 1113 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1114 return RHSType; 1115 } else if (order != (LHSSigned ? 1 : -1)) { 1116 // The unsigned type has greater than or equal rank to the 1117 // signed type, so use the unsigned type 1118 if (RHSSigned) { 1119 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1120 return LHSType; 1121 } else if (!IsCompAssign) 1122 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1123 return RHSType; 1124 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1125 // The two types are different widths; if we are here, that 1126 // means the signed type is larger than the unsigned type, so 1127 // use the signed type. 1128 if (LHSSigned) { 1129 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1130 return LHSType; 1131 } else if (!IsCompAssign) 1132 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1133 return RHSType; 1134 } else { 1135 // The signed type is higher-ranked than the unsigned type, 1136 // but isn't actually any bigger (like unsigned int and long 1137 // on most 32-bit systems). Use the unsigned type corresponding 1138 // to the signed type. 1139 QualType result = 1140 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1141 RHS = (*doRHSCast)(S, RHS.take(), result); 1142 if (!IsCompAssign) 1143 LHS = (*doLHSCast)(S, LHS.take(), result); 1144 return result; 1145 } 1146 } 1147 1148 /// \brief Handle conversions with GCC complex int extension. Helper function 1149 /// of UsualArithmeticConversions() 1150 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1151 ExprResult &RHS, QualType LHSType, 1152 QualType RHSType, 1153 bool IsCompAssign) { 1154 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1155 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1156 1157 if (LHSComplexInt && RHSComplexInt) { 1158 QualType LHSEltType = LHSComplexInt->getElementType(); 1159 QualType RHSEltType = RHSComplexInt->getElementType(); 1160 QualType ScalarType = 1161 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1162 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1163 1164 return S.Context.getComplexType(ScalarType); 1165 } 1166 1167 if (LHSComplexInt) { 1168 QualType LHSEltType = LHSComplexInt->getElementType(); 1169 QualType ScalarType = 1170 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1171 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1172 QualType ComplexType = S.Context.getComplexType(ScalarType); 1173 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1174 CK_IntegralRealToComplex); 1175 1176 return ComplexType; 1177 } 1178 1179 assert(RHSComplexInt); 1180 1181 QualType RHSEltType = RHSComplexInt->getElementType(); 1182 QualType ScalarType = 1183 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1184 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1185 QualType ComplexType = S.Context.getComplexType(ScalarType); 1186 1187 if (!IsCompAssign) 1188 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1189 CK_IntegralRealToComplex); 1190 return ComplexType; 1191 } 1192 1193 /// UsualArithmeticConversions - Performs various conversions that are common to 1194 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1195 /// routine returns the first non-arithmetic type found. The client is 1196 /// responsible for emitting appropriate error diagnostics. 1197 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1198 bool IsCompAssign) { 1199 if (!IsCompAssign) { 1200 LHS = UsualUnaryConversions(LHS.take()); 1201 if (LHS.isInvalid()) 1202 return QualType(); 1203 } 1204 1205 RHS = UsualUnaryConversions(RHS.take()); 1206 if (RHS.isInvalid()) 1207 return QualType(); 1208 1209 // For conversion purposes, we ignore any qualifiers. 1210 // For example, "const float" and "float" are equivalent. 1211 QualType LHSType = 1212 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1213 QualType RHSType = 1214 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1215 1216 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1217 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1218 LHSType = AtomicLHS->getValueType(); 1219 1220 // If both types are identical, no conversion is needed. 1221 if (LHSType == RHSType) 1222 return LHSType; 1223 1224 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1225 // The caller can deal with this (e.g. pointer + int). 1226 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1227 return QualType(); 1228 1229 // Apply unary and bitfield promotions to the LHS's type. 1230 QualType LHSUnpromotedType = LHSType; 1231 if (LHSType->isPromotableIntegerType()) 1232 LHSType = Context.getPromotedIntegerType(LHSType); 1233 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1234 if (!LHSBitfieldPromoteTy.isNull()) 1235 LHSType = LHSBitfieldPromoteTy; 1236 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1237 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1238 1239 // If both types are identical, no conversion is needed. 1240 if (LHSType == RHSType) 1241 return LHSType; 1242 1243 // At this point, we have two different arithmetic types. 1244 1245 // Handle complex types first (C99 6.3.1.8p1). 1246 if (LHSType->isComplexType() || RHSType->isComplexType()) 1247 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1248 IsCompAssign); 1249 1250 // Now handle "real" floating types (i.e. float, double, long double). 1251 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1252 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1253 IsCompAssign); 1254 1255 // Handle GCC complex int extension. 1256 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1257 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1258 IsCompAssign); 1259 1260 // Finally, we have two differing integer types. 1261 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1262 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1263 } 1264 1265 1266 //===----------------------------------------------------------------------===// 1267 // Semantic Analysis for various Expression Types 1268 //===----------------------------------------------------------------------===// 1269 1270 1271 ExprResult 1272 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1273 SourceLocation DefaultLoc, 1274 SourceLocation RParenLoc, 1275 Expr *ControllingExpr, 1276 ArrayRef<ParsedType> ArgTypes, 1277 ArrayRef<Expr *> ArgExprs) { 1278 unsigned NumAssocs = ArgTypes.size(); 1279 assert(NumAssocs == ArgExprs.size()); 1280 1281 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1282 for (unsigned i = 0; i < NumAssocs; ++i) { 1283 if (ArgTypes[i]) 1284 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1285 else 1286 Types[i] = 0; 1287 } 1288 1289 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1290 ControllingExpr, 1291 llvm::makeArrayRef(Types, NumAssocs), 1292 ArgExprs); 1293 delete [] Types; 1294 return ER; 1295 } 1296 1297 ExprResult 1298 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1299 SourceLocation DefaultLoc, 1300 SourceLocation RParenLoc, 1301 Expr *ControllingExpr, 1302 ArrayRef<TypeSourceInfo *> Types, 1303 ArrayRef<Expr *> Exprs) { 1304 unsigned NumAssocs = Types.size(); 1305 assert(NumAssocs == Exprs.size()); 1306 if (ControllingExpr->getType()->isPlaceholderType()) { 1307 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1308 if (result.isInvalid()) return ExprError(); 1309 ControllingExpr = result.take(); 1310 } 1311 1312 bool TypeErrorFound = false, 1313 IsResultDependent = ControllingExpr->isTypeDependent(), 1314 ContainsUnexpandedParameterPack 1315 = ControllingExpr->containsUnexpandedParameterPack(); 1316 1317 for (unsigned i = 0; i < NumAssocs; ++i) { 1318 if (Exprs[i]->containsUnexpandedParameterPack()) 1319 ContainsUnexpandedParameterPack = true; 1320 1321 if (Types[i]) { 1322 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1323 ContainsUnexpandedParameterPack = true; 1324 1325 if (Types[i]->getType()->isDependentType()) { 1326 IsResultDependent = true; 1327 } else { 1328 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1329 // complete object type other than a variably modified type." 1330 unsigned D = 0; 1331 if (Types[i]->getType()->isIncompleteType()) 1332 D = diag::err_assoc_type_incomplete; 1333 else if (!Types[i]->getType()->isObjectType()) 1334 D = diag::err_assoc_type_nonobject; 1335 else if (Types[i]->getType()->isVariablyModifiedType()) 1336 D = diag::err_assoc_type_variably_modified; 1337 1338 if (D != 0) { 1339 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1340 << Types[i]->getTypeLoc().getSourceRange() 1341 << Types[i]->getType(); 1342 TypeErrorFound = true; 1343 } 1344 1345 // C11 6.5.1.1p2 "No two generic associations in the same generic 1346 // selection shall specify compatible types." 1347 for (unsigned j = i+1; j < NumAssocs; ++j) 1348 if (Types[j] && !Types[j]->getType()->isDependentType() && 1349 Context.typesAreCompatible(Types[i]->getType(), 1350 Types[j]->getType())) { 1351 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1352 diag::err_assoc_compatible_types) 1353 << Types[j]->getTypeLoc().getSourceRange() 1354 << Types[j]->getType() 1355 << Types[i]->getType(); 1356 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1357 diag::note_compat_assoc) 1358 << Types[i]->getTypeLoc().getSourceRange() 1359 << Types[i]->getType(); 1360 TypeErrorFound = true; 1361 } 1362 } 1363 } 1364 } 1365 if (TypeErrorFound) 1366 return ExprError(); 1367 1368 // If we determined that the generic selection is result-dependent, don't 1369 // try to compute the result expression. 1370 if (IsResultDependent) 1371 return Owned(new (Context) GenericSelectionExpr( 1372 Context, KeyLoc, ControllingExpr, 1373 Types, Exprs, 1374 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1375 1376 SmallVector<unsigned, 1> CompatIndices; 1377 unsigned DefaultIndex = -1U; 1378 for (unsigned i = 0; i < NumAssocs; ++i) { 1379 if (!Types[i]) 1380 DefaultIndex = i; 1381 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1382 Types[i]->getType())) 1383 CompatIndices.push_back(i); 1384 } 1385 1386 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1387 // type compatible with at most one of the types named in its generic 1388 // association list." 1389 if (CompatIndices.size() > 1) { 1390 // We strip parens here because the controlling expression is typically 1391 // parenthesized in macro definitions. 1392 ControllingExpr = ControllingExpr->IgnoreParens(); 1393 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1394 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1395 << (unsigned) CompatIndices.size(); 1396 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1397 E = CompatIndices.end(); I != E; ++I) { 1398 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1399 diag::note_compat_assoc) 1400 << Types[*I]->getTypeLoc().getSourceRange() 1401 << Types[*I]->getType(); 1402 } 1403 return ExprError(); 1404 } 1405 1406 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1407 // its controlling expression shall have type compatible with exactly one of 1408 // the types named in its generic association list." 1409 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1410 // We strip parens here because the controlling expression is typically 1411 // parenthesized in macro definitions. 1412 ControllingExpr = ControllingExpr->IgnoreParens(); 1413 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1414 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1415 return ExprError(); 1416 } 1417 1418 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1419 // type name that is compatible with the type of the controlling expression, 1420 // then the result expression of the generic selection is the expression 1421 // in that generic association. Otherwise, the result expression of the 1422 // generic selection is the expression in the default generic association." 1423 unsigned ResultIndex = 1424 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1425 1426 return Owned(new (Context) GenericSelectionExpr( 1427 Context, KeyLoc, ControllingExpr, 1428 Types, Exprs, 1429 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1430 ResultIndex)); 1431 } 1432 1433 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1434 /// location of the token and the offset of the ud-suffix within it. 1435 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1436 unsigned Offset) { 1437 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1438 S.getLangOpts()); 1439 } 1440 1441 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1442 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1443 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1444 IdentifierInfo *UDSuffix, 1445 SourceLocation UDSuffixLoc, 1446 ArrayRef<Expr*> Args, 1447 SourceLocation LitEndLoc) { 1448 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1449 1450 QualType ArgTy[2]; 1451 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1452 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1453 if (ArgTy[ArgIdx]->isArrayType()) 1454 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1455 } 1456 1457 DeclarationName OpName = 1458 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1459 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1460 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1461 1462 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1463 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1464 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1465 return ExprError(); 1466 1467 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1468 } 1469 1470 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1471 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1472 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1473 /// multiple tokens. However, the common case is that StringToks points to one 1474 /// string. 1475 /// 1476 ExprResult 1477 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1478 Scope *UDLScope) { 1479 assert(NumStringToks && "Must have at least one string!"); 1480 1481 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1482 if (Literal.hadError) 1483 return ExprError(); 1484 1485 SmallVector<SourceLocation, 4> StringTokLocs; 1486 for (unsigned i = 0; i != NumStringToks; ++i) 1487 StringTokLocs.push_back(StringToks[i].getLocation()); 1488 1489 QualType StrTy = Context.CharTy; 1490 if (Literal.isWide()) 1491 StrTy = Context.getWideCharType(); 1492 else if (Literal.isUTF16()) 1493 StrTy = Context.Char16Ty; 1494 else if (Literal.isUTF32()) 1495 StrTy = Context.Char32Ty; 1496 else if (Literal.isPascal()) 1497 StrTy = Context.UnsignedCharTy; 1498 1499 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1500 if (Literal.isWide()) 1501 Kind = StringLiteral::Wide; 1502 else if (Literal.isUTF8()) 1503 Kind = StringLiteral::UTF8; 1504 else if (Literal.isUTF16()) 1505 Kind = StringLiteral::UTF16; 1506 else if (Literal.isUTF32()) 1507 Kind = StringLiteral::UTF32; 1508 1509 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1510 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1511 StrTy.addConst(); 1512 1513 // Get an array type for the string, according to C99 6.4.5. This includes 1514 // the nul terminator character as well as the string length for pascal 1515 // strings. 1516 StrTy = Context.getConstantArrayType(StrTy, 1517 llvm::APInt(32, Literal.GetNumStringChars()+1), 1518 ArrayType::Normal, 0); 1519 1520 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1521 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1522 Kind, Literal.Pascal, StrTy, 1523 &StringTokLocs[0], 1524 StringTokLocs.size()); 1525 if (Literal.getUDSuffix().empty()) 1526 return Owned(Lit); 1527 1528 // We're building a user-defined literal. 1529 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1530 SourceLocation UDSuffixLoc = 1531 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1532 Literal.getUDSuffixOffset()); 1533 1534 // Make sure we're allowed user-defined literals here. 1535 if (!UDLScope) 1536 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1537 1538 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1539 // operator "" X (str, len) 1540 QualType SizeType = Context.getSizeType(); 1541 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1542 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1543 StringTokLocs[0]); 1544 Expr *Args[] = { Lit, LenArg }; 1545 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1546 Args, StringTokLocs.back()); 1547 } 1548 1549 ExprResult 1550 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1551 SourceLocation Loc, 1552 const CXXScopeSpec *SS) { 1553 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1554 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1555 } 1556 1557 /// BuildDeclRefExpr - Build an expression that references a 1558 /// declaration that does not require a closure capture. 1559 ExprResult 1560 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1561 const DeclarationNameInfo &NameInfo, 1562 const CXXScopeSpec *SS, NamedDecl *FoundD, 1563 const TemplateArgumentListInfo *TemplateArgs) { 1564 if (getLangOpts().CUDA) 1565 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1566 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1567 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1568 CalleeTarget = IdentifyCUDATarget(Callee); 1569 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1570 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1571 << CalleeTarget << D->getIdentifier() << CallerTarget; 1572 Diag(D->getLocation(), diag::note_previous_decl) 1573 << D->getIdentifier(); 1574 return ExprError(); 1575 } 1576 } 1577 1578 bool refersToEnclosingScope = 1579 (CurContext != D->getDeclContext() && 1580 D->getDeclContext()->isFunctionOrMethod()); 1581 1582 DeclRefExpr *E; 1583 if (isa<VarTemplateSpecializationDecl>(D)) { 1584 VarTemplateSpecializationDecl *VarSpec = 1585 cast<VarTemplateSpecializationDecl>(D); 1586 1587 E = DeclRefExpr::Create( 1588 Context, 1589 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1590 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1591 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1592 } else { 1593 assert(!TemplateArgs && "No template arguments for non-variable" 1594 " template specialization referrences"); 1595 E = DeclRefExpr::Create( 1596 Context, 1597 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1598 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1599 } 1600 1601 MarkDeclRefReferenced(E); 1602 1603 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1604 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1605 DiagnosticsEngine::Level Level = 1606 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1607 E->getLocStart()); 1608 if (Level != DiagnosticsEngine::Ignored) 1609 recordUseOfEvaluatedWeak(E); 1610 } 1611 1612 // Just in case we're building an illegal pointer-to-member. 1613 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1614 if (FD && FD->isBitField()) 1615 E->setObjectKind(OK_BitField); 1616 1617 return Owned(E); 1618 } 1619 1620 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1621 /// possibly a list of template arguments. 1622 /// 1623 /// If this produces template arguments, it is permitted to call 1624 /// DecomposeTemplateName. 1625 /// 1626 /// This actually loses a lot of source location information for 1627 /// non-standard name kinds; we should consider preserving that in 1628 /// some way. 1629 void 1630 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1631 TemplateArgumentListInfo &Buffer, 1632 DeclarationNameInfo &NameInfo, 1633 const TemplateArgumentListInfo *&TemplateArgs) { 1634 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1635 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1636 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1637 1638 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1639 Id.TemplateId->NumArgs); 1640 translateTemplateArguments(TemplateArgsPtr, Buffer); 1641 1642 TemplateName TName = Id.TemplateId->Template.get(); 1643 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1644 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1645 TemplateArgs = &Buffer; 1646 } else { 1647 NameInfo = GetNameFromUnqualifiedId(Id); 1648 TemplateArgs = 0; 1649 } 1650 } 1651 1652 /// Diagnose an empty lookup. 1653 /// 1654 /// \return false if new lookup candidates were found 1655 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1656 CorrectionCandidateCallback &CCC, 1657 TemplateArgumentListInfo *ExplicitTemplateArgs, 1658 llvm::ArrayRef<Expr *> Args) { 1659 DeclarationName Name = R.getLookupName(); 1660 1661 unsigned diagnostic = diag::err_undeclared_var_use; 1662 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1663 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1664 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1665 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1666 diagnostic = diag::err_undeclared_use; 1667 diagnostic_suggest = diag::err_undeclared_use_suggest; 1668 } 1669 1670 // If the original lookup was an unqualified lookup, fake an 1671 // unqualified lookup. This is useful when (for example) the 1672 // original lookup would not have found something because it was a 1673 // dependent name. 1674 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1675 ? CurContext : 0; 1676 while (DC) { 1677 if (isa<CXXRecordDecl>(DC)) { 1678 LookupQualifiedName(R, DC); 1679 1680 if (!R.empty()) { 1681 // Don't give errors about ambiguities in this lookup. 1682 R.suppressDiagnostics(); 1683 1684 // During a default argument instantiation the CurContext points 1685 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1686 // function parameter list, hence add an explicit check. 1687 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1688 ActiveTemplateInstantiations.back().Kind == 1689 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1690 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1691 bool isInstance = CurMethod && 1692 CurMethod->isInstance() && 1693 DC == CurMethod->getParent() && !isDefaultArgument; 1694 1695 1696 // Give a code modification hint to insert 'this->'. 1697 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1698 // Actually quite difficult! 1699 if (getLangOpts().MicrosoftMode) 1700 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1701 if (isInstance) { 1702 Diag(R.getNameLoc(), diagnostic) << Name 1703 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1704 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1705 CallsUndergoingInstantiation.back()->getCallee()); 1706 1707 CXXMethodDecl *DepMethod; 1708 if (CurMethod->isDependentContext()) 1709 DepMethod = CurMethod; 1710 else if (CurMethod->getTemplatedKind() == 1711 FunctionDecl::TK_FunctionTemplateSpecialization) 1712 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1713 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1714 else 1715 DepMethod = cast<CXXMethodDecl>( 1716 CurMethod->getInstantiatedFromMemberFunction()); 1717 assert(DepMethod && "No template pattern found"); 1718 1719 QualType DepThisType = DepMethod->getThisType(Context); 1720 CheckCXXThisCapture(R.getNameLoc()); 1721 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1722 R.getNameLoc(), DepThisType, false); 1723 TemplateArgumentListInfo TList; 1724 if (ULE->hasExplicitTemplateArgs()) 1725 ULE->copyTemplateArgumentsInto(TList); 1726 1727 CXXScopeSpec SS; 1728 SS.Adopt(ULE->getQualifierLoc()); 1729 CXXDependentScopeMemberExpr *DepExpr = 1730 CXXDependentScopeMemberExpr::Create( 1731 Context, DepThis, DepThisType, true, SourceLocation(), 1732 SS.getWithLocInContext(Context), 1733 ULE->getTemplateKeywordLoc(), 0, 1734 R.getLookupNameInfo(), 1735 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1736 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1737 } else { 1738 Diag(R.getNameLoc(), diagnostic) << Name; 1739 } 1740 1741 // Do we really want to note all of these? 1742 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1743 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1744 1745 // Return true if we are inside a default argument instantiation 1746 // and the found name refers to an instance member function, otherwise 1747 // the function calling DiagnoseEmptyLookup will try to create an 1748 // implicit member call and this is wrong for default argument. 1749 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1750 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1751 return true; 1752 } 1753 1754 // Tell the callee to try to recover. 1755 return false; 1756 } 1757 1758 R.clear(); 1759 } 1760 1761 // In Microsoft mode, if we are performing lookup from within a friend 1762 // function definition declared at class scope then we must set 1763 // DC to the lexical parent to be able to search into the parent 1764 // class. 1765 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1766 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1767 DC->getLexicalParent()->isRecord()) 1768 DC = DC->getLexicalParent(); 1769 else 1770 DC = DC->getParent(); 1771 } 1772 1773 // We didn't find anything, so try to correct for a typo. 1774 TypoCorrection Corrected; 1775 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1776 S, &SS, CCC))) { 1777 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1778 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1779 bool droppedSpecifier = 1780 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1781 R.setLookupName(Corrected.getCorrection()); 1782 1783 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1784 if (Corrected.isOverloaded()) { 1785 OverloadCandidateSet OCS(R.getNameLoc()); 1786 OverloadCandidateSet::iterator Best; 1787 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1788 CDEnd = Corrected.end(); 1789 CD != CDEnd; ++CD) { 1790 if (FunctionTemplateDecl *FTD = 1791 dyn_cast<FunctionTemplateDecl>(*CD)) 1792 AddTemplateOverloadCandidate( 1793 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1794 Args, OCS); 1795 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1796 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1797 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1798 Args, OCS); 1799 } 1800 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1801 case OR_Success: 1802 ND = Best->Function; 1803 break; 1804 default: 1805 break; 1806 } 1807 } 1808 R.addDecl(ND); 1809 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1810 if (SS.isEmpty()) 1811 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1812 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1813 else 1814 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1815 << Name << computeDeclContext(SS, false) << droppedSpecifier 1816 << CorrectedQuotedStr << SS.getRange() 1817 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 1818 CorrectedStr); 1819 1820 unsigned diag = isa<ImplicitParamDecl>(ND) 1821 ? diag::note_implicit_param_decl 1822 : diag::note_previous_decl; 1823 1824 Diag(ND->getLocation(), diag) 1825 << CorrectedQuotedStr; 1826 1827 // Tell the callee to try to recover. 1828 return false; 1829 } 1830 1831 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1832 // FIXME: If we ended up with a typo for a type name or 1833 // Objective-C class name, we're in trouble because the parser 1834 // is in the wrong place to recover. Suggest the typo 1835 // correction, but don't make it a fix-it since we're not going 1836 // to recover well anyway. 1837 if (SS.isEmpty()) 1838 Diag(R.getNameLoc(), diagnostic_suggest) 1839 << Name << CorrectedQuotedStr; 1840 else 1841 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1842 << Name << computeDeclContext(SS, false) << droppedSpecifier 1843 << CorrectedQuotedStr << SS.getRange(); 1844 1845 // Don't try to recover; it won't work. 1846 return true; 1847 } 1848 } else { 1849 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1850 // because we aren't able to recover. 1851 if (SS.isEmpty()) 1852 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1853 else 1854 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1855 << Name << computeDeclContext(SS, false) << droppedSpecifier 1856 << CorrectedQuotedStr << SS.getRange(); 1857 return true; 1858 } 1859 } 1860 R.clear(); 1861 1862 // Emit a special diagnostic for failed member lookups. 1863 // FIXME: computing the declaration context might fail here (?) 1864 if (!SS.isEmpty()) { 1865 Diag(R.getNameLoc(), diag::err_no_member) 1866 << Name << computeDeclContext(SS, false) 1867 << SS.getRange(); 1868 return true; 1869 } 1870 1871 // Give up, we can't recover. 1872 Diag(R.getNameLoc(), diagnostic) << Name; 1873 return true; 1874 } 1875 1876 ExprResult Sema::ActOnIdExpression(Scope *S, 1877 CXXScopeSpec &SS, 1878 SourceLocation TemplateKWLoc, 1879 UnqualifiedId &Id, 1880 bool HasTrailingLParen, 1881 bool IsAddressOfOperand, 1882 CorrectionCandidateCallback *CCC, 1883 bool IsInlineAsmIdentifier) { 1884 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1885 "cannot be direct & operand and have a trailing lparen"); 1886 if (SS.isInvalid()) 1887 return ExprError(); 1888 1889 TemplateArgumentListInfo TemplateArgsBuffer; 1890 1891 // Decompose the UnqualifiedId into the following data. 1892 DeclarationNameInfo NameInfo; 1893 const TemplateArgumentListInfo *TemplateArgs; 1894 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1895 1896 DeclarationName Name = NameInfo.getName(); 1897 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1898 SourceLocation NameLoc = NameInfo.getLoc(); 1899 1900 // C++ [temp.dep.expr]p3: 1901 // An id-expression is type-dependent if it contains: 1902 // -- an identifier that was declared with a dependent type, 1903 // (note: handled after lookup) 1904 // -- a template-id that is dependent, 1905 // (note: handled in BuildTemplateIdExpr) 1906 // -- a conversion-function-id that specifies a dependent type, 1907 // -- a nested-name-specifier that contains a class-name that 1908 // names a dependent type. 1909 // Determine whether this is a member of an unknown specialization; 1910 // we need to handle these differently. 1911 bool DependentID = false; 1912 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1913 Name.getCXXNameType()->isDependentType()) { 1914 DependentID = true; 1915 } else if (SS.isSet()) { 1916 if (DeclContext *DC = computeDeclContext(SS, false)) { 1917 if (RequireCompleteDeclContext(SS, DC)) 1918 return ExprError(); 1919 } else { 1920 DependentID = true; 1921 } 1922 } 1923 1924 if (DependentID) 1925 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1926 IsAddressOfOperand, TemplateArgs); 1927 1928 // Perform the required lookup. 1929 LookupResult R(*this, NameInfo, 1930 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1931 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1932 if (TemplateArgs) { 1933 // Lookup the template name again to correctly establish the context in 1934 // which it was found. This is really unfortunate as we already did the 1935 // lookup to determine that it was a template name in the first place. If 1936 // this becomes a performance hit, we can work harder to preserve those 1937 // results until we get here but it's likely not worth it. 1938 bool MemberOfUnknownSpecialization; 1939 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1940 MemberOfUnknownSpecialization); 1941 1942 if (MemberOfUnknownSpecialization || 1943 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1944 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1945 IsAddressOfOperand, TemplateArgs); 1946 } else { 1947 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1948 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1949 1950 // If the result might be in a dependent base class, this is a dependent 1951 // id-expression. 1952 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1953 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1954 IsAddressOfOperand, TemplateArgs); 1955 1956 // If this reference is in an Objective-C method, then we need to do 1957 // some special Objective-C lookup, too. 1958 if (IvarLookupFollowUp) { 1959 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1960 if (E.isInvalid()) 1961 return ExprError(); 1962 1963 if (Expr *Ex = E.takeAs<Expr>()) 1964 return Owned(Ex); 1965 } 1966 } 1967 1968 if (R.isAmbiguous()) 1969 return ExprError(); 1970 1971 // Determine whether this name might be a candidate for 1972 // argument-dependent lookup. 1973 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1974 1975 if (R.empty() && !ADL) { 1976 1977 // Otherwise, this could be an implicitly declared function reference (legal 1978 // in C90, extension in C99, forbidden in C++). 1979 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1980 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1981 if (D) R.addDecl(D); 1982 } 1983 1984 // If this name wasn't predeclared and if this is not a function 1985 // call, diagnose the problem. 1986 if (R.empty()) { 1987 // In Microsoft mode, if we are inside a template class member function 1988 // whose parent class has dependent base classes, and we can't resolve 1989 // an identifier, then assume the identifier is type dependent. The 1990 // goal is to postpone name lookup to instantiation time to be able to 1991 // search into the type dependent base classes. 1992 if (getLangOpts().MicrosoftMode) { 1993 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 1994 if (MD && MD->getParent()->hasAnyDependentBases()) 1995 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1996 IsAddressOfOperand, TemplateArgs); 1997 } 1998 1999 // Don't diagnose an empty lookup for inline assmebly. 2000 if (IsInlineAsmIdentifier) 2001 return ExprError(); 2002 2003 CorrectionCandidateCallback DefaultValidator; 2004 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2005 return ExprError(); 2006 2007 assert(!R.empty() && 2008 "DiagnoseEmptyLookup returned false but added no results"); 2009 2010 // If we found an Objective-C instance variable, let 2011 // LookupInObjCMethod build the appropriate expression to 2012 // reference the ivar. 2013 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2014 R.clear(); 2015 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2016 // In a hopelessly buggy code, Objective-C instance variable 2017 // lookup fails and no expression will be built to reference it. 2018 if (!E.isInvalid() && !E.get()) 2019 return ExprError(); 2020 return E; 2021 } 2022 } 2023 } 2024 2025 // This is guaranteed from this point on. 2026 assert(!R.empty() || ADL); 2027 2028 // Check whether this might be a C++ implicit instance member access. 2029 // C++ [class.mfct.non-static]p3: 2030 // When an id-expression that is not part of a class member access 2031 // syntax and not used to form a pointer to member is used in the 2032 // body of a non-static member function of class X, if name lookup 2033 // resolves the name in the id-expression to a non-static non-type 2034 // member of some class C, the id-expression is transformed into a 2035 // class member access expression using (*this) as the 2036 // postfix-expression to the left of the . operator. 2037 // 2038 // But we don't actually need to do this for '&' operands if R 2039 // resolved to a function or overloaded function set, because the 2040 // expression is ill-formed if it actually works out to be a 2041 // non-static member function: 2042 // 2043 // C++ [expr.ref]p4: 2044 // Otherwise, if E1.E2 refers to a non-static member function. . . 2045 // [t]he expression can be used only as the left-hand operand of a 2046 // member function call. 2047 // 2048 // There are other safeguards against such uses, but it's important 2049 // to get this right here so that we don't end up making a 2050 // spuriously dependent expression if we're inside a dependent 2051 // instance method. 2052 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2053 bool MightBeImplicitMember; 2054 if (!IsAddressOfOperand) 2055 MightBeImplicitMember = true; 2056 else if (!SS.isEmpty()) 2057 MightBeImplicitMember = false; 2058 else if (R.isOverloadedResult()) 2059 MightBeImplicitMember = false; 2060 else if (R.isUnresolvableResult()) 2061 MightBeImplicitMember = true; 2062 else 2063 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2064 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2065 isa<MSPropertyDecl>(R.getFoundDecl()); 2066 2067 if (MightBeImplicitMember) 2068 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2069 R, TemplateArgs); 2070 } 2071 2072 if (TemplateArgs || TemplateKWLoc.isValid()) { 2073 2074 // In C++1y, if this is a variable template id, then check it 2075 // in BuildTemplateIdExpr(). 2076 // The single lookup result must be a variable template declaration. 2077 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2078 Id.TemplateId->Kind == TNK_Var_template) { 2079 assert(R.getAsSingle<VarTemplateDecl>() && 2080 "There should only be one declaration found."); 2081 } 2082 2083 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2084 } 2085 2086 return BuildDeclarationNameExpr(SS, R, ADL); 2087 } 2088 2089 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2090 /// declaration name, generally during template instantiation. 2091 /// There's a large number of things which don't need to be done along 2092 /// this path. 2093 ExprResult 2094 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2095 const DeclarationNameInfo &NameInfo, 2096 bool IsAddressOfOperand) { 2097 DeclContext *DC = computeDeclContext(SS, false); 2098 if (!DC) 2099 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2100 NameInfo, /*TemplateArgs=*/0); 2101 2102 if (RequireCompleteDeclContext(SS, DC)) 2103 return ExprError(); 2104 2105 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2106 LookupQualifiedName(R, DC); 2107 2108 if (R.isAmbiguous()) 2109 return ExprError(); 2110 2111 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2112 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2113 NameInfo, /*TemplateArgs=*/0); 2114 2115 if (R.empty()) { 2116 Diag(NameInfo.getLoc(), diag::err_no_member) 2117 << NameInfo.getName() << DC << SS.getRange(); 2118 return ExprError(); 2119 } 2120 2121 // Defend against this resolving to an implicit member access. We usually 2122 // won't get here if this might be a legitimate a class member (we end up in 2123 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2124 // a pointer-to-member or in an unevaluated context in C++11. 2125 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2126 return BuildPossibleImplicitMemberExpr(SS, 2127 /*TemplateKWLoc=*/SourceLocation(), 2128 R, /*TemplateArgs=*/0); 2129 2130 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2131 } 2132 2133 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2134 /// detected that we're currently inside an ObjC method. Perform some 2135 /// additional lookup. 2136 /// 2137 /// Ideally, most of this would be done by lookup, but there's 2138 /// actually quite a lot of extra work involved. 2139 /// 2140 /// Returns a null sentinel to indicate trivial success. 2141 ExprResult 2142 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2143 IdentifierInfo *II, bool AllowBuiltinCreation) { 2144 SourceLocation Loc = Lookup.getNameLoc(); 2145 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2146 2147 // Check for error condition which is already reported. 2148 if (!CurMethod) 2149 return ExprError(); 2150 2151 // There are two cases to handle here. 1) scoped lookup could have failed, 2152 // in which case we should look for an ivar. 2) scoped lookup could have 2153 // found a decl, but that decl is outside the current instance method (i.e. 2154 // a global variable). In these two cases, we do a lookup for an ivar with 2155 // this name, if the lookup sucedes, we replace it our current decl. 2156 2157 // If we're in a class method, we don't normally want to look for 2158 // ivars. But if we don't find anything else, and there's an 2159 // ivar, that's an error. 2160 bool IsClassMethod = CurMethod->isClassMethod(); 2161 2162 bool LookForIvars; 2163 if (Lookup.empty()) 2164 LookForIvars = true; 2165 else if (IsClassMethod) 2166 LookForIvars = false; 2167 else 2168 LookForIvars = (Lookup.isSingleResult() && 2169 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2170 ObjCInterfaceDecl *IFace = 0; 2171 if (LookForIvars) { 2172 IFace = CurMethod->getClassInterface(); 2173 ObjCInterfaceDecl *ClassDeclared; 2174 ObjCIvarDecl *IV = 0; 2175 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2176 // Diagnose using an ivar in a class method. 2177 if (IsClassMethod) 2178 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2179 << IV->getDeclName()); 2180 2181 // If we're referencing an invalid decl, just return this as a silent 2182 // error node. The error diagnostic was already emitted on the decl. 2183 if (IV->isInvalidDecl()) 2184 return ExprError(); 2185 2186 // Check if referencing a field with __attribute__((deprecated)). 2187 if (DiagnoseUseOfDecl(IV, Loc)) 2188 return ExprError(); 2189 2190 // Diagnose the use of an ivar outside of the declaring class. 2191 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2192 !declaresSameEntity(ClassDeclared, IFace) && 2193 !getLangOpts().DebuggerSupport) 2194 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2195 2196 // FIXME: This should use a new expr for a direct reference, don't 2197 // turn this into Self->ivar, just return a BareIVarExpr or something. 2198 IdentifierInfo &II = Context.Idents.get("self"); 2199 UnqualifiedId SelfName; 2200 SelfName.setIdentifier(&II, SourceLocation()); 2201 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2202 CXXScopeSpec SelfScopeSpec; 2203 SourceLocation TemplateKWLoc; 2204 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2205 SelfName, false, false); 2206 if (SelfExpr.isInvalid()) 2207 return ExprError(); 2208 2209 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2210 if (SelfExpr.isInvalid()) 2211 return ExprError(); 2212 2213 MarkAnyDeclReferenced(Loc, IV, true); 2214 2215 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2216 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2217 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2218 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2219 2220 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2221 Loc, IV->getLocation(), 2222 SelfExpr.take(), 2223 true, true); 2224 2225 if (getLangOpts().ObjCAutoRefCount) { 2226 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2227 DiagnosticsEngine::Level Level = 2228 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2229 if (Level != DiagnosticsEngine::Ignored) 2230 recordUseOfEvaluatedWeak(Result); 2231 } 2232 if (CurContext->isClosure()) 2233 Diag(Loc, diag::warn_implicitly_retains_self) 2234 << FixItHint::CreateInsertion(Loc, "self->"); 2235 } 2236 2237 return Owned(Result); 2238 } 2239 } else if (CurMethod->isInstanceMethod()) { 2240 // We should warn if a local variable hides an ivar. 2241 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2242 ObjCInterfaceDecl *ClassDeclared; 2243 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2244 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2245 declaresSameEntity(IFace, ClassDeclared)) 2246 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2247 } 2248 } 2249 } else if (Lookup.isSingleResult() && 2250 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2251 // If accessing a stand-alone ivar in a class method, this is an error. 2252 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2253 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2254 << IV->getDeclName()); 2255 } 2256 2257 if (Lookup.empty() && II && AllowBuiltinCreation) { 2258 // FIXME. Consolidate this with similar code in LookupName. 2259 if (unsigned BuiltinID = II->getBuiltinID()) { 2260 if (!(getLangOpts().CPlusPlus && 2261 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2262 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2263 S, Lookup.isForRedeclaration(), 2264 Lookup.getNameLoc()); 2265 if (D) Lookup.addDecl(D); 2266 } 2267 } 2268 } 2269 // Sentinel value saying that we didn't do anything special. 2270 return Owned((Expr*) 0); 2271 } 2272 2273 /// \brief Cast a base object to a member's actual type. 2274 /// 2275 /// Logically this happens in three phases: 2276 /// 2277 /// * First we cast from the base type to the naming class. 2278 /// The naming class is the class into which we were looking 2279 /// when we found the member; it's the qualifier type if a 2280 /// qualifier was provided, and otherwise it's the base type. 2281 /// 2282 /// * Next we cast from the naming class to the declaring class. 2283 /// If the member we found was brought into a class's scope by 2284 /// a using declaration, this is that class; otherwise it's 2285 /// the class declaring the member. 2286 /// 2287 /// * Finally we cast from the declaring class to the "true" 2288 /// declaring class of the member. This conversion does not 2289 /// obey access control. 2290 ExprResult 2291 Sema::PerformObjectMemberConversion(Expr *From, 2292 NestedNameSpecifier *Qualifier, 2293 NamedDecl *FoundDecl, 2294 NamedDecl *Member) { 2295 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2296 if (!RD) 2297 return Owned(From); 2298 2299 QualType DestRecordType; 2300 QualType DestType; 2301 QualType FromRecordType; 2302 QualType FromType = From->getType(); 2303 bool PointerConversions = false; 2304 if (isa<FieldDecl>(Member)) { 2305 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2306 2307 if (FromType->getAs<PointerType>()) { 2308 DestType = Context.getPointerType(DestRecordType); 2309 FromRecordType = FromType->getPointeeType(); 2310 PointerConversions = true; 2311 } else { 2312 DestType = DestRecordType; 2313 FromRecordType = FromType; 2314 } 2315 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2316 if (Method->isStatic()) 2317 return Owned(From); 2318 2319 DestType = Method->getThisType(Context); 2320 DestRecordType = DestType->getPointeeType(); 2321 2322 if (FromType->getAs<PointerType>()) { 2323 FromRecordType = FromType->getPointeeType(); 2324 PointerConversions = true; 2325 } else { 2326 FromRecordType = FromType; 2327 DestType = DestRecordType; 2328 } 2329 } else { 2330 // No conversion necessary. 2331 return Owned(From); 2332 } 2333 2334 if (DestType->isDependentType() || FromType->isDependentType()) 2335 return Owned(From); 2336 2337 // If the unqualified types are the same, no conversion is necessary. 2338 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2339 return Owned(From); 2340 2341 SourceRange FromRange = From->getSourceRange(); 2342 SourceLocation FromLoc = FromRange.getBegin(); 2343 2344 ExprValueKind VK = From->getValueKind(); 2345 2346 // C++ [class.member.lookup]p8: 2347 // [...] Ambiguities can often be resolved by qualifying a name with its 2348 // class name. 2349 // 2350 // If the member was a qualified name and the qualified referred to a 2351 // specific base subobject type, we'll cast to that intermediate type 2352 // first and then to the object in which the member is declared. That allows 2353 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2354 // 2355 // class Base { public: int x; }; 2356 // class Derived1 : public Base { }; 2357 // class Derived2 : public Base { }; 2358 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2359 // 2360 // void VeryDerived::f() { 2361 // x = 17; // error: ambiguous base subobjects 2362 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2363 // } 2364 if (Qualifier && Qualifier->getAsType()) { 2365 QualType QType = QualType(Qualifier->getAsType(), 0); 2366 assert(QType->isRecordType() && "lookup done with non-record type"); 2367 2368 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2369 2370 // In C++98, the qualifier type doesn't actually have to be a base 2371 // type of the object type, in which case we just ignore it. 2372 // Otherwise build the appropriate casts. 2373 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2374 CXXCastPath BasePath; 2375 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2376 FromLoc, FromRange, &BasePath)) 2377 return ExprError(); 2378 2379 if (PointerConversions) 2380 QType = Context.getPointerType(QType); 2381 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2382 VK, &BasePath).take(); 2383 2384 FromType = QType; 2385 FromRecordType = QRecordType; 2386 2387 // If the qualifier type was the same as the destination type, 2388 // we're done. 2389 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2390 return Owned(From); 2391 } 2392 } 2393 2394 bool IgnoreAccess = false; 2395 2396 // If we actually found the member through a using declaration, cast 2397 // down to the using declaration's type. 2398 // 2399 // Pointer equality is fine here because only one declaration of a 2400 // class ever has member declarations. 2401 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2402 assert(isa<UsingShadowDecl>(FoundDecl)); 2403 QualType URecordType = Context.getTypeDeclType( 2404 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2405 2406 // We only need to do this if the naming-class to declaring-class 2407 // conversion is non-trivial. 2408 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2409 assert(IsDerivedFrom(FromRecordType, URecordType)); 2410 CXXCastPath BasePath; 2411 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2412 FromLoc, FromRange, &BasePath)) 2413 return ExprError(); 2414 2415 QualType UType = URecordType; 2416 if (PointerConversions) 2417 UType = Context.getPointerType(UType); 2418 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2419 VK, &BasePath).take(); 2420 FromType = UType; 2421 FromRecordType = URecordType; 2422 } 2423 2424 // We don't do access control for the conversion from the 2425 // declaring class to the true declaring class. 2426 IgnoreAccess = true; 2427 } 2428 2429 CXXCastPath BasePath; 2430 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2431 FromLoc, FromRange, &BasePath, 2432 IgnoreAccess)) 2433 return ExprError(); 2434 2435 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2436 VK, &BasePath); 2437 } 2438 2439 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2440 const LookupResult &R, 2441 bool HasTrailingLParen) { 2442 // Only when used directly as the postfix-expression of a call. 2443 if (!HasTrailingLParen) 2444 return false; 2445 2446 // Never if a scope specifier was provided. 2447 if (SS.isSet()) 2448 return false; 2449 2450 // Only in C++ or ObjC++. 2451 if (!getLangOpts().CPlusPlus) 2452 return false; 2453 2454 // Turn off ADL when we find certain kinds of declarations during 2455 // normal lookup: 2456 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2457 NamedDecl *D = *I; 2458 2459 // C++0x [basic.lookup.argdep]p3: 2460 // -- a declaration of a class member 2461 // Since using decls preserve this property, we check this on the 2462 // original decl. 2463 if (D->isCXXClassMember()) 2464 return false; 2465 2466 // C++0x [basic.lookup.argdep]p3: 2467 // -- a block-scope function declaration that is not a 2468 // using-declaration 2469 // NOTE: we also trigger this for function templates (in fact, we 2470 // don't check the decl type at all, since all other decl types 2471 // turn off ADL anyway). 2472 if (isa<UsingShadowDecl>(D)) 2473 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2474 else if (D->getDeclContext()->isFunctionOrMethod()) 2475 return false; 2476 2477 // C++0x [basic.lookup.argdep]p3: 2478 // -- a declaration that is neither a function or a function 2479 // template 2480 // And also for builtin functions. 2481 if (isa<FunctionDecl>(D)) { 2482 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2483 2484 // But also builtin functions. 2485 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2486 return false; 2487 } else if (!isa<FunctionTemplateDecl>(D)) 2488 return false; 2489 } 2490 2491 return true; 2492 } 2493 2494 2495 /// Diagnoses obvious problems with the use of the given declaration 2496 /// as an expression. This is only actually called for lookups that 2497 /// were not overloaded, and it doesn't promise that the declaration 2498 /// will in fact be used. 2499 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2500 if (isa<TypedefNameDecl>(D)) { 2501 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2502 return true; 2503 } 2504 2505 if (isa<ObjCInterfaceDecl>(D)) { 2506 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2507 return true; 2508 } 2509 2510 if (isa<NamespaceDecl>(D)) { 2511 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2512 return true; 2513 } 2514 2515 return false; 2516 } 2517 2518 ExprResult 2519 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2520 LookupResult &R, 2521 bool NeedsADL) { 2522 // If this is a single, fully-resolved result and we don't need ADL, 2523 // just build an ordinary singleton decl ref. 2524 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2525 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2526 R.getRepresentativeDecl()); 2527 2528 // We only need to check the declaration if there's exactly one 2529 // result, because in the overloaded case the results can only be 2530 // functions and function templates. 2531 if (R.isSingleResult() && 2532 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2533 return ExprError(); 2534 2535 // Otherwise, just build an unresolved lookup expression. Suppress 2536 // any lookup-related diagnostics; we'll hash these out later, when 2537 // we've picked a target. 2538 R.suppressDiagnostics(); 2539 2540 UnresolvedLookupExpr *ULE 2541 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2542 SS.getWithLocInContext(Context), 2543 R.getLookupNameInfo(), 2544 NeedsADL, R.isOverloadedResult(), 2545 R.begin(), R.end()); 2546 2547 return Owned(ULE); 2548 } 2549 2550 /// \brief Complete semantic analysis for a reference to the given declaration. 2551 ExprResult Sema::BuildDeclarationNameExpr( 2552 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2553 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2554 assert(D && "Cannot refer to a NULL declaration"); 2555 assert(!isa<FunctionTemplateDecl>(D) && 2556 "Cannot refer unambiguously to a function template"); 2557 2558 SourceLocation Loc = NameInfo.getLoc(); 2559 if (CheckDeclInExpr(*this, Loc, D)) 2560 return ExprError(); 2561 2562 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2563 // Specifically diagnose references to class templates that are missing 2564 // a template argument list. 2565 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2566 << Template << SS.getRange(); 2567 Diag(Template->getLocation(), diag::note_template_decl_here); 2568 return ExprError(); 2569 } 2570 2571 // Make sure that we're referring to a value. 2572 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2573 if (!VD) { 2574 Diag(Loc, diag::err_ref_non_value) 2575 << D << SS.getRange(); 2576 Diag(D->getLocation(), diag::note_declared_at); 2577 return ExprError(); 2578 } 2579 2580 // Check whether this declaration can be used. Note that we suppress 2581 // this check when we're going to perform argument-dependent lookup 2582 // on this function name, because this might not be the function 2583 // that overload resolution actually selects. 2584 if (DiagnoseUseOfDecl(VD, Loc)) 2585 return ExprError(); 2586 2587 // Only create DeclRefExpr's for valid Decl's. 2588 if (VD->isInvalidDecl()) 2589 return ExprError(); 2590 2591 // Handle members of anonymous structs and unions. If we got here, 2592 // and the reference is to a class member indirect field, then this 2593 // must be the subject of a pointer-to-member expression. 2594 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2595 if (!indirectField->isCXXClassMember()) 2596 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2597 indirectField); 2598 2599 { 2600 QualType type = VD->getType(); 2601 ExprValueKind valueKind = VK_RValue; 2602 2603 switch (D->getKind()) { 2604 // Ignore all the non-ValueDecl kinds. 2605 #define ABSTRACT_DECL(kind) 2606 #define VALUE(type, base) 2607 #define DECL(type, base) \ 2608 case Decl::type: 2609 #include "clang/AST/DeclNodes.inc" 2610 llvm_unreachable("invalid value decl kind"); 2611 2612 // These shouldn't make it here. 2613 case Decl::ObjCAtDefsField: 2614 case Decl::ObjCIvar: 2615 llvm_unreachable("forming non-member reference to ivar?"); 2616 2617 // Enum constants are always r-values and never references. 2618 // Unresolved using declarations are dependent. 2619 case Decl::EnumConstant: 2620 case Decl::UnresolvedUsingValue: 2621 valueKind = VK_RValue; 2622 break; 2623 2624 // Fields and indirect fields that got here must be for 2625 // pointer-to-member expressions; we just call them l-values for 2626 // internal consistency, because this subexpression doesn't really 2627 // exist in the high-level semantics. 2628 case Decl::Field: 2629 case Decl::IndirectField: 2630 assert(getLangOpts().CPlusPlus && 2631 "building reference to field in C?"); 2632 2633 // These can't have reference type in well-formed programs, but 2634 // for internal consistency we do this anyway. 2635 type = type.getNonReferenceType(); 2636 valueKind = VK_LValue; 2637 break; 2638 2639 // Non-type template parameters are either l-values or r-values 2640 // depending on the type. 2641 case Decl::NonTypeTemplateParm: { 2642 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2643 type = reftype->getPointeeType(); 2644 valueKind = VK_LValue; // even if the parameter is an r-value reference 2645 break; 2646 } 2647 2648 // For non-references, we need to strip qualifiers just in case 2649 // the template parameter was declared as 'const int' or whatever. 2650 valueKind = VK_RValue; 2651 type = type.getUnqualifiedType(); 2652 break; 2653 } 2654 2655 case Decl::Var: 2656 case Decl::VarTemplateSpecialization: 2657 case Decl::VarTemplatePartialSpecialization: 2658 // In C, "extern void blah;" is valid and is an r-value. 2659 if (!getLangOpts().CPlusPlus && 2660 !type.hasQualifiers() && 2661 type->isVoidType()) { 2662 valueKind = VK_RValue; 2663 break; 2664 } 2665 // fallthrough 2666 2667 case Decl::ImplicitParam: 2668 case Decl::ParmVar: { 2669 // These are always l-values. 2670 valueKind = VK_LValue; 2671 type = type.getNonReferenceType(); 2672 2673 // FIXME: Does the addition of const really only apply in 2674 // potentially-evaluated contexts? Since the variable isn't actually 2675 // captured in an unevaluated context, it seems that the answer is no. 2676 if (!isUnevaluatedContext()) { 2677 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2678 if (!CapturedType.isNull()) 2679 type = CapturedType; 2680 } 2681 2682 break; 2683 } 2684 2685 case Decl::Function: { 2686 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2687 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2688 type = Context.BuiltinFnTy; 2689 valueKind = VK_RValue; 2690 break; 2691 } 2692 } 2693 2694 const FunctionType *fty = type->castAs<FunctionType>(); 2695 2696 // If we're referring to a function with an __unknown_anytype 2697 // result type, make the entire expression __unknown_anytype. 2698 if (fty->getResultType() == Context.UnknownAnyTy) { 2699 type = Context.UnknownAnyTy; 2700 valueKind = VK_RValue; 2701 break; 2702 } 2703 2704 // Functions are l-values in C++. 2705 if (getLangOpts().CPlusPlus) { 2706 valueKind = VK_LValue; 2707 break; 2708 } 2709 2710 // C99 DR 316 says that, if a function type comes from a 2711 // function definition (without a prototype), that type is only 2712 // used for checking compatibility. Therefore, when referencing 2713 // the function, we pretend that we don't have the full function 2714 // type. 2715 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2716 isa<FunctionProtoType>(fty)) 2717 type = Context.getFunctionNoProtoType(fty->getResultType(), 2718 fty->getExtInfo()); 2719 2720 // Functions are r-values in C. 2721 valueKind = VK_RValue; 2722 break; 2723 } 2724 2725 case Decl::MSProperty: 2726 valueKind = VK_LValue; 2727 break; 2728 2729 case Decl::CXXMethod: 2730 // If we're referring to a method with an __unknown_anytype 2731 // result type, make the entire expression __unknown_anytype. 2732 // This should only be possible with a type written directly. 2733 if (const FunctionProtoType *proto 2734 = dyn_cast<FunctionProtoType>(VD->getType())) 2735 if (proto->getResultType() == Context.UnknownAnyTy) { 2736 type = Context.UnknownAnyTy; 2737 valueKind = VK_RValue; 2738 break; 2739 } 2740 2741 // C++ methods are l-values if static, r-values if non-static. 2742 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2743 valueKind = VK_LValue; 2744 break; 2745 } 2746 // fallthrough 2747 2748 case Decl::CXXConversion: 2749 case Decl::CXXDestructor: 2750 case Decl::CXXConstructor: 2751 valueKind = VK_RValue; 2752 break; 2753 } 2754 2755 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2756 TemplateArgs); 2757 } 2758 } 2759 2760 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2761 PredefinedExpr::IdentType IT; 2762 2763 switch (Kind) { 2764 default: llvm_unreachable("Unknown simple primary expr!"); 2765 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2766 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2767 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2768 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2769 } 2770 2771 // Pre-defined identifiers are of type char[x], where x is the length of the 2772 // string. 2773 2774 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2775 // Blocks and lambdas can occur at global scope. Don't emit a warning. 2776 if (!currentDecl) { 2777 if (const BlockScopeInfo *BSI = getCurBlock()) 2778 currentDecl = BSI->TheDecl; 2779 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2780 currentDecl = LSI->CallOperator; 2781 } 2782 2783 if (!currentDecl) { 2784 Diag(Loc, diag::ext_predef_outside_function); 2785 currentDecl = Context.getTranslationUnitDecl(); 2786 } 2787 2788 QualType ResTy; 2789 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2790 ResTy = Context.DependentTy; 2791 } else { 2792 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2793 2794 llvm::APInt LengthI(32, Length + 1); 2795 if (IT == PredefinedExpr::LFunction) 2796 ResTy = Context.WideCharTy.withConst(); 2797 else 2798 ResTy = Context.CharTy.withConst(); 2799 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2800 } 2801 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2802 } 2803 2804 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2805 SmallString<16> CharBuffer; 2806 bool Invalid = false; 2807 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2808 if (Invalid) 2809 return ExprError(); 2810 2811 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2812 PP, Tok.getKind()); 2813 if (Literal.hadError()) 2814 return ExprError(); 2815 2816 QualType Ty; 2817 if (Literal.isWide()) 2818 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2819 else if (Literal.isUTF16()) 2820 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2821 else if (Literal.isUTF32()) 2822 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2823 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2824 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2825 else 2826 Ty = Context.CharTy; // 'x' -> char in C++ 2827 2828 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2829 if (Literal.isWide()) 2830 Kind = CharacterLiteral::Wide; 2831 else if (Literal.isUTF16()) 2832 Kind = CharacterLiteral::UTF16; 2833 else if (Literal.isUTF32()) 2834 Kind = CharacterLiteral::UTF32; 2835 2836 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2837 Tok.getLocation()); 2838 2839 if (Literal.getUDSuffix().empty()) 2840 return Owned(Lit); 2841 2842 // We're building a user-defined literal. 2843 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2844 SourceLocation UDSuffixLoc = 2845 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2846 2847 // Make sure we're allowed user-defined literals here. 2848 if (!UDLScope) 2849 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2850 2851 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2852 // operator "" X (ch) 2853 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2854 Lit, Tok.getLocation()); 2855 } 2856 2857 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2858 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2859 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2860 Context.IntTy, Loc)); 2861 } 2862 2863 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2864 QualType Ty, SourceLocation Loc) { 2865 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2866 2867 using llvm::APFloat; 2868 APFloat Val(Format); 2869 2870 APFloat::opStatus result = Literal.GetFloatValue(Val); 2871 2872 // Overflow is always an error, but underflow is only an error if 2873 // we underflowed to zero (APFloat reports denormals as underflow). 2874 if ((result & APFloat::opOverflow) || 2875 ((result & APFloat::opUnderflow) && Val.isZero())) { 2876 unsigned diagnostic; 2877 SmallString<20> buffer; 2878 if (result & APFloat::opOverflow) { 2879 diagnostic = diag::warn_float_overflow; 2880 APFloat::getLargest(Format).toString(buffer); 2881 } else { 2882 diagnostic = diag::warn_float_underflow; 2883 APFloat::getSmallest(Format).toString(buffer); 2884 } 2885 2886 S.Diag(Loc, diagnostic) 2887 << Ty 2888 << StringRef(buffer.data(), buffer.size()); 2889 } 2890 2891 bool isExact = (result == APFloat::opOK); 2892 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2893 } 2894 2895 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2896 // Fast path for a single digit (which is quite common). A single digit 2897 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2898 if (Tok.getLength() == 1) { 2899 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2900 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2901 } 2902 2903 SmallString<128> SpellingBuffer; 2904 // NumericLiteralParser wants to overread by one character. Add padding to 2905 // the buffer in case the token is copied to the buffer. If getSpelling() 2906 // returns a StringRef to the memory buffer, it should have a null char at 2907 // the EOF, so it is also safe. 2908 SpellingBuffer.resize(Tok.getLength() + 1); 2909 2910 // Get the spelling of the token, which eliminates trigraphs, etc. 2911 bool Invalid = false; 2912 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2913 if (Invalid) 2914 return ExprError(); 2915 2916 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2917 if (Literal.hadError) 2918 return ExprError(); 2919 2920 if (Literal.hasUDSuffix()) { 2921 // We're building a user-defined literal. 2922 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2923 SourceLocation UDSuffixLoc = 2924 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2925 2926 // Make sure we're allowed user-defined literals here. 2927 if (!UDLScope) 2928 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2929 2930 QualType CookedTy; 2931 if (Literal.isFloatingLiteral()) { 2932 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2933 // long double, the literal is treated as a call of the form 2934 // operator "" X (f L) 2935 CookedTy = Context.LongDoubleTy; 2936 } else { 2937 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2938 // unsigned long long, the literal is treated as a call of the form 2939 // operator "" X (n ULL) 2940 CookedTy = Context.UnsignedLongLongTy; 2941 } 2942 2943 DeclarationName OpName = 2944 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2945 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2946 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2947 2948 // Perform literal operator lookup to determine if we're building a raw 2949 // literal or a cooked one. 2950 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2951 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 2952 /*AllowRawAndTemplate*/true)) { 2953 case LOLR_Error: 2954 return ExprError(); 2955 2956 case LOLR_Cooked: { 2957 Expr *Lit; 2958 if (Literal.isFloatingLiteral()) { 2959 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2960 } else { 2961 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2962 if (Literal.GetIntegerValue(ResultVal)) 2963 Diag(Tok.getLocation(), diag::err_integer_too_large); 2964 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2965 Tok.getLocation()); 2966 } 2967 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, 2968 Tok.getLocation()); 2969 } 2970 2971 case LOLR_Raw: { 2972 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2973 // literal is treated as a call of the form 2974 // operator "" X ("n") 2975 SourceLocation TokLoc = Tok.getLocation(); 2976 unsigned Length = Literal.getUDSuffixOffset(); 2977 QualType StrTy = Context.getConstantArrayType( 2978 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 2979 ArrayType::Normal, 0); 2980 Expr *Lit = StringLiteral::Create( 2981 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 2982 /*Pascal*/false, StrTy, &TokLoc, 1); 2983 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 2984 } 2985 2986 case LOLR_Template: 2987 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2988 // template), L is treated as a call fo the form 2989 // operator "" X <'c1', 'c2', ... 'ck'>() 2990 // where n is the source character sequence c1 c2 ... ck. 2991 TemplateArgumentListInfo ExplicitArgs; 2992 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2993 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2994 llvm::APSInt Value(CharBits, CharIsUnsigned); 2995 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2996 Value = TokSpelling[I]; 2997 TemplateArgument Arg(Context, Value, Context.CharTy); 2998 TemplateArgumentLocInfo ArgInfo; 2999 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3000 } 3001 return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(), 3002 &ExplicitArgs); 3003 } 3004 3005 llvm_unreachable("unexpected literal operator lookup result"); 3006 } 3007 3008 Expr *Res; 3009 3010 if (Literal.isFloatingLiteral()) { 3011 QualType Ty; 3012 if (Literal.isFloat) 3013 Ty = Context.FloatTy; 3014 else if (!Literal.isLong) 3015 Ty = Context.DoubleTy; 3016 else 3017 Ty = Context.LongDoubleTy; 3018 3019 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3020 3021 if (Ty == Context.DoubleTy) { 3022 if (getLangOpts().SinglePrecisionConstants) { 3023 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3024 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3025 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3026 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3027 } 3028 } 3029 } else if (!Literal.isIntegerLiteral()) { 3030 return ExprError(); 3031 } else { 3032 QualType Ty; 3033 3034 // 'long long' is a C99 or C++11 feature. 3035 if (!getLangOpts().C99 && Literal.isLongLong) { 3036 if (getLangOpts().CPlusPlus) 3037 Diag(Tok.getLocation(), 3038 getLangOpts().CPlusPlus11 ? 3039 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3040 else 3041 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3042 } 3043 3044 // Get the value in the widest-possible width. 3045 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3046 // The microsoft literal suffix extensions support 128-bit literals, which 3047 // may be wider than [u]intmax_t. 3048 // FIXME: Actually, they don't. We seem to have accidentally invented the 3049 // i128 suffix. 3050 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3051 PP.getTargetInfo().hasInt128Type()) 3052 MaxWidth = 128; 3053 llvm::APInt ResultVal(MaxWidth, 0); 3054 3055 if (Literal.GetIntegerValue(ResultVal)) { 3056 // If this value didn't fit into uintmax_t, error and force to ull. 3057 Diag(Tok.getLocation(), diag::err_integer_too_large); 3058 Ty = Context.UnsignedLongLongTy; 3059 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3060 "long long is not intmax_t?"); 3061 } else { 3062 // If this value fits into a ULL, try to figure out what else it fits into 3063 // according to the rules of C99 6.4.4.1p5. 3064 3065 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3066 // be an unsigned int. 3067 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3068 3069 // Check from smallest to largest, picking the smallest type we can. 3070 unsigned Width = 0; 3071 if (!Literal.isLong && !Literal.isLongLong) { 3072 // Are int/unsigned possibilities? 3073 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3074 3075 // Does it fit in a unsigned int? 3076 if (ResultVal.isIntN(IntSize)) { 3077 // Does it fit in a signed int? 3078 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3079 Ty = Context.IntTy; 3080 else if (AllowUnsigned) 3081 Ty = Context.UnsignedIntTy; 3082 Width = IntSize; 3083 } 3084 } 3085 3086 // Are long/unsigned long possibilities? 3087 if (Ty.isNull() && !Literal.isLongLong) { 3088 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3089 3090 // Does it fit in a unsigned long? 3091 if (ResultVal.isIntN(LongSize)) { 3092 // Does it fit in a signed long? 3093 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3094 Ty = Context.LongTy; 3095 else if (AllowUnsigned) 3096 Ty = Context.UnsignedLongTy; 3097 Width = LongSize; 3098 } 3099 } 3100 3101 // Check long long if needed. 3102 if (Ty.isNull()) { 3103 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3104 3105 // Does it fit in a unsigned long long? 3106 if (ResultVal.isIntN(LongLongSize)) { 3107 // Does it fit in a signed long long? 3108 // To be compatible with MSVC, hex integer literals ending with the 3109 // LL or i64 suffix are always signed in Microsoft mode. 3110 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3111 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3112 Ty = Context.LongLongTy; 3113 else if (AllowUnsigned) 3114 Ty = Context.UnsignedLongLongTy; 3115 Width = LongLongSize; 3116 } 3117 } 3118 3119 // If it doesn't fit in unsigned long long, and we're using Microsoft 3120 // extensions, then its a 128-bit integer literal. 3121 if (Ty.isNull() && Literal.isMicrosoftInteger && 3122 PP.getTargetInfo().hasInt128Type()) { 3123 if (Literal.isUnsigned) 3124 Ty = Context.UnsignedInt128Ty; 3125 else 3126 Ty = Context.Int128Ty; 3127 Width = 128; 3128 } 3129 3130 // If we still couldn't decide a type, we probably have something that 3131 // does not fit in a signed long long, but has no U suffix. 3132 if (Ty.isNull()) { 3133 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3134 Ty = Context.UnsignedLongLongTy; 3135 Width = Context.getTargetInfo().getLongLongWidth(); 3136 } 3137 3138 if (ResultVal.getBitWidth() != Width) 3139 ResultVal = ResultVal.trunc(Width); 3140 } 3141 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3142 } 3143 3144 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3145 if (Literal.isImaginary) 3146 Res = new (Context) ImaginaryLiteral(Res, 3147 Context.getComplexType(Res->getType())); 3148 3149 return Owned(Res); 3150 } 3151 3152 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3153 assert((E != 0) && "ActOnParenExpr() missing expr"); 3154 return Owned(new (Context) ParenExpr(L, R, E)); 3155 } 3156 3157 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3158 SourceLocation Loc, 3159 SourceRange ArgRange) { 3160 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3161 // scalar or vector data type argument..." 3162 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3163 // type (C99 6.2.5p18) or void. 3164 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3165 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3166 << T << ArgRange; 3167 return true; 3168 } 3169 3170 assert((T->isVoidType() || !T->isIncompleteType()) && 3171 "Scalar types should always be complete"); 3172 return false; 3173 } 3174 3175 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3176 SourceLocation Loc, 3177 SourceRange ArgRange, 3178 UnaryExprOrTypeTrait TraitKind) { 3179 // C99 6.5.3.4p1: 3180 if (T->isFunctionType() && 3181 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3182 // sizeof(function)/alignof(function) is allowed as an extension. 3183 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3184 << TraitKind << ArgRange; 3185 return false; 3186 } 3187 3188 // Allow sizeof(void)/alignof(void) as an extension. 3189 if (T->isVoidType()) { 3190 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3191 return false; 3192 } 3193 3194 return true; 3195 } 3196 3197 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3198 SourceLocation Loc, 3199 SourceRange ArgRange, 3200 UnaryExprOrTypeTrait TraitKind) { 3201 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3202 // runtime doesn't allow it. 3203 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3204 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3205 << T << (TraitKind == UETT_SizeOf) 3206 << ArgRange; 3207 return true; 3208 } 3209 3210 return false; 3211 } 3212 3213 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3214 /// pointer type is equal to T) and emit a warning if it is. 3215 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3216 Expr *E) { 3217 // Don't warn if the operation changed the type. 3218 if (T != E->getType()) 3219 return; 3220 3221 // Now look for array decays. 3222 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3223 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3224 return; 3225 3226 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3227 << ICE->getType() 3228 << ICE->getSubExpr()->getType(); 3229 } 3230 3231 /// \brief Check the constrains on expression operands to unary type expression 3232 /// and type traits. 3233 /// 3234 /// Completes any types necessary and validates the constraints on the operand 3235 /// expression. The logic mostly mirrors the type-based overload, but may modify 3236 /// the expression as it completes the type for that expression through template 3237 /// instantiation, etc. 3238 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3239 UnaryExprOrTypeTrait ExprKind) { 3240 QualType ExprTy = E->getType(); 3241 assert(!ExprTy->isReferenceType()); 3242 3243 if (ExprKind == UETT_VecStep) 3244 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3245 E->getSourceRange()); 3246 3247 // Whitelist some types as extensions 3248 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3249 E->getSourceRange(), ExprKind)) 3250 return false; 3251 3252 if (RequireCompleteExprType(E, 3253 diag::err_sizeof_alignof_incomplete_type, 3254 ExprKind, E->getSourceRange())) 3255 return true; 3256 3257 // Completing the expression's type may have changed it. 3258 ExprTy = E->getType(); 3259 assert(!ExprTy->isReferenceType()); 3260 3261 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3262 E->getSourceRange(), ExprKind)) 3263 return true; 3264 3265 if (ExprKind == UETT_SizeOf) { 3266 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3267 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3268 QualType OType = PVD->getOriginalType(); 3269 QualType Type = PVD->getType(); 3270 if (Type->isPointerType() && OType->isArrayType()) { 3271 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3272 << Type << OType; 3273 Diag(PVD->getLocation(), diag::note_declared_at); 3274 } 3275 } 3276 } 3277 3278 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3279 // decays into a pointer and returns an unintended result. This is most 3280 // likely a typo for "sizeof(array) op x". 3281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3282 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3283 BO->getLHS()); 3284 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3285 BO->getRHS()); 3286 } 3287 } 3288 3289 return false; 3290 } 3291 3292 /// \brief Check the constraints on operands to unary expression and type 3293 /// traits. 3294 /// 3295 /// This will complete any types necessary, and validate the various constraints 3296 /// on those operands. 3297 /// 3298 /// The UsualUnaryConversions() function is *not* called by this routine. 3299 /// C99 6.3.2.1p[2-4] all state: 3300 /// Except when it is the operand of the sizeof operator ... 3301 /// 3302 /// C++ [expr.sizeof]p4 3303 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3304 /// standard conversions are not applied to the operand of sizeof. 3305 /// 3306 /// This policy is followed for all of the unary trait expressions. 3307 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3308 SourceLocation OpLoc, 3309 SourceRange ExprRange, 3310 UnaryExprOrTypeTrait ExprKind) { 3311 if (ExprType->isDependentType()) 3312 return false; 3313 3314 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3315 // the result is the size of the referenced type." 3316 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3317 // result shall be the alignment of the referenced type." 3318 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3319 ExprType = Ref->getPointeeType(); 3320 3321 if (ExprKind == UETT_VecStep) 3322 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3323 3324 // Whitelist some types as extensions 3325 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3326 ExprKind)) 3327 return false; 3328 3329 if (RequireCompleteType(OpLoc, ExprType, 3330 diag::err_sizeof_alignof_incomplete_type, 3331 ExprKind, ExprRange)) 3332 return true; 3333 3334 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3335 ExprKind)) 3336 return true; 3337 3338 return false; 3339 } 3340 3341 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3342 E = E->IgnoreParens(); 3343 3344 // Cannot know anything else if the expression is dependent. 3345 if (E->isTypeDependent()) 3346 return false; 3347 3348 if (E->getObjectKind() == OK_BitField) { 3349 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3350 << 1 << E->getSourceRange(); 3351 return true; 3352 } 3353 3354 ValueDecl *D = 0; 3355 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3356 D = DRE->getDecl(); 3357 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3358 D = ME->getMemberDecl(); 3359 } 3360 3361 // If it's a field, require the containing struct to have a 3362 // complete definition so that we can compute the layout. 3363 // 3364 // This requires a very particular set of circumstances. For a 3365 // field to be contained within an incomplete type, we must in the 3366 // process of parsing that type. To have an expression refer to a 3367 // field, it must be an id-expression or a member-expression, but 3368 // the latter are always ill-formed when the base type is 3369 // incomplete, including only being partially complete. An 3370 // id-expression can never refer to a field in C because fields 3371 // are not in the ordinary namespace. In C++, an id-expression 3372 // can implicitly be a member access, but only if there's an 3373 // implicit 'this' value, and all such contexts are subject to 3374 // delayed parsing --- except for trailing return types in C++11. 3375 // And if an id-expression referring to a field occurs in a 3376 // context that lacks a 'this' value, it's ill-formed --- except, 3377 // agian, in C++11, where such references are allowed in an 3378 // unevaluated context. So C++11 introduces some new complexity. 3379 // 3380 // For the record, since __alignof__ on expressions is a GCC 3381 // extension, GCC seems to permit this but always gives the 3382 // nonsensical answer 0. 3383 // 3384 // We don't really need the layout here --- we could instead just 3385 // directly check for all the appropriate alignment-lowing 3386 // attributes --- but that would require duplicating a lot of 3387 // logic that just isn't worth duplicating for such a marginal 3388 // use-case. 3389 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3390 // Fast path this check, since we at least know the record has a 3391 // definition if we can find a member of it. 3392 if (!FD->getParent()->isCompleteDefinition()) { 3393 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3394 << E->getSourceRange(); 3395 return true; 3396 } 3397 3398 // Otherwise, if it's a field, and the field doesn't have 3399 // reference type, then it must have a complete type (or be a 3400 // flexible array member, which we explicitly want to 3401 // white-list anyway), which makes the following checks trivial. 3402 if (!FD->getType()->isReferenceType()) 3403 return false; 3404 } 3405 3406 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3407 } 3408 3409 bool Sema::CheckVecStepExpr(Expr *E) { 3410 E = E->IgnoreParens(); 3411 3412 // Cannot know anything else if the expression is dependent. 3413 if (E->isTypeDependent()) 3414 return false; 3415 3416 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3417 } 3418 3419 /// \brief Build a sizeof or alignof expression given a type operand. 3420 ExprResult 3421 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3422 SourceLocation OpLoc, 3423 UnaryExprOrTypeTrait ExprKind, 3424 SourceRange R) { 3425 if (!TInfo) 3426 return ExprError(); 3427 3428 QualType T = TInfo->getType(); 3429 3430 if (!T->isDependentType() && 3431 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3432 return ExprError(); 3433 3434 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3435 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3436 Context.getSizeType(), 3437 OpLoc, R.getEnd())); 3438 } 3439 3440 /// \brief Build a sizeof or alignof expression given an expression 3441 /// operand. 3442 ExprResult 3443 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3444 UnaryExprOrTypeTrait ExprKind) { 3445 ExprResult PE = CheckPlaceholderExpr(E); 3446 if (PE.isInvalid()) 3447 return ExprError(); 3448 3449 E = PE.get(); 3450 3451 // Verify that the operand is valid. 3452 bool isInvalid = false; 3453 if (E->isTypeDependent()) { 3454 // Delay type-checking for type-dependent expressions. 3455 } else if (ExprKind == UETT_AlignOf) { 3456 isInvalid = CheckAlignOfExpr(*this, E); 3457 } else if (ExprKind == UETT_VecStep) { 3458 isInvalid = CheckVecStepExpr(E); 3459 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3460 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3461 isInvalid = true; 3462 } else { 3463 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3464 } 3465 3466 if (isInvalid) 3467 return ExprError(); 3468 3469 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3470 PE = TransformToPotentiallyEvaluated(E); 3471 if (PE.isInvalid()) return ExprError(); 3472 E = PE.take(); 3473 } 3474 3475 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3476 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3477 ExprKind, E, Context.getSizeType(), OpLoc, 3478 E->getSourceRange().getEnd())); 3479 } 3480 3481 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3482 /// expr and the same for @c alignof and @c __alignof 3483 /// Note that the ArgRange is invalid if isType is false. 3484 ExprResult 3485 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3486 UnaryExprOrTypeTrait ExprKind, bool IsType, 3487 void *TyOrEx, const SourceRange &ArgRange) { 3488 // If error parsing type, ignore. 3489 if (TyOrEx == 0) return ExprError(); 3490 3491 if (IsType) { 3492 TypeSourceInfo *TInfo; 3493 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3494 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3495 } 3496 3497 Expr *ArgEx = (Expr *)TyOrEx; 3498 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3499 return Result; 3500 } 3501 3502 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3503 bool IsReal) { 3504 if (V.get()->isTypeDependent()) 3505 return S.Context.DependentTy; 3506 3507 // _Real and _Imag are only l-values for normal l-values. 3508 if (V.get()->getObjectKind() != OK_Ordinary) { 3509 V = S.DefaultLvalueConversion(V.take()); 3510 if (V.isInvalid()) 3511 return QualType(); 3512 } 3513 3514 // These operators return the element type of a complex type. 3515 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3516 return CT->getElementType(); 3517 3518 // Otherwise they pass through real integer and floating point types here. 3519 if (V.get()->getType()->isArithmeticType()) 3520 return V.get()->getType(); 3521 3522 // Test for placeholders. 3523 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3524 if (PR.isInvalid()) return QualType(); 3525 if (PR.get() != V.get()) { 3526 V = PR; 3527 return CheckRealImagOperand(S, V, Loc, IsReal); 3528 } 3529 3530 // Reject anything else. 3531 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3532 << (IsReal ? "__real" : "__imag"); 3533 return QualType(); 3534 } 3535 3536 3537 3538 ExprResult 3539 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3540 tok::TokenKind Kind, Expr *Input) { 3541 UnaryOperatorKind Opc; 3542 switch (Kind) { 3543 default: llvm_unreachable("Unknown unary op!"); 3544 case tok::plusplus: Opc = UO_PostInc; break; 3545 case tok::minusminus: Opc = UO_PostDec; break; 3546 } 3547 3548 // Since this might is a postfix expression, get rid of ParenListExprs. 3549 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3550 if (Result.isInvalid()) return ExprError(); 3551 Input = Result.take(); 3552 3553 return BuildUnaryOp(S, OpLoc, Opc, Input); 3554 } 3555 3556 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3557 /// 3558 /// \return true on error 3559 static bool checkArithmeticOnObjCPointer(Sema &S, 3560 SourceLocation opLoc, 3561 Expr *op) { 3562 assert(op->getType()->isObjCObjectPointerType()); 3563 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3564 return false; 3565 3566 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3567 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3568 << op->getSourceRange(); 3569 return true; 3570 } 3571 3572 ExprResult 3573 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3574 Expr *idx, SourceLocation rbLoc) { 3575 // Since this might be a postfix expression, get rid of ParenListExprs. 3576 if (isa<ParenListExpr>(base)) { 3577 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3578 if (result.isInvalid()) return ExprError(); 3579 base = result.take(); 3580 } 3581 3582 // Handle any non-overload placeholder types in the base and index 3583 // expressions. We can't handle overloads here because the other 3584 // operand might be an overloadable type, in which case the overload 3585 // resolution for the operator overload should get the first crack 3586 // at the overload. 3587 if (base->getType()->isNonOverloadPlaceholderType()) { 3588 ExprResult result = CheckPlaceholderExpr(base); 3589 if (result.isInvalid()) return ExprError(); 3590 base = result.take(); 3591 } 3592 if (idx->getType()->isNonOverloadPlaceholderType()) { 3593 ExprResult result = CheckPlaceholderExpr(idx); 3594 if (result.isInvalid()) return ExprError(); 3595 idx = result.take(); 3596 } 3597 3598 // Build an unanalyzed expression if either operand is type-dependent. 3599 if (getLangOpts().CPlusPlus && 3600 (base->isTypeDependent() || idx->isTypeDependent())) { 3601 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3602 Context.DependentTy, 3603 VK_LValue, OK_Ordinary, 3604 rbLoc)); 3605 } 3606 3607 // Use C++ overloaded-operator rules if either operand has record 3608 // type. The spec says to do this if either type is *overloadable*, 3609 // but enum types can't declare subscript operators or conversion 3610 // operators, so there's nothing interesting for overload resolution 3611 // to do if there aren't any record types involved. 3612 // 3613 // ObjC pointers have their own subscripting logic that is not tied 3614 // to overload resolution and so should not take this path. 3615 if (getLangOpts().CPlusPlus && 3616 (base->getType()->isRecordType() || 3617 (!base->getType()->isObjCObjectPointerType() && 3618 idx->getType()->isRecordType()))) { 3619 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3620 } 3621 3622 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3623 } 3624 3625 ExprResult 3626 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3627 Expr *Idx, SourceLocation RLoc) { 3628 Expr *LHSExp = Base; 3629 Expr *RHSExp = Idx; 3630 3631 // Perform default conversions. 3632 if (!LHSExp->getType()->getAs<VectorType>()) { 3633 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3634 if (Result.isInvalid()) 3635 return ExprError(); 3636 LHSExp = Result.take(); 3637 } 3638 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3639 if (Result.isInvalid()) 3640 return ExprError(); 3641 RHSExp = Result.take(); 3642 3643 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3644 ExprValueKind VK = VK_LValue; 3645 ExprObjectKind OK = OK_Ordinary; 3646 3647 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3648 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3649 // in the subscript position. As a result, we need to derive the array base 3650 // and index from the expression types. 3651 Expr *BaseExpr, *IndexExpr; 3652 QualType ResultType;