SemaExpr.cpp revision ab41fe914f63bb470dfa7e400876ada72f57a931
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 "clang/Sema/DelayedDiagnostic.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Lookup.h" 18#include "clang/Sema/ScopeInfo.h" 19#include "clang/Sema/AnalysisBasedWarnings.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/ASTConsumer.h" 22#include "clang/AST/ASTMutationListener.h" 23#include "clang/AST/CXXInheritance.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/DeclTemplate.h" 26#include "clang/AST/EvaluatedExprVisitor.h" 27#include "clang/AST/Expr.h" 28#include "clang/AST/ExprCXX.h" 29#include "clang/AST/ExprObjC.h" 30#include "clang/AST/RecursiveASTVisitor.h" 31#include "clang/AST/TypeLoc.h" 32#include "clang/Basic/PartialDiagnostic.h" 33#include "clang/Basic/SourceManager.h" 34#include "clang/Basic/TargetInfo.h" 35#include "clang/Lex/LiteralSupport.h" 36#include "clang/Lex/Preprocessor.h" 37#include "clang/Sema/DeclSpec.h" 38#include "clang/Sema/Designator.h" 39#include "clang/Sema/Scope.h" 40#include "clang/Sema/ScopeInfo.h" 41#include "clang/Sema/ParsedTemplate.h" 42#include "clang/Sema/SemaFixItUtils.h" 43#include "clang/Sema/Template.h" 44#include "TreeTransform.h" 45using namespace clang; 46using namespace sema; 47 48/// \brief Determine whether the use of this declaration is valid, without 49/// emitting diagnostics. 50bool Sema::CanUseDecl(NamedDecl *D) { 51 // See if this is an auto-typed variable whose initializer we are parsing. 52 if (ParsingInitForAutoVars.count(D)) 53 return false; 54 55 // See if this is a deleted function. 56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 57 if (FD->isDeleted()) 58 return false; 59 } 60 61 // See if this function is unavailable. 62 if (D->getAvailability() == AR_Unavailable && 63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 64 return false; 65 66 return true; 67} 68 69static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 70 NamedDecl *D, SourceLocation Loc, 71 const ObjCInterfaceDecl *UnknownObjCClass) { 72 // See if this declaration is unavailable or deprecated. 73 std::string Message; 74 AvailabilityResult Result = D->getAvailability(&Message); 75 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 76 if (Result == AR_Available) { 77 const DeclContext *DC = ECD->getDeclContext(); 78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 79 Result = TheEnumDecl->getAvailability(&Message); 80 } 81 82 switch (Result) { 83 case AR_Available: 84 case AR_NotYetIntroduced: 85 break; 86 87 case AR_Deprecated: 88 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass); 89 break; 90 91 case AR_Unavailable: 92 if (S.getCurContextAvailability() != AR_Unavailable) { 93 if (Message.empty()) { 94 if (!UnknownObjCClass) 95 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 96 else 97 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 98 << D->getDeclName(); 99 } 100 else 101 S.Diag(Loc, diag::err_unavailable_message) 102 << D->getDeclName() << Message; 103 S.Diag(D->getLocation(), diag::note_unavailable_here) 104 << isa<FunctionDecl>(D) << false; 105 } 106 break; 107 } 108 return Result; 109} 110 111/// \brief Emit a note explaining that this function is deleted or unavailable. 112void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 114 115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) { 116 // If the method was explicitly defaulted, point at that declaration. 117 if (!Method->isImplicit()) 118 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 119 120 // Try to diagnose why this special member function was implicitly 121 // deleted. This might fail, if that reason no longer applies. 122 CXXSpecialMember CSM = getSpecialMember(Method); 123 if (CSM != CXXInvalid) 124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 125 126 return; 127 } 128 129 Diag(Decl->getLocation(), diag::note_unavailable_here) 130 << 1 << Decl->isDeleted(); 131} 132 133/// \brief Determine whether the use of this declaration is valid, and 134/// emit any corresponding diagnostics. 135/// 136/// This routine diagnoses various problems with referencing 137/// declarations that can occur when using a declaration. For example, 138/// it might warn if a deprecated or unavailable declaration is being 139/// used, or produce an error (and return true) if a C++0x deleted 140/// function is being used. 141/// 142/// \returns true if there was an error (this declaration cannot be 143/// referenced), false otherwise. 144/// 145bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 146 const ObjCInterfaceDecl *UnknownObjCClass) { 147 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 148 // If there were any diagnostics suppressed by template argument deduction, 149 // emit them now. 150 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 151 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 152 if (Pos != SuppressedDiagnostics.end()) { 153 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 154 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 155 Diag(Suppressed[I].first, Suppressed[I].second); 156 157 // Clear out the list of suppressed diagnostics, so that we don't emit 158 // them again for this specialization. However, we don't obsolete this 159 // entry from the table, because we want to avoid ever emitting these 160 // diagnostics again. 161 Suppressed.clear(); 162 } 163 } 164 165 // See if this is an auto-typed variable whose initializer we are parsing. 166 if (ParsingInitForAutoVars.count(D)) { 167 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 168 << D->getDeclName(); 169 return true; 170 } 171 172 // See if this is a deleted function. 173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 174 if (FD->isDeleted()) { 175 Diag(Loc, diag::err_deleted_function_use); 176 NoteDeletedFunction(FD); 177 return true; 178 } 179 } 180 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 181 182 // Warn if this is used but marked unused. 183 if (D->hasAttr<UnusedAttr>()) 184 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 185 return false; 186} 187 188/// \brief Retrieve the message suffix that should be added to a 189/// diagnostic complaining about the given function being deleted or 190/// unavailable. 191std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 192 // FIXME: C++0x implicitly-deleted special member functions could be 193 // detected here so that we could improve diagnostics to say, e.g., 194 // "base class 'A' had a deleted copy constructor". 195 if (FD->isDeleted()) 196 return std::string(); 197 198 std::string Message; 199 if (FD->getAvailability(&Message)) 200 return ": " + Message; 201 202 return std::string(); 203} 204 205/// DiagnoseSentinelCalls - This routine checks whether a call or 206/// message-send is to a declaration with the sentinel attribute, and 207/// if so, it checks that the requirements of the sentinel are 208/// satisfied. 209void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 210 Expr **args, unsigned numArgs) { 211 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 212 if (!attr) 213 return; 214 215 // The number of formal parameters of the declaration. 216 unsigned numFormalParams; 217 218 // The kind of declaration. This is also an index into a %select in 219 // the diagnostic. 220 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 221 222 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 223 numFormalParams = MD->param_size(); 224 calleeType = CT_Method; 225 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 226 numFormalParams = FD->param_size(); 227 calleeType = CT_Function; 228 } else if (isa<VarDecl>(D)) { 229 QualType type = cast<ValueDecl>(D)->getType(); 230 const FunctionType *fn = 0; 231 if (const PointerType *ptr = type->getAs<PointerType>()) { 232 fn = ptr->getPointeeType()->getAs<FunctionType>(); 233 if (!fn) return; 234 calleeType = CT_Function; 235 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 236 fn = ptr->getPointeeType()->castAs<FunctionType>(); 237 calleeType = CT_Block; 238 } else { 239 return; 240 } 241 242 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 243 numFormalParams = proto->getNumArgs(); 244 } else { 245 numFormalParams = 0; 246 } 247 } else { 248 return; 249 } 250 251 // "nullPos" is the number of formal parameters at the end which 252 // effectively count as part of the variadic arguments. This is 253 // useful if you would prefer to not have *any* formal parameters, 254 // but the language forces you to have at least one. 255 unsigned nullPos = attr->getNullPos(); 256 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 257 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 258 259 // The number of arguments which should follow the sentinel. 260 unsigned numArgsAfterSentinel = attr->getSentinel(); 261 262 // If there aren't enough arguments for all the formal parameters, 263 // the sentinel, and the args after the sentinel, complain. 264 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) { 265 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 266 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 267 return; 268 } 269 270 // Otherwise, find the sentinel expression. 271 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1]; 272 if (!sentinelExpr) return; 273 if (sentinelExpr->isValueDependent()) return; 274 if (Context.isSentinelNullExpr(sentinelExpr)) return; 275 276 // Pick a reasonable string to insert. Optimistically use 'nil' or 277 // 'NULL' if those are actually defined in the context. Only use 278 // 'nil' for ObjC methods, where it's much more likely that the 279 // variadic arguments form a list of object pointers. 280 SourceLocation MissingNilLoc 281 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 282 std::string NullValue; 283 if (calleeType == CT_Method && 284 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 285 NullValue = "nil"; 286 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 287 NullValue = "NULL"; 288 else 289 NullValue = "(void*) 0"; 290 291 if (MissingNilLoc.isInvalid()) 292 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 293 else 294 Diag(MissingNilLoc, diag::warn_missing_sentinel) 295 << calleeType 296 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 297 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 298} 299 300SourceRange Sema::getExprRange(Expr *E) const { 301 return E ? E->getSourceRange() : SourceRange(); 302} 303 304//===----------------------------------------------------------------------===// 305// Standard Promotions and Conversions 306//===----------------------------------------------------------------------===// 307 308/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 309ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 310 // Handle any placeholder expressions which made it here. 311 if (E->getType()->isPlaceholderType()) { 312 ExprResult result = CheckPlaceholderExpr(E); 313 if (result.isInvalid()) return ExprError(); 314 E = result.take(); 315 } 316 317 QualType Ty = E->getType(); 318 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 319 320 if (Ty->isFunctionType()) 321 E = ImpCastExprToType(E, Context.getPointerType(Ty), 322 CK_FunctionToPointerDecay).take(); 323 else if (Ty->isArrayType()) { 324 // In C90 mode, arrays only promote to pointers if the array expression is 325 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 326 // type 'array of type' is converted to an expression that has type 'pointer 327 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 328 // that has type 'array of type' ...". The relevant change is "an lvalue" 329 // (C90) to "an expression" (C99). 330 // 331 // C++ 4.2p1: 332 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 333 // T" can be converted to an rvalue of type "pointer to T". 334 // 335 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 336 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 337 CK_ArrayToPointerDecay).take(); 338 } 339 return Owned(E); 340} 341 342static void CheckForNullPointerDereference(Sema &S, Expr *E) { 343 // Check to see if we are dereferencing a null pointer. If so, 344 // and if not volatile-qualified, this is undefined behavior that the 345 // optimizer will delete, so warn about it. People sometimes try to use this 346 // to get a deterministic trap and are surprised by clang's behavior. This 347 // only handles the pattern "*null", which is a very syntactic check. 348 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 349 if (UO->getOpcode() == UO_Deref && 350 UO->getSubExpr()->IgnoreParenCasts()-> 351 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 352 !UO->getType().isVolatileQualified()) { 353 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 354 S.PDiag(diag::warn_indirection_through_null) 355 << UO->getSubExpr()->getSourceRange()); 356 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 357 S.PDiag(diag::note_indirection_through_null)); 358 } 359} 360 361ExprResult Sema::DefaultLvalueConversion(Expr *E) { 362 // Handle any placeholder expressions which made it here. 363 if (E->getType()->isPlaceholderType()) { 364 ExprResult result = CheckPlaceholderExpr(E); 365 if (result.isInvalid()) return ExprError(); 366 E = result.take(); 367 } 368 369 // C++ [conv.lval]p1: 370 // A glvalue of a non-function, non-array type T can be 371 // converted to a prvalue. 372 if (!E->isGLValue()) return Owned(E); 373 374 QualType T = E->getType(); 375 assert(!T.isNull() && "r-value conversion on typeless expression?"); 376 377 // We don't want to throw lvalue-to-rvalue casts on top of 378 // expressions of certain types in C++. 379 if (getLangOpts().CPlusPlus && 380 (E->getType() == Context.OverloadTy || 381 T->isDependentType() || 382 T->isRecordType())) 383 return Owned(E); 384 385 // The C standard is actually really unclear on this point, and 386 // DR106 tells us what the result should be but not why. It's 387 // generally best to say that void types just doesn't undergo 388 // lvalue-to-rvalue at all. Note that expressions of unqualified 389 // 'void' type are never l-values, but qualified void can be. 390 if (T->isVoidType()) 391 return Owned(E); 392 393 CheckForNullPointerDereference(*this, E); 394 395 // C++ [conv.lval]p1: 396 // [...] If T is a non-class type, the type of the prvalue is the 397 // cv-unqualified version of T. Otherwise, the type of the 398 // rvalue is T. 399 // 400 // C99 6.3.2.1p2: 401 // If the lvalue has qualified type, the value has the unqualified 402 // version of the type of the lvalue; otherwise, the value has the 403 // type of the lvalue. 404 if (T.hasQualifiers()) 405 T = T.getUnqualifiedType(); 406 407 UpdateMarkingForLValueToRValue(E); 408 409 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 410 E, 0, VK_RValue)); 411 412 // C11 6.3.2.1p2: 413 // ... if the lvalue has atomic type, the value has the non-atomic version 414 // of the type of the lvalue ... 415 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 416 T = Atomic->getValueType().getUnqualifiedType(); 417 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 418 Res.get(), 0, VK_RValue)); 419 } 420 421 return Res; 422} 423 424ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 425 ExprResult Res = DefaultFunctionArrayConversion(E); 426 if (Res.isInvalid()) 427 return ExprError(); 428 Res = DefaultLvalueConversion(Res.take()); 429 if (Res.isInvalid()) 430 return ExprError(); 431 return move(Res); 432} 433 434 435/// UsualUnaryConversions - Performs various conversions that are common to most 436/// operators (C99 6.3). The conversions of array and function types are 437/// sometimes suppressed. For example, the array->pointer conversion doesn't 438/// apply if the array is an argument to the sizeof or address (&) operators. 439/// In these instances, this routine should *not* be called. 440ExprResult Sema::UsualUnaryConversions(Expr *E) { 441 // First, convert to an r-value. 442 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 443 if (Res.isInvalid()) 444 return Owned(E); 445 E = Res.take(); 446 447 QualType Ty = E->getType(); 448 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 449 450 // Half FP is a bit different: it's a storage-only type, meaning that any 451 // "use" of it should be promoted to float. 452 if (Ty->isHalfType()) 453 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 454 455 // Try to perform integral promotions if the object has a theoretically 456 // promotable type. 457 if (Ty->isIntegralOrUnscopedEnumerationType()) { 458 // C99 6.3.1.1p2: 459 // 460 // The following may be used in an expression wherever an int or 461 // unsigned int may be used: 462 // - an object or expression with an integer type whose integer 463 // conversion rank is less than or equal to the rank of int 464 // and unsigned int. 465 // - A bit-field of type _Bool, int, signed int, or unsigned int. 466 // 467 // If an int can represent all values of the original type, the 468 // value is converted to an int; otherwise, it is converted to an 469 // unsigned int. These are called the integer promotions. All 470 // other types are unchanged by the integer promotions. 471 472 QualType PTy = Context.isPromotableBitField(E); 473 if (!PTy.isNull()) { 474 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 475 return Owned(E); 476 } 477 if (Ty->isPromotableIntegerType()) { 478 QualType PT = Context.getPromotedIntegerType(Ty); 479 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 480 return Owned(E); 481 } 482 } 483 return Owned(E); 484} 485 486/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 487/// do not have a prototype. Arguments that have type float are promoted to 488/// double. All other argument types are converted by UsualUnaryConversions(). 489ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 490 QualType Ty = E->getType(); 491 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 492 493 ExprResult Res = UsualUnaryConversions(E); 494 if (Res.isInvalid()) 495 return Owned(E); 496 E = Res.take(); 497 498 // If this is a 'float' (CVR qualified or typedef) promote to double. 499 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 500 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 501 502 // C++ performs lvalue-to-rvalue conversion as a default argument 503 // promotion, even on class types, but note: 504 // C++11 [conv.lval]p2: 505 // When an lvalue-to-rvalue conversion occurs in an unevaluated 506 // operand or a subexpression thereof the value contained in the 507 // referenced object is not accessed. Otherwise, if the glvalue 508 // has a class type, the conversion copy-initializes a temporary 509 // of type T from the glvalue and the result of the conversion 510 // is a prvalue for the temporary. 511 // FIXME: add some way to gate this entire thing for correctness in 512 // potentially potentially evaluated contexts. 513 if (getLangOpts().CPlusPlus && E->isGLValue() && 514 ExprEvalContexts.back().Context != Unevaluated) { 515 ExprResult Temp = PerformCopyInitialization( 516 InitializedEntity::InitializeTemporary(E->getType()), 517 E->getExprLoc(), 518 Owned(E)); 519 if (Temp.isInvalid()) 520 return ExprError(); 521 E = Temp.get(); 522 } 523 524 return Owned(E); 525} 526 527/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 528/// will warn if the resulting type is not a POD type, and rejects ObjC 529/// interfaces passed by value. 530ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 531 FunctionDecl *FDecl) { 532 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 533 // Strip the unbridged-cast placeholder expression off, if applicable. 534 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 535 (CT == VariadicMethod || 536 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 537 E = stripARCUnbridgedCast(E); 538 539 // Otherwise, do normal placeholder checking. 540 } else { 541 ExprResult ExprRes = CheckPlaceholderExpr(E); 542 if (ExprRes.isInvalid()) 543 return ExprError(); 544 E = ExprRes.take(); 545 } 546 } 547 548 ExprResult ExprRes = DefaultArgumentPromotion(E); 549 if (ExprRes.isInvalid()) 550 return ExprError(); 551 E = ExprRes.take(); 552 553 // Don't allow one to pass an Objective-C interface to a vararg. 554 if (E->getType()->isObjCObjectType() && 555 DiagRuntimeBehavior(E->getLocStart(), 0, 556 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 557 << E->getType() << CT)) 558 return ExprError(); 559 560 // Complain about passing non-POD types through varargs. However, don't 561 // perform this check for incomplete types, which we can get here when we're 562 // in an unevaluated context. 563 if (!E->getType()->isIncompleteType() && 564 !E->getType().isCXX98PODType(Context)) { 565 // C++0x [expr.call]p7: 566 // Passing a potentially-evaluated argument of class type (Clause 9) 567 // having a non-trivial copy constructor, a non-trivial move constructor, 568 // or a non-trivial destructor, with no corresponding parameter, 569 // is conditionally-supported with implementation-defined semantics. 570 bool TrivialEnough = false; 571 if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType()) { 572 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) { 573 if (Record->hasTrivialCopyConstructor() && 574 Record->hasTrivialMoveConstructor() && 575 Record->hasTrivialDestructor()) { 576 DiagRuntimeBehavior(E->getLocStart(), 0, 577 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 578 << E->getType() << CT); 579 TrivialEnough = true; 580 } 581 } 582 } 583 584 if (!TrivialEnough && 585 getLangOpts().ObjCAutoRefCount && 586 E->getType()->isObjCLifetimeType()) 587 TrivialEnough = true; 588 589 if (TrivialEnough) { 590 // Nothing to diagnose. This is okay. 591 } else if (DiagRuntimeBehavior(E->getLocStart(), 0, 592 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 593 << getLangOpts().CPlusPlus0x << E->getType() 594 << CT)) { 595 // Turn this into a trap. 596 CXXScopeSpec SS; 597 SourceLocation TemplateKWLoc; 598 UnqualifiedId Name; 599 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 600 E->getLocStart()); 601 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 602 true, false); 603 if (TrapFn.isInvalid()) 604 return ExprError(); 605 606 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(), 607 MultiExprArg(), E->getLocEnd()); 608 if (Call.isInvalid()) 609 return ExprError(); 610 611 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 612 Call.get(), E); 613 if (Comma.isInvalid()) 614 return ExprError(); 615 E = Comma.get(); 616 } 617 } 618 // c++ rules are enforced elsewhere. 619 if (!getLangOpts().CPlusPlus && 620 RequireCompleteType(E->getExprLoc(), E->getType(), 621 diag::err_call_incomplete_argument)) 622 return ExprError(); 623 624 return Owned(E); 625} 626 627/// \brief Converts an integer to complex float type. Helper function of 628/// UsualArithmeticConversions() 629/// 630/// \return false if the integer expression is an integer type and is 631/// successfully converted to the complex type. 632static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 633 ExprResult &ComplexExpr, 634 QualType IntTy, 635 QualType ComplexTy, 636 bool SkipCast) { 637 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 638 if (SkipCast) return false; 639 if (IntTy->isIntegerType()) { 640 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 641 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 642 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 643 CK_FloatingRealToComplex); 644 } else { 645 assert(IntTy->isComplexIntegerType()); 646 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 647 CK_IntegralComplexToFloatingComplex); 648 } 649 return false; 650} 651 652/// \brief Takes two complex float types and converts them to the same type. 653/// Helper function of UsualArithmeticConversions() 654static QualType 655handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 656 ExprResult &RHS, QualType LHSType, 657 QualType RHSType, 658 bool IsCompAssign) { 659 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 660 661 if (order < 0) { 662 // _Complex float -> _Complex double 663 if (!IsCompAssign) 664 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 665 return RHSType; 666 } 667 if (order > 0) 668 // _Complex float -> _Complex double 669 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 670 return LHSType; 671} 672 673/// \brief Converts otherExpr to complex float and promotes complexExpr if 674/// necessary. Helper function of UsualArithmeticConversions() 675static QualType handleOtherComplexFloatConversion(Sema &S, 676 ExprResult &ComplexExpr, 677 ExprResult &OtherExpr, 678 QualType ComplexTy, 679 QualType OtherTy, 680 bool ConvertComplexExpr, 681 bool ConvertOtherExpr) { 682 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 683 684 // If just the complexExpr is complex, the otherExpr needs to be converted, 685 // and the complexExpr might need to be promoted. 686 if (order > 0) { // complexExpr is wider 687 // float -> _Complex double 688 if (ConvertOtherExpr) { 689 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 690 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 691 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 692 CK_FloatingRealToComplex); 693 } 694 return ComplexTy; 695 } 696 697 // otherTy is at least as wide. Find its corresponding complex type. 698 QualType result = (order == 0 ? ComplexTy : 699 S.Context.getComplexType(OtherTy)); 700 701 // double -> _Complex double 702 if (ConvertOtherExpr) 703 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 704 CK_FloatingRealToComplex); 705 706 // _Complex float -> _Complex double 707 if (ConvertComplexExpr && order < 0) 708 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 709 CK_FloatingComplexCast); 710 711 return result; 712} 713 714/// \brief Handle arithmetic conversion with complex types. Helper function of 715/// UsualArithmeticConversions() 716static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 717 ExprResult &RHS, QualType LHSType, 718 QualType RHSType, 719 bool IsCompAssign) { 720 // if we have an integer operand, the result is the complex type. 721 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 722 /*skipCast*/false)) 723 return LHSType; 724 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 725 /*skipCast*/IsCompAssign)) 726 return RHSType; 727 728 // This handles complex/complex, complex/float, or float/complex. 729 // When both operands are complex, the shorter operand is converted to the 730 // type of the longer, and that is the type of the result. This corresponds 731 // to what is done when combining two real floating-point operands. 732 // The fun begins when size promotion occur across type domains. 733 // From H&S 6.3.4: When one operand is complex and the other is a real 734 // floating-point type, the less precise type is converted, within it's 735 // real or complex domain, to the precision of the other type. For example, 736 // when combining a "long double" with a "double _Complex", the 737 // "double _Complex" is promoted to "long double _Complex". 738 739 bool LHSComplexFloat = LHSType->isComplexType(); 740 bool RHSComplexFloat = RHSType->isComplexType(); 741 742 // If both are complex, just cast to the more precise type. 743 if (LHSComplexFloat && RHSComplexFloat) 744 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 745 LHSType, RHSType, 746 IsCompAssign); 747 748 // If only one operand is complex, promote it if necessary and convert the 749 // other operand to complex. 750 if (LHSComplexFloat) 751 return handleOtherComplexFloatConversion( 752 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 753 /*convertOtherExpr*/ true); 754 755 assert(RHSComplexFloat); 756 return handleOtherComplexFloatConversion( 757 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 758 /*convertOtherExpr*/ !IsCompAssign); 759} 760 761/// \brief Hande arithmetic conversion from integer to float. Helper function 762/// of UsualArithmeticConversions() 763static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 764 ExprResult &IntExpr, 765 QualType FloatTy, QualType IntTy, 766 bool ConvertFloat, bool ConvertInt) { 767 if (IntTy->isIntegerType()) { 768 if (ConvertInt) 769 // Convert intExpr to the lhs floating point type. 770 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 771 CK_IntegralToFloating); 772 return FloatTy; 773 } 774 775 // Convert both sides to the appropriate complex float. 776 assert(IntTy->isComplexIntegerType()); 777 QualType result = S.Context.getComplexType(FloatTy); 778 779 // _Complex int -> _Complex float 780 if (ConvertInt) 781 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 782 CK_IntegralComplexToFloatingComplex); 783 784 // float -> _Complex float 785 if (ConvertFloat) 786 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 787 CK_FloatingRealToComplex); 788 789 return result; 790} 791 792/// \brief Handle arithmethic conversion with floating point types. Helper 793/// function of UsualArithmeticConversions() 794static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 795 ExprResult &RHS, QualType LHSType, 796 QualType RHSType, bool IsCompAssign) { 797 bool LHSFloat = LHSType->isRealFloatingType(); 798 bool RHSFloat = RHSType->isRealFloatingType(); 799 800 // If we have two real floating types, convert the smaller operand 801 // to the bigger result. 802 if (LHSFloat && RHSFloat) { 803 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 804 if (order > 0) { 805 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 806 return LHSType; 807 } 808 809 assert(order < 0 && "illegal float comparison"); 810 if (!IsCompAssign) 811 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 812 return RHSType; 813 } 814 815 if (LHSFloat) 816 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 817 /*convertFloat=*/!IsCompAssign, 818 /*convertInt=*/ true); 819 assert(RHSFloat); 820 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 821 /*convertInt=*/ true, 822 /*convertFloat=*/!IsCompAssign); 823} 824 825/// \brief Handle conversions with GCC complex int extension. Helper function 826/// of UsualArithmeticConversions() 827// FIXME: if the operands are (int, _Complex long), we currently 828// don't promote the complex. Also, signedness? 829static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 830 ExprResult &RHS, QualType LHSType, 831 QualType RHSType, 832 bool IsCompAssign) { 833 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 834 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 835 836 if (LHSComplexInt && RHSComplexInt) { 837 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(), 838 RHSComplexInt->getElementType()); 839 assert(order && "inequal types with equal element ordering"); 840 if (order > 0) { 841 // _Complex int -> _Complex long 842 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast); 843 return LHSType; 844 } 845 846 if (!IsCompAssign) 847 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast); 848 return RHSType; 849 } 850 851 if (LHSComplexInt) { 852 // int -> _Complex int 853 // FIXME: This needs to take integer ranks into account 854 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(), 855 CK_IntegralCast); 856 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex); 857 return LHSType; 858 } 859 860 assert(RHSComplexInt); 861 // int -> _Complex int 862 // FIXME: This needs to take integer ranks into account 863 if (!IsCompAssign) { 864 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(), 865 CK_IntegralCast); 866 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex); 867 } 868 return RHSType; 869} 870 871/// \brief Handle integer arithmetic conversions. Helper function of 872/// UsualArithmeticConversions() 873static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 874 ExprResult &RHS, QualType LHSType, 875 QualType RHSType, bool IsCompAssign) { 876 // The rules for this case are in C99 6.3.1.8 877 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 878 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 879 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 880 if (LHSSigned == RHSSigned) { 881 // Same signedness; use the higher-ranked type 882 if (order >= 0) { 883 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 884 return LHSType; 885 } else if (!IsCompAssign) 886 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 887 return RHSType; 888 } else if (order != (LHSSigned ? 1 : -1)) { 889 // The unsigned type has greater than or equal rank to the 890 // signed type, so use the unsigned type 891 if (RHSSigned) { 892 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 893 return LHSType; 894 } else if (!IsCompAssign) 895 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 896 return RHSType; 897 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 898 // The two types are different widths; if we are here, that 899 // means the signed type is larger than the unsigned type, so 900 // use the signed type. 901 if (LHSSigned) { 902 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 903 return LHSType; 904 } else if (!IsCompAssign) 905 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 906 return RHSType; 907 } else { 908 // The signed type is higher-ranked than the unsigned type, 909 // but isn't actually any bigger (like unsigned int and long 910 // on most 32-bit systems). Use the unsigned type corresponding 911 // to the signed type. 912 QualType result = 913 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 914 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast); 915 if (!IsCompAssign) 916 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast); 917 return result; 918 } 919} 920 921/// UsualArithmeticConversions - Performs various conversions that are common to 922/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 923/// routine returns the first non-arithmetic type found. The client is 924/// responsible for emitting appropriate error diagnostics. 925/// FIXME: verify the conversion rules for "complex int" are consistent with 926/// GCC. 927QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 928 bool IsCompAssign) { 929 if (!IsCompAssign) { 930 LHS = UsualUnaryConversions(LHS.take()); 931 if (LHS.isInvalid()) 932 return QualType(); 933 } 934 935 RHS = UsualUnaryConversions(RHS.take()); 936 if (RHS.isInvalid()) 937 return QualType(); 938 939 // For conversion purposes, we ignore any qualifiers. 940 // For example, "const float" and "float" are equivalent. 941 QualType LHSType = 942 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 943 QualType RHSType = 944 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 945 946 // If both types are identical, no conversion is needed. 947 if (LHSType == RHSType) 948 return LHSType; 949 950 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 951 // The caller can deal with this (e.g. pointer + int). 952 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 953 return LHSType; 954 955 // Apply unary and bitfield promotions to the LHS's type. 956 QualType LHSUnpromotedType = LHSType; 957 if (LHSType->isPromotableIntegerType()) 958 LHSType = Context.getPromotedIntegerType(LHSType); 959 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 960 if (!LHSBitfieldPromoteTy.isNull()) 961 LHSType = LHSBitfieldPromoteTy; 962 if (LHSType != LHSUnpromotedType && !IsCompAssign) 963 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 964 965 // If both types are identical, no conversion is needed. 966 if (LHSType == RHSType) 967 return LHSType; 968 969 // At this point, we have two different arithmetic types. 970 971 // Handle complex types first (C99 6.3.1.8p1). 972 if (LHSType->isComplexType() || RHSType->isComplexType()) 973 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 974 IsCompAssign); 975 976 // Now handle "real" floating types (i.e. float, double, long double). 977 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 978 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 979 IsCompAssign); 980 981 // Handle GCC complex int extension. 982 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 983 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 984 IsCompAssign); 985 986 // Finally, we have two differing integer types. 987 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType, 988 IsCompAssign); 989} 990 991//===----------------------------------------------------------------------===// 992// Semantic Analysis for various Expression Types 993//===----------------------------------------------------------------------===// 994 995 996ExprResult 997Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 998 SourceLocation DefaultLoc, 999 SourceLocation RParenLoc, 1000 Expr *ControllingExpr, 1001 MultiTypeArg ArgTypes, 1002 MultiExprArg ArgExprs) { 1003 unsigned NumAssocs = ArgTypes.size(); 1004 assert(NumAssocs == ArgExprs.size()); 1005 1006 ParsedType *ParsedTypes = ArgTypes.release(); 1007 Expr **Exprs = ArgExprs.release(); 1008 1009 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1010 for (unsigned i = 0; i < NumAssocs; ++i) { 1011 if (ParsedTypes[i]) 1012 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 1013 else 1014 Types[i] = 0; 1015 } 1016 1017 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1018 ControllingExpr, Types, Exprs, 1019 NumAssocs); 1020 delete [] Types; 1021 return ER; 1022} 1023 1024ExprResult 1025Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1026 SourceLocation DefaultLoc, 1027 SourceLocation RParenLoc, 1028 Expr *ControllingExpr, 1029 TypeSourceInfo **Types, 1030 Expr **Exprs, 1031 unsigned NumAssocs) { 1032 bool TypeErrorFound = false, 1033 IsResultDependent = ControllingExpr->isTypeDependent(), 1034 ContainsUnexpandedParameterPack 1035 = ControllingExpr->containsUnexpandedParameterPack(); 1036 1037 for (unsigned i = 0; i < NumAssocs; ++i) { 1038 if (Exprs[i]->containsUnexpandedParameterPack()) 1039 ContainsUnexpandedParameterPack = true; 1040 1041 if (Types[i]) { 1042 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1043 ContainsUnexpandedParameterPack = true; 1044 1045 if (Types[i]->getType()->isDependentType()) { 1046 IsResultDependent = true; 1047 } else { 1048 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1049 // complete object type other than a variably modified type." 1050 unsigned D = 0; 1051 if (Types[i]->getType()->isIncompleteType()) 1052 D = diag::err_assoc_type_incomplete; 1053 else if (!Types[i]->getType()->isObjectType()) 1054 D = diag::err_assoc_type_nonobject; 1055 else if (Types[i]->getType()->isVariablyModifiedType()) 1056 D = diag::err_assoc_type_variably_modified; 1057 1058 if (D != 0) { 1059 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1060 << Types[i]->getTypeLoc().getSourceRange() 1061 << Types[i]->getType(); 1062 TypeErrorFound = true; 1063 } 1064 1065 // C11 6.5.1.1p2 "No two generic associations in the same generic 1066 // selection shall specify compatible types." 1067 for (unsigned j = i+1; j < NumAssocs; ++j) 1068 if (Types[j] && !Types[j]->getType()->isDependentType() && 1069 Context.typesAreCompatible(Types[i]->getType(), 1070 Types[j]->getType())) { 1071 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1072 diag::err_assoc_compatible_types) 1073 << Types[j]->getTypeLoc().getSourceRange() 1074 << Types[j]->getType() 1075 << Types[i]->getType(); 1076 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1077 diag::note_compat_assoc) 1078 << Types[i]->getTypeLoc().getSourceRange() 1079 << Types[i]->getType(); 1080 TypeErrorFound = true; 1081 } 1082 } 1083 } 1084 } 1085 if (TypeErrorFound) 1086 return ExprError(); 1087 1088 // If we determined that the generic selection is result-dependent, don't 1089 // try to compute the result expression. 1090 if (IsResultDependent) 1091 return Owned(new (Context) GenericSelectionExpr( 1092 Context, KeyLoc, ControllingExpr, 1093 Types, Exprs, NumAssocs, DefaultLoc, 1094 RParenLoc, ContainsUnexpandedParameterPack)); 1095 1096 SmallVector<unsigned, 1> CompatIndices; 1097 unsigned DefaultIndex = -1U; 1098 for (unsigned i = 0; i < NumAssocs; ++i) { 1099 if (!Types[i]) 1100 DefaultIndex = i; 1101 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1102 Types[i]->getType())) 1103 CompatIndices.push_back(i); 1104 } 1105 1106 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1107 // type compatible with at most one of the types named in its generic 1108 // association list." 1109 if (CompatIndices.size() > 1) { 1110 // We strip parens here because the controlling expression is typically 1111 // parenthesized in macro definitions. 1112 ControllingExpr = ControllingExpr->IgnoreParens(); 1113 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1114 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1115 << (unsigned) CompatIndices.size(); 1116 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1117 E = CompatIndices.end(); I != E; ++I) { 1118 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1119 diag::note_compat_assoc) 1120 << Types[*I]->getTypeLoc().getSourceRange() 1121 << Types[*I]->getType(); 1122 } 1123 return ExprError(); 1124 } 1125 1126 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1127 // its controlling expression shall have type compatible with exactly one of 1128 // the types named in its generic association list." 1129 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1130 // We strip parens here because the controlling expression is typically 1131 // parenthesized in macro definitions. 1132 ControllingExpr = ControllingExpr->IgnoreParens(); 1133 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1134 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1135 return ExprError(); 1136 } 1137 1138 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1139 // type name that is compatible with the type of the controlling expression, 1140 // then the result expression of the generic selection is the expression 1141 // in that generic association. Otherwise, the result expression of the 1142 // generic selection is the expression in the default generic association." 1143 unsigned ResultIndex = 1144 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1145 1146 return Owned(new (Context) GenericSelectionExpr( 1147 Context, KeyLoc, ControllingExpr, 1148 Types, Exprs, NumAssocs, DefaultLoc, 1149 RParenLoc, ContainsUnexpandedParameterPack, 1150 ResultIndex)); 1151} 1152 1153/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1154/// location of the token and the offset of the ud-suffix within it. 1155static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1156 unsigned Offset) { 1157 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1158 S.getLangOpts()); 1159} 1160 1161/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1162/// the corresponding cooked (non-raw) literal operator, and build a call to it. 1163static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1164 IdentifierInfo *UDSuffix, 1165 SourceLocation UDSuffixLoc, 1166 ArrayRef<Expr*> Args, 1167 SourceLocation LitEndLoc) { 1168 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1169 1170 QualType ArgTy[2]; 1171 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1172 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1173 if (ArgTy[ArgIdx]->isArrayType()) 1174 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1175 } 1176 1177 DeclarationName OpName = 1178 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1179 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1180 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1181 1182 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1183 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1184 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1185 return ExprError(); 1186 1187 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1188} 1189 1190/// ActOnStringLiteral - The specified tokens were lexed as pasted string 1191/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1192/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1193/// multiple tokens. However, the common case is that StringToks points to one 1194/// string. 1195/// 1196ExprResult 1197Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1198 Scope *UDLScope) { 1199 assert(NumStringToks && "Must have at least one string!"); 1200 1201 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1202 if (Literal.hadError) 1203 return ExprError(); 1204 1205 SmallVector<SourceLocation, 4> StringTokLocs; 1206 for (unsigned i = 0; i != NumStringToks; ++i) 1207 StringTokLocs.push_back(StringToks[i].getLocation()); 1208 1209 QualType StrTy = Context.CharTy; 1210 if (Literal.isWide()) 1211 StrTy = Context.getWCharType(); 1212 else if (Literal.isUTF16()) 1213 StrTy = Context.Char16Ty; 1214 else if (Literal.isUTF32()) 1215 StrTy = Context.Char32Ty; 1216 else if (Literal.isPascal()) 1217 StrTy = Context.UnsignedCharTy; 1218 1219 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1220 if (Literal.isWide()) 1221 Kind = StringLiteral::Wide; 1222 else if (Literal.isUTF8()) 1223 Kind = StringLiteral::UTF8; 1224 else if (Literal.isUTF16()) 1225 Kind = StringLiteral::UTF16; 1226 else if (Literal.isUTF32()) 1227 Kind = StringLiteral::UTF32; 1228 1229 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1230 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1231 StrTy.addConst(); 1232 1233 // Get an array type for the string, according to C99 6.4.5. This includes 1234 // the nul terminator character as well as the string length for pascal 1235 // strings. 1236 StrTy = Context.getConstantArrayType(StrTy, 1237 llvm::APInt(32, Literal.GetNumStringChars()+1), 1238 ArrayType::Normal, 0); 1239 1240 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1241 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1242 Kind, Literal.Pascal, StrTy, 1243 &StringTokLocs[0], 1244 StringTokLocs.size()); 1245 if (Literal.getUDSuffix().empty()) 1246 return Owned(Lit); 1247 1248 // We're building a user-defined literal. 1249 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1250 SourceLocation UDSuffixLoc = 1251 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1252 Literal.getUDSuffixOffset()); 1253 1254 // Make sure we're allowed user-defined literals here. 1255 if (!UDLScope) 1256 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1257 1258 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1259 // operator "" X (str, len) 1260 QualType SizeType = Context.getSizeType(); 1261 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1262 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1263 StringTokLocs[0]); 1264 Expr *Args[] = { Lit, LenArg }; 1265 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1266 Args, StringTokLocs.back()); 1267} 1268 1269ExprResult 1270Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1271 SourceLocation Loc, 1272 const CXXScopeSpec *SS) { 1273 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1274 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1275} 1276 1277/// BuildDeclRefExpr - Build an expression that references a 1278/// declaration that does not require a closure capture. 1279ExprResult 1280Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1281 const DeclarationNameInfo &NameInfo, 1282 const CXXScopeSpec *SS) { 1283 if (getLangOpts().CUDA) 1284 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1285 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1286 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1287 CalleeTarget = IdentifyCUDATarget(Callee); 1288 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1289 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1290 << CalleeTarget << D->getIdentifier() << CallerTarget; 1291 Diag(D->getLocation(), diag::note_previous_decl) 1292 << D->getIdentifier(); 1293 return ExprError(); 1294 } 1295 } 1296 1297 bool refersToEnclosingScope = 1298 (CurContext != D->getDeclContext() && 1299 D->getDeclContext()->isFunctionOrMethod()); 1300 1301 DeclRefExpr *E = DeclRefExpr::Create(Context, 1302 SS ? SS->getWithLocInContext(Context) 1303 : NestedNameSpecifierLoc(), 1304 SourceLocation(), 1305 D, refersToEnclosingScope, 1306 NameInfo, Ty, VK); 1307 1308 MarkDeclRefReferenced(E); 1309 1310 // Just in case we're building an illegal pointer-to-member. 1311 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1312 if (FD && FD->isBitField()) 1313 E->setObjectKind(OK_BitField); 1314 1315 return Owned(E); 1316} 1317 1318/// Decomposes the given name into a DeclarationNameInfo, its location, and 1319/// possibly a list of template arguments. 1320/// 1321/// If this produces template arguments, it is permitted to call 1322/// DecomposeTemplateName. 1323/// 1324/// This actually loses a lot of source location information for 1325/// non-standard name kinds; we should consider preserving that in 1326/// some way. 1327void 1328Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1329 TemplateArgumentListInfo &Buffer, 1330 DeclarationNameInfo &NameInfo, 1331 const TemplateArgumentListInfo *&TemplateArgs) { 1332 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1333 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1334 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1335 1336 ASTTemplateArgsPtr TemplateArgsPtr(*this, 1337 Id.TemplateId->getTemplateArgs(), 1338 Id.TemplateId->NumArgs); 1339 translateTemplateArguments(TemplateArgsPtr, Buffer); 1340 TemplateArgsPtr.release(); 1341 1342 TemplateName TName = Id.TemplateId->Template.get(); 1343 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1344 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1345 TemplateArgs = &Buffer; 1346 } else { 1347 NameInfo = GetNameFromUnqualifiedId(Id); 1348 TemplateArgs = 0; 1349 } 1350} 1351 1352/// Diagnose an empty lookup. 1353/// 1354/// \return false if new lookup candidates were found 1355bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1356 CorrectionCandidateCallback &CCC, 1357 TemplateArgumentListInfo *ExplicitTemplateArgs, 1358 llvm::ArrayRef<Expr *> Args) { 1359 DeclarationName Name = R.getLookupName(); 1360 1361 unsigned diagnostic = diag::err_undeclared_var_use; 1362 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1363 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1364 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1365 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1366 diagnostic = diag::err_undeclared_use; 1367 diagnostic_suggest = diag::err_undeclared_use_suggest; 1368 } 1369 1370 // If the original lookup was an unqualified lookup, fake an 1371 // unqualified lookup. This is useful when (for example) the 1372 // original lookup would not have found something because it was a 1373 // dependent name. 1374 DeclContext *DC = SS.isEmpty() ? CurContext : 0; 1375 while (DC) { 1376 if (isa<CXXRecordDecl>(DC)) { 1377 LookupQualifiedName(R, DC); 1378 1379 if (!R.empty()) { 1380 // Don't give errors about ambiguities in this lookup. 1381 R.suppressDiagnostics(); 1382 1383 // During a default argument instantiation the CurContext points 1384 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1385 // function parameter list, hence add an explicit check. 1386 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1387 ActiveTemplateInstantiations.back().Kind == 1388 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1389 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1390 bool isInstance = CurMethod && 1391 CurMethod->isInstance() && 1392 DC == CurMethod->getParent() && !isDefaultArgument; 1393 1394 1395 // Give a code modification hint to insert 'this->'. 1396 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1397 // Actually quite difficult! 1398 if (isInstance) { 1399 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1400 CallsUndergoingInstantiation.back()->getCallee()); 1401 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>( 1402 CurMethod->getInstantiatedFromMemberFunction()); 1403 if (DepMethod) { 1404 if (getLangOpts().MicrosoftMode) 1405 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1406 Diag(R.getNameLoc(), diagnostic) << Name 1407 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1408 QualType DepThisType = DepMethod->getThisType(Context); 1409 CheckCXXThisCapture(R.getNameLoc()); 1410 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1411 R.getNameLoc(), DepThisType, false); 1412 TemplateArgumentListInfo TList; 1413 if (ULE->hasExplicitTemplateArgs()) 1414 ULE->copyTemplateArgumentsInto(TList); 1415 1416 CXXScopeSpec SS; 1417 SS.Adopt(ULE->getQualifierLoc()); 1418 CXXDependentScopeMemberExpr *DepExpr = 1419 CXXDependentScopeMemberExpr::Create( 1420 Context, DepThis, DepThisType, true, SourceLocation(), 1421 SS.getWithLocInContext(Context), 1422 ULE->getTemplateKeywordLoc(), 0, 1423 R.getLookupNameInfo(), 1424 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1425 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1426 } else { 1427 // FIXME: we should be able to handle this case too. It is correct 1428 // to add this-> here. This is a workaround for PR7947. 1429 Diag(R.getNameLoc(), diagnostic) << Name; 1430 } 1431 } else { 1432 if (getLangOpts().MicrosoftMode) 1433 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1434 Diag(R.getNameLoc(), diagnostic) << Name; 1435 } 1436 1437 // Do we really want to note all of these? 1438 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1439 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1440 1441 // Return true if we are inside a default argument instantiation 1442 // and the found name refers to an instance member function, otherwise 1443 // the function calling DiagnoseEmptyLookup will try to create an 1444 // implicit member call and this is wrong for default argument. 1445 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1446 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1447 return true; 1448 } 1449 1450 // Tell the callee to try to recover. 1451 return false; 1452 } 1453 1454 R.clear(); 1455 } 1456 1457 // In Microsoft mode, if we are performing lookup from within a friend 1458 // function definition declared at class scope then we must set 1459 // DC to the lexical parent to be able to search into the parent 1460 // class. 1461 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1462 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1463 DC->getLexicalParent()->isRecord()) 1464 DC = DC->getLexicalParent(); 1465 else 1466 DC = DC->getParent(); 1467 } 1468 1469 // We didn't find anything, so try to correct for a typo. 1470 TypoCorrection Corrected; 1471 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1472 S, &SS, CCC))) { 1473 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1474 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1475 R.setLookupName(Corrected.getCorrection()); 1476 1477 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1478 if (Corrected.isOverloaded()) { 1479 OverloadCandidateSet OCS(R.getNameLoc()); 1480 OverloadCandidateSet::iterator Best; 1481 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1482 CDEnd = Corrected.end(); 1483 CD != CDEnd; ++CD) { 1484 if (FunctionTemplateDecl *FTD = 1485 dyn_cast<FunctionTemplateDecl>(*CD)) 1486 AddTemplateOverloadCandidate( 1487 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1488 Args, OCS); 1489 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1490 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1491 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1492 Args, OCS); 1493 } 1494 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1495 case OR_Success: 1496 ND = Best->Function; 1497 break; 1498 default: 1499 break; 1500 } 1501 } 1502 R.addDecl(ND); 1503 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1504 if (SS.isEmpty()) 1505 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1506 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1507 else 1508 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1509 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1510 << SS.getRange() 1511 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1512 if (ND) 1513 Diag(ND->getLocation(), diag::note_previous_decl) 1514 << CorrectedQuotedStr; 1515 1516 // Tell the callee to try to recover. 1517 return false; 1518 } 1519 1520 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1521 // FIXME: If we ended up with a typo for a type name or 1522 // Objective-C class name, we're in trouble because the parser 1523 // is in the wrong place to recover. Suggest the typo 1524 // correction, but don't make it a fix-it since we're not going 1525 // to recover well anyway. 1526 if (SS.isEmpty()) 1527 Diag(R.getNameLoc(), diagnostic_suggest) 1528 << Name << CorrectedQuotedStr; 1529 else 1530 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1531 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1532 << SS.getRange(); 1533 1534 // Don't try to recover; it won't work. 1535 return true; 1536 } 1537 } else { 1538 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1539 // because we aren't able to recover. 1540 if (SS.isEmpty()) 1541 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1542 else 1543 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1544 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1545 << SS.getRange(); 1546 return true; 1547 } 1548 } 1549 R.clear(); 1550 1551 // Emit a special diagnostic for failed member lookups. 1552 // FIXME: computing the declaration context might fail here (?) 1553 if (!SS.isEmpty()) { 1554 Diag(R.getNameLoc(), diag::err_no_member) 1555 << Name << computeDeclContext(SS, false) 1556 << SS.getRange(); 1557 return true; 1558 } 1559 1560 // Give up, we can't recover. 1561 Diag(R.getNameLoc(), diagnostic) << Name; 1562 return true; 1563} 1564 1565ExprResult Sema::ActOnIdExpression(Scope *S, 1566 CXXScopeSpec &SS, 1567 SourceLocation TemplateKWLoc, 1568 UnqualifiedId &Id, 1569 bool HasTrailingLParen, 1570 bool IsAddressOfOperand, 1571 CorrectionCandidateCallback *CCC) { 1572 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1573 "cannot be direct & operand and have a trailing lparen"); 1574 1575 if (SS.isInvalid()) 1576 return ExprError(); 1577 1578 TemplateArgumentListInfo TemplateArgsBuffer; 1579 1580 // Decompose the UnqualifiedId into the following data. 1581 DeclarationNameInfo NameInfo; 1582 const TemplateArgumentListInfo *TemplateArgs; 1583 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1584 1585 DeclarationName Name = NameInfo.getName(); 1586 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1587 SourceLocation NameLoc = NameInfo.getLoc(); 1588 1589 // C++ [temp.dep.expr]p3: 1590 // An id-expression is type-dependent if it contains: 1591 // -- an identifier that was declared with a dependent type, 1592 // (note: handled after lookup) 1593 // -- a template-id that is dependent, 1594 // (note: handled in BuildTemplateIdExpr) 1595 // -- a conversion-function-id that specifies a dependent type, 1596 // -- a nested-name-specifier that contains a class-name that 1597 // names a dependent type. 1598 // Determine whether this is a member of an unknown specialization; 1599 // we need to handle these differently. 1600 bool DependentID = false; 1601 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1602 Name.getCXXNameType()->isDependentType()) { 1603 DependentID = true; 1604 } else if (SS.isSet()) { 1605 if (DeclContext *DC = computeDeclContext(SS, false)) { 1606 if (RequireCompleteDeclContext(SS, DC)) 1607 return ExprError(); 1608 } else { 1609 DependentID = true; 1610 } 1611 } 1612 1613 if (DependentID) 1614 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1615 IsAddressOfOperand, TemplateArgs); 1616 1617 // Perform the required lookup. 1618 LookupResult R(*this, NameInfo, 1619 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1620 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1621 if (TemplateArgs) { 1622 // Lookup the template name again to correctly establish the context in 1623 // which it was found. This is really unfortunate as we already did the 1624 // lookup to determine that it was a template name in the first place. If 1625 // this becomes a performance hit, we can work harder to preserve those 1626 // results until we get here but it's likely not worth it. 1627 bool MemberOfUnknownSpecialization; 1628 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1629 MemberOfUnknownSpecialization); 1630 1631 if (MemberOfUnknownSpecialization || 1632 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1633 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1634 IsAddressOfOperand, TemplateArgs); 1635 } else { 1636 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1637 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1638 1639 // If the result might be in a dependent base class, this is a dependent 1640 // id-expression. 1641 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1642 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1643 IsAddressOfOperand, TemplateArgs); 1644 1645 // If this reference is in an Objective-C method, then we need to do 1646 // some special Objective-C lookup, too. 1647 if (IvarLookupFollowUp) { 1648 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1649 if (E.isInvalid()) 1650 return ExprError(); 1651 1652 if (Expr *Ex = E.takeAs<Expr>()) 1653 return Owned(Ex); 1654 } 1655 } 1656 1657 if (R.isAmbiguous()) 1658 return ExprError(); 1659 1660 // Determine whether this name might be a candidate for 1661 // argument-dependent lookup. 1662 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1663 1664 if (R.empty() && !ADL) { 1665 // Otherwise, this could be an implicitly declared function reference (legal 1666 // in C90, extension in C99, forbidden in C++). 1667 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1668 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1669 if (D) R.addDecl(D); 1670 } 1671 1672 // If this name wasn't predeclared and if this is not a function 1673 // call, diagnose the problem. 1674 if (R.empty()) { 1675 1676 // In Microsoft mode, if we are inside a template class member function 1677 // and we can't resolve an identifier then assume the identifier is type 1678 // dependent. The goal is to postpone name lookup to instantiation time 1679 // to be able to search into type dependent base classes. 1680 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 1681 isa<CXXMethodDecl>(CurContext)) 1682 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1683 IsAddressOfOperand, TemplateArgs); 1684 1685 CorrectionCandidateCallback DefaultValidator; 1686 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1687 return ExprError(); 1688 1689 assert(!R.empty() && 1690 "DiagnoseEmptyLookup returned false but added no results"); 1691 1692 // If we found an Objective-C instance variable, let 1693 // LookupInObjCMethod build the appropriate expression to 1694 // reference the ivar. 1695 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1696 R.clear(); 1697 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1698 // In a hopelessly buggy code, Objective-C instance variable 1699 // lookup fails and no expression will be built to reference it. 1700 if (!E.isInvalid() && !E.get()) 1701 return ExprError(); 1702 return move(E); 1703 } 1704 } 1705 } 1706 1707 // This is guaranteed from this point on. 1708 assert(!R.empty() || ADL); 1709 1710 // Check whether this might be a C++ implicit instance member access. 1711 // C++ [class.mfct.non-static]p3: 1712 // When an id-expression that is not part of a class member access 1713 // syntax and not used to form a pointer to member is used in the 1714 // body of a non-static member function of class X, if name lookup 1715 // resolves the name in the id-expression to a non-static non-type 1716 // member of some class C, the id-expression is transformed into a 1717 // class member access expression using (*this) as the 1718 // postfix-expression to the left of the . operator. 1719 // 1720 // But we don't actually need to do this for '&' operands if R 1721 // resolved to a function or overloaded function set, because the 1722 // expression is ill-formed if it actually works out to be a 1723 // non-static member function: 1724 // 1725 // C++ [expr.ref]p4: 1726 // Otherwise, if E1.E2 refers to a non-static member function. . . 1727 // [t]he expression can be used only as the left-hand operand of a 1728 // member function call. 1729 // 1730 // There are other safeguards against such uses, but it's important 1731 // to get this right here so that we don't end up making a 1732 // spuriously dependent expression if we're inside a dependent 1733 // instance method. 1734 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1735 bool MightBeImplicitMember; 1736 if (!IsAddressOfOperand) 1737 MightBeImplicitMember = true; 1738 else if (!SS.isEmpty()) 1739 MightBeImplicitMember = false; 1740 else if (R.isOverloadedResult()) 1741 MightBeImplicitMember = false; 1742 else if (R.isUnresolvableResult()) 1743 MightBeImplicitMember = true; 1744 else 1745 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1746 isa<IndirectFieldDecl>(R.getFoundDecl()); 1747 1748 if (MightBeImplicitMember) 1749 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 1750 R, TemplateArgs); 1751 } 1752 1753 if (TemplateArgs || TemplateKWLoc.isValid()) 1754 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 1755 1756 return BuildDeclarationNameExpr(SS, R, ADL); 1757} 1758 1759/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1760/// declaration name, generally during template instantiation. 1761/// There's a large number of things which don't need to be done along 1762/// this path. 1763ExprResult 1764Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1765 const DeclarationNameInfo &NameInfo) { 1766 DeclContext *DC; 1767 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext()) 1768 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 1769 NameInfo, /*TemplateArgs=*/0); 1770 1771 if (RequireCompleteDeclContext(SS, DC)) 1772 return ExprError(); 1773 1774 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1775 LookupQualifiedName(R, DC); 1776 1777 if (R.isAmbiguous()) 1778 return ExprError(); 1779 1780 if (R.empty()) { 1781 Diag(NameInfo.getLoc(), diag::err_no_member) 1782 << NameInfo.getName() << DC << SS.getRange(); 1783 return ExprError(); 1784 } 1785 1786 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1787} 1788 1789/// LookupInObjCMethod - The parser has read a name in, and Sema has 1790/// detected that we're currently inside an ObjC method. Perform some 1791/// additional lookup. 1792/// 1793/// Ideally, most of this would be done by lookup, but there's 1794/// actually quite a lot of extra work involved. 1795/// 1796/// Returns a null sentinel to indicate trivial success. 1797ExprResult 1798Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1799 IdentifierInfo *II, bool AllowBuiltinCreation) { 1800 SourceLocation Loc = Lookup.getNameLoc(); 1801 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1802 1803 // There are two cases to handle here. 1) scoped lookup could have failed, 1804 // in which case we should look for an ivar. 2) scoped lookup could have 1805 // found a decl, but that decl is outside the current instance method (i.e. 1806 // a global variable). In these two cases, we do a lookup for an ivar with 1807 // this name, if the lookup sucedes, we replace it our current decl. 1808 1809 // If we're in a class method, we don't normally want to look for 1810 // ivars. But if we don't find anything else, and there's an 1811 // ivar, that's an error. 1812 bool IsClassMethod = CurMethod->isClassMethod(); 1813 1814 bool LookForIvars; 1815 if (Lookup.empty()) 1816 LookForIvars = true; 1817 else if (IsClassMethod) 1818 LookForIvars = false; 1819 else 1820 LookForIvars = (Lookup.isSingleResult() && 1821 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1822 ObjCInterfaceDecl *IFace = 0; 1823 if (LookForIvars) { 1824 IFace = CurMethod->getClassInterface(); 1825 ObjCInterfaceDecl *ClassDeclared; 1826 ObjCIvarDecl *IV = 0; 1827 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 1828 // Diagnose using an ivar in a class method. 1829 if (IsClassMethod) 1830 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1831 << IV->getDeclName()); 1832 1833 // If we're referencing an invalid decl, just return this as a silent 1834 // error node. The error diagnostic was already emitted on the decl. 1835 if (IV->isInvalidDecl()) 1836 return ExprError(); 1837 1838 // Check if referencing a field with __attribute__((deprecated)). 1839 if (DiagnoseUseOfDecl(IV, Loc)) 1840 return ExprError(); 1841 1842 // Diagnose the use of an ivar outside of the declaring class. 1843 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1844 !declaresSameEntity(ClassDeclared, IFace) && 1845 !getLangOpts().DebuggerSupport) 1846 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1847 1848 // FIXME: This should use a new expr for a direct reference, don't 1849 // turn this into Self->ivar, just return a BareIVarExpr or something. 1850 IdentifierInfo &II = Context.Idents.get("self"); 1851 UnqualifiedId SelfName; 1852 SelfName.setIdentifier(&II, SourceLocation()); 1853 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 1854 CXXScopeSpec SelfScopeSpec; 1855 SourceLocation TemplateKWLoc; 1856 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 1857 SelfName, false, false); 1858 if (SelfExpr.isInvalid()) 1859 return ExprError(); 1860 1861 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 1862 if (SelfExpr.isInvalid()) 1863 return ExprError(); 1864 1865 MarkAnyDeclReferenced(Loc, IV); 1866 return Owned(new (Context) 1867 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1868 SelfExpr.take(), true, true)); 1869 } 1870 } else if (CurMethod->isInstanceMethod()) { 1871 // We should warn if a local variable hides an ivar. 1872 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 1873 ObjCInterfaceDecl *ClassDeclared; 1874 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1875 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1876 declaresSameEntity(IFace, ClassDeclared)) 1877 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1878 } 1879 } 1880 } else if (Lookup.isSingleResult() && 1881 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 1882 // If accessing a stand-alone ivar in a class method, this is an error. 1883 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 1884 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1885 << IV->getDeclName()); 1886 } 1887 1888 if (Lookup.empty() && II && AllowBuiltinCreation) { 1889 // FIXME. Consolidate this with similar code in LookupName. 1890 if (unsigned BuiltinID = II->getBuiltinID()) { 1891 if (!(getLangOpts().CPlusPlus && 1892 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1893 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1894 S, Lookup.isForRedeclaration(), 1895 Lookup.getNameLoc()); 1896 if (D) Lookup.addDecl(D); 1897 } 1898 } 1899 } 1900 // Sentinel value saying that we didn't do anything special. 1901 return Owned((Expr*) 0); 1902} 1903 1904/// \brief Cast a base object to a member's actual type. 1905/// 1906/// Logically this happens in three phases: 1907/// 1908/// * First we cast from the base type to the naming class. 1909/// The naming class is the class into which we were looking 1910/// when we found the member; it's the qualifier type if a 1911/// qualifier was provided, and otherwise it's the base type. 1912/// 1913/// * Next we cast from the naming class to the declaring class. 1914/// If the member we found was brought into a class's scope by 1915/// a using declaration, this is that class; otherwise it's 1916/// the class declaring the member. 1917/// 1918/// * Finally we cast from the declaring class to the "true" 1919/// declaring class of the member. This conversion does not 1920/// obey access control. 1921ExprResult 1922Sema::PerformObjectMemberConversion(Expr *From, 1923 NestedNameSpecifier *Qualifier, 1924 NamedDecl *FoundDecl, 1925 NamedDecl *Member) { 1926 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 1927 if (!RD) 1928 return Owned(From); 1929 1930 QualType DestRecordType; 1931 QualType DestType; 1932 QualType FromRecordType; 1933 QualType FromType = From->getType(); 1934 bool PointerConversions = false; 1935 if (isa<FieldDecl>(Member)) { 1936 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 1937 1938 if (FromType->getAs<PointerType>()) { 1939 DestType = Context.getPointerType(DestRecordType); 1940 FromRecordType = FromType->getPointeeType(); 1941 PointerConversions = true; 1942 } else { 1943 DestType = DestRecordType; 1944 FromRecordType = FromType; 1945 } 1946 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 1947 if (Method->isStatic()) 1948 return Owned(From); 1949 1950 DestType = Method->getThisType(Context); 1951 DestRecordType = DestType->getPointeeType(); 1952 1953 if (FromType->getAs<PointerType>()) { 1954 FromRecordType = FromType->getPointeeType(); 1955 PointerConversions = true; 1956 } else { 1957 FromRecordType = FromType; 1958 DestType = DestRecordType; 1959 } 1960 } else { 1961 // No conversion necessary. 1962 return Owned(From); 1963 } 1964 1965 if (DestType->isDependentType() || FromType->isDependentType()) 1966 return Owned(From); 1967 1968 // If the unqualified types are the same, no conversion is necessary. 1969 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1970 return Owned(From); 1971 1972 SourceRange FromRange = From->getSourceRange(); 1973 SourceLocation FromLoc = FromRange.getBegin(); 1974 1975 ExprValueKind VK = From->getValueKind(); 1976 1977 // C++ [class.member.lookup]p8: 1978 // [...] Ambiguities can often be resolved by qualifying a name with its 1979 // class name. 1980 // 1981 // If the member was a qualified name and the qualified referred to a 1982 // specific base subobject type, we'll cast to that intermediate type 1983 // first and then to the object in which the member is declared. That allows 1984 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 1985 // 1986 // class Base { public: int x; }; 1987 // class Derived1 : public Base { }; 1988 // class Derived2 : public Base { }; 1989 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 1990 // 1991 // void VeryDerived::f() { 1992 // x = 17; // error: ambiguous base subobjects 1993 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 1994 // } 1995 if (Qualifier) { 1996 QualType QType = QualType(Qualifier->getAsType(), 0); 1997 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 1998 assert(QType->isRecordType() && "lookup done with non-record type"); 1999 2000 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2001 2002 // In C++98, the qualifier type doesn't actually have to be a base 2003 // type of the object type, in which case we just ignore it. 2004 // Otherwise build the appropriate casts. 2005 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2006 CXXCastPath BasePath; 2007 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2008 FromLoc, FromRange, &BasePath)) 2009 return ExprError(); 2010 2011 if (PointerConversions) 2012 QType = Context.getPointerType(QType); 2013 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2014 VK, &BasePath).take(); 2015 2016 FromType = QType; 2017 FromRecordType = QRecordType; 2018 2019 // If the qualifier type was the same as the destination type, 2020 // we're done. 2021 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2022 return Owned(From); 2023 } 2024 } 2025 2026 bool IgnoreAccess = false; 2027 2028 // If we actually found the member through a using declaration, cast 2029 // down to the using declaration's type. 2030 // 2031 // Pointer equality is fine here because only one declaration of a 2032 // class ever has member declarations. 2033 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2034 assert(isa<UsingShadowDecl>(FoundDecl)); 2035 QualType URecordType = Context.getTypeDeclType( 2036 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2037 2038 // We only need to do this if the naming-class to declaring-class 2039 // conversion is non-trivial. 2040 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2041 assert(IsDerivedFrom(FromRecordType, URecordType)); 2042 CXXCastPath BasePath; 2043 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2044 FromLoc, FromRange, &BasePath)) 2045 return ExprError(); 2046 2047 QualType UType = URecordType; 2048 if (PointerConversions) 2049 UType = Context.getPointerType(UType); 2050 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2051 VK, &BasePath).take(); 2052 FromType = UType; 2053 FromRecordType = URecordType; 2054 } 2055 2056 // We don't do access control for the conversion from the 2057 // declaring class to the true declaring class. 2058 IgnoreAccess = true; 2059 } 2060 2061 CXXCastPath BasePath; 2062 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2063 FromLoc, FromRange, &BasePath, 2064 IgnoreAccess)) 2065 return ExprError(); 2066 2067 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2068 VK, &BasePath); 2069} 2070 2071bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2072 const LookupResult &R, 2073 bool HasTrailingLParen) { 2074 // Only when used directly as the postfix-expression of a call. 2075 if (!HasTrailingLParen) 2076 return false; 2077 2078 // Never if a scope specifier was provided. 2079 if (SS.isSet()) 2080 return false; 2081 2082 // Only in C++ or ObjC++. 2083 if (!getLangOpts().CPlusPlus) 2084 return false; 2085 2086 // Turn off ADL when we find certain kinds of declarations during 2087 // normal lookup: 2088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2089 NamedDecl *D = *I; 2090 2091 // C++0x [basic.lookup.argdep]p3: 2092 // -- a declaration of a class member 2093 // Since using decls preserve this property, we check this on the 2094 // original decl. 2095 if (D->isCXXClassMember()) 2096 return false; 2097 2098 // C++0x [basic.lookup.argdep]p3: 2099 // -- a block-scope function declaration that is not a 2100 // using-declaration 2101 // NOTE: we also trigger this for function templates (in fact, we 2102 // don't check the decl type at all, since all other decl types 2103 // turn off ADL anyway). 2104 if (isa<UsingShadowDecl>(D)) 2105 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2106 else if (D->getDeclContext()->isFunctionOrMethod()) 2107 return false; 2108 2109 // C++0x [basic.lookup.argdep]p3: 2110 // -- a declaration that is neither a function or a function 2111 // template 2112 // And also for builtin functions. 2113 if (isa<FunctionDecl>(D)) { 2114 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2115 2116 // But also builtin functions. 2117 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2118 return false; 2119 } else if (!isa<FunctionTemplateDecl>(D)) 2120 return false; 2121 } 2122 2123 return true; 2124} 2125 2126 2127/// Diagnoses obvious problems with the use of the given declaration 2128/// as an expression. This is only actually called for lookups that 2129/// were not overloaded, and it doesn't promise that the declaration 2130/// will in fact be used. 2131static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2132 if (isa<TypedefNameDecl>(D)) { 2133 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2134 return true; 2135 } 2136 2137 if (isa<ObjCInterfaceDecl>(D)) { 2138 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2139 return true; 2140 } 2141 2142 if (isa<NamespaceDecl>(D)) { 2143 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2144 return true; 2145 } 2146 2147 return false; 2148} 2149 2150ExprResult 2151Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2152 LookupResult &R, 2153 bool NeedsADL) { 2154 // If this is a single, fully-resolved result and we don't need ADL, 2155 // just build an ordinary singleton decl ref. 2156 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 2158 R.getFoundDecl()); 2159 2160 // We only need to check the declaration if there's exactly one 2161 // result, because in the overloaded case the results can only be 2162 // functions and function templates. 2163 if (R.isSingleResult() && 2164 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2165 return ExprError(); 2166 2167 // Otherwise, just build an unresolved lookup expression. Suppress 2168 // any lookup-related diagnostics; we'll hash these out later, when 2169 // we've picked a target. 2170 R.suppressDiagnostics(); 2171 2172 UnresolvedLookupExpr *ULE 2173 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2174 SS.getWithLocInContext(Context), 2175 R.getLookupNameInfo(), 2176 NeedsADL, R.isOverloadedResult(), 2177 R.begin(), R.end()); 2178 2179 return Owned(ULE); 2180} 2181 2182/// \brief Complete semantic analysis for a reference to the given declaration. 2183ExprResult 2184Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2185 const DeclarationNameInfo &NameInfo, 2186 NamedDecl *D) { 2187 assert(D && "Cannot refer to a NULL declaration"); 2188 assert(!isa<FunctionTemplateDecl>(D) && 2189 "Cannot refer unambiguously to a function template"); 2190 2191 SourceLocation Loc = NameInfo.getLoc(); 2192 if (CheckDeclInExpr(*this, Loc, D)) 2193 return ExprError(); 2194 2195 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2196 // Specifically diagnose references to class templates that are missing 2197 // a template argument list. 2198 Diag(Loc, diag::err_template_decl_ref) 2199 << Template << SS.getRange(); 2200 Diag(Template->getLocation(), diag::note_template_decl_here); 2201 return ExprError(); 2202 } 2203 2204 // Make sure that we're referring to a value. 2205 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2206 if (!VD) { 2207 Diag(Loc, diag::err_ref_non_value) 2208 << D << SS.getRange(); 2209 Diag(D->getLocation(), diag::note_declared_at); 2210 return ExprError(); 2211 } 2212 2213 // Check whether this declaration can be used. Note that we suppress 2214 // this check when we're going to perform argument-dependent lookup 2215 // on this function name, because this might not be the function 2216 // that overload resolution actually selects. 2217 if (DiagnoseUseOfDecl(VD, Loc)) 2218 return ExprError(); 2219 2220 // Only create DeclRefExpr's for valid Decl's. 2221 if (VD->isInvalidDecl()) 2222 return ExprError(); 2223 2224 // Handle members of anonymous structs and unions. If we got here, 2225 // and the reference is to a class member indirect field, then this 2226 // must be the subject of a pointer-to-member expression. 2227 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2228 if (!indirectField->isCXXClassMember()) 2229 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2230 indirectField); 2231 2232 { 2233 QualType type = VD->getType(); 2234 ExprValueKind valueKind = VK_RValue; 2235 2236 switch (D->getKind()) { 2237 // Ignore all the non-ValueDecl kinds. 2238#define ABSTRACT_DECL(kind) 2239#define VALUE(type, base) 2240#define DECL(type, base) \ 2241 case Decl::type: 2242#include "clang/AST/DeclNodes.inc" 2243 llvm_unreachable("invalid value decl kind"); 2244 2245 // These shouldn't make it here. 2246 case Decl::ObjCAtDefsField: 2247 case Decl::ObjCIvar: 2248 llvm_unreachable("forming non-member reference to ivar?"); 2249 2250 // Enum constants are always r-values and never references. 2251 // Unresolved using declarations are dependent. 2252 case Decl::EnumConstant: 2253 case Decl::UnresolvedUsingValue: 2254 valueKind = VK_RValue; 2255 break; 2256 2257 // Fields and indirect fields that got here must be for 2258 // pointer-to-member expressions; we just call them l-values for 2259 // internal consistency, because this subexpression doesn't really 2260 // exist in the high-level semantics. 2261 case Decl::Field: 2262 case Decl::IndirectField: 2263 assert(getLangOpts().CPlusPlus && 2264 "building reference to field in C?"); 2265 2266 // These can't have reference type in well-formed programs, but 2267 // for internal consistency we do this anyway. 2268 type = type.getNonReferenceType(); 2269 valueKind = VK_LValue; 2270 break; 2271 2272 // Non-type template parameters are either l-values or r-values 2273 // depending on the type. 2274 case Decl::NonTypeTemplateParm: { 2275 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2276 type = reftype->getPointeeType(); 2277 valueKind = VK_LValue; // even if the parameter is an r-value reference 2278 break; 2279 } 2280 2281 // For non-references, we need to strip qualifiers just in case 2282 // the template parameter was declared as 'const int' or whatever. 2283 valueKind = VK_RValue; 2284 type = type.getUnqualifiedType(); 2285 break; 2286 } 2287 2288 case Decl::Var: 2289 // In C, "extern void blah;" is valid and is an r-value. 2290 if (!getLangOpts().CPlusPlus && 2291 !type.hasQualifiers() && 2292 type->isVoidType()) { 2293 valueKind = VK_RValue; 2294 break; 2295 } 2296 // fallthrough 2297 2298 case Decl::ImplicitParam: 2299 case Decl::ParmVar: { 2300 // These are always l-values. 2301 valueKind = VK_LValue; 2302 type = type.getNonReferenceType(); 2303 2304 // FIXME: Does the addition of const really only apply in 2305 // potentially-evaluated contexts? Since the variable isn't actually 2306 // captured in an unevaluated context, it seems that the answer is no. 2307 if (ExprEvalContexts.back().Context != Sema::Unevaluated) { 2308 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2309 if (!CapturedType.isNull()) 2310 type = CapturedType; 2311 } 2312 2313 break; 2314 } 2315 2316 case Decl::Function: { 2317 const FunctionType *fty = type->castAs<FunctionType>(); 2318 2319 // If we're referring to a function with an __unknown_anytype 2320 // result type, make the entire expression __unknown_anytype. 2321 if (fty->getResultType() == Context.UnknownAnyTy) { 2322 type = Context.UnknownAnyTy; 2323 valueKind = VK_RValue; 2324 break; 2325 } 2326 2327 // Functions are l-values in C++. 2328 if (getLangOpts().CPlusPlus) { 2329 valueKind = VK_LValue; 2330 break; 2331 } 2332 2333 // C99 DR 316 says that, if a function type comes from a 2334 // function definition (without a prototype), that type is only 2335 // used for checking compatibility. Therefore, when referencing 2336 // the function, we pretend that we don't have the full function 2337 // type. 2338 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2339 isa<FunctionProtoType>(fty)) 2340 type = Context.getFunctionNoProtoType(fty->getResultType(), 2341 fty->getExtInfo()); 2342 2343 // Functions are r-values in C. 2344 valueKind = VK_RValue; 2345 break; 2346 } 2347 2348 case Decl::CXXMethod: 2349 // If we're referring to a method with an __unknown_anytype 2350 // result type, make the entire expression __unknown_anytype. 2351 // This should only be possible with a type written directly. 2352 if (const FunctionProtoType *proto 2353 = dyn_cast<FunctionProtoType>(VD->getType())) 2354 if (proto->getResultType() == Context.UnknownAnyTy) { 2355 type = Context.UnknownAnyTy; 2356 valueKind = VK_RValue; 2357 break; 2358 } 2359 2360 // C++ methods are l-values if static, r-values if non-static. 2361 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2362 valueKind = VK_LValue; 2363 break; 2364 } 2365 // fallthrough 2366 2367 case Decl::CXXConversion: 2368 case Decl::CXXDestructor: 2369 case Decl::CXXConstructor: 2370 valueKind = VK_RValue; 2371 break; 2372 } 2373 2374 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS); 2375 } 2376} 2377 2378ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2379 PredefinedExpr::IdentType IT; 2380 2381 switch (Kind) { 2382 default: llvm_unreachable("Unknown simple primary expr!"); 2383 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2384 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2385 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2386 } 2387 2388 // Pre-defined identifiers are of type char[x], where x is the length of the 2389 // string. 2390 2391 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2392 if (!currentDecl && getCurBlock()) 2393 currentDecl = getCurBlock()->TheDecl; 2394 if (!currentDecl) { 2395 Diag(Loc, diag::ext_predef_outside_function); 2396 currentDecl = Context.getTranslationUnitDecl(); 2397 } 2398 2399 QualType ResTy; 2400 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2401 ResTy = Context.DependentTy; 2402 } else { 2403 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2404 2405 llvm::APInt LengthI(32, Length + 1); 2406 ResTy = Context.CharTy.withConst(); 2407 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2408 } 2409 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2410} 2411 2412ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2413 SmallString<16> CharBuffer; 2414 bool Invalid = false; 2415 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2416 if (Invalid) 2417 return ExprError(); 2418 2419 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2420 PP, Tok.getKind()); 2421 if (Literal.hadError()) 2422 return ExprError(); 2423 2424 QualType Ty; 2425 if (Literal.isWide()) 2426 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++. 2427 else if (Literal.isUTF16()) 2428 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2429 else if (Literal.isUTF32()) 2430 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2431 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2432 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2433 else 2434 Ty = Context.CharTy; // 'x' -> char in C++ 2435 2436 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2437 if (Literal.isWide()) 2438 Kind = CharacterLiteral::Wide; 2439 else if (Literal.isUTF16()) 2440 Kind = CharacterLiteral::UTF16; 2441 else if (Literal.isUTF32()) 2442 Kind = CharacterLiteral::UTF32; 2443 2444 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2445 Tok.getLocation()); 2446 2447 if (Literal.getUDSuffix().empty()) 2448 return Owned(Lit); 2449 2450 // We're building a user-defined literal. 2451 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2452 SourceLocation UDSuffixLoc = 2453 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2454 2455 // Make sure we're allowed user-defined literals here. 2456 if (!UDLScope) 2457 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2458 2459 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2460 // operator "" X (ch) 2461 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2462 llvm::makeArrayRef(&Lit, 1), 2463 Tok.getLocation()); 2464} 2465 2466ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2467 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2468 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2469 Context.IntTy, Loc)); 2470} 2471 2472static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2473 QualType Ty, SourceLocation Loc) { 2474 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2475 2476 using llvm::APFloat; 2477 APFloat Val(Format); 2478 2479 APFloat::opStatus result = Literal.GetFloatValue(Val); 2480 2481 // Overflow is always an error, but underflow is only an error if 2482 // we underflowed to zero (APFloat reports denormals as underflow). 2483 if ((result & APFloat::opOverflow) || 2484 ((result & APFloat::opUnderflow) && Val.isZero())) { 2485 unsigned diagnostic; 2486 SmallString<20> buffer; 2487 if (result & APFloat::opOverflow) { 2488 diagnostic = diag::warn_float_overflow; 2489 APFloat::getLargest(Format).toString(buffer); 2490 } else { 2491 diagnostic = diag::warn_float_underflow; 2492 APFloat::getSmallest(Format).toString(buffer); 2493 } 2494 2495 S.Diag(Loc, diagnostic) 2496 << Ty 2497 << StringRef(buffer.data(), buffer.size()); 2498 } 2499 2500 bool isExact = (result == APFloat::opOK); 2501 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2502} 2503 2504ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2505 // Fast path for a single digit (which is quite common). A single digit 2506 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2507 if (Tok.getLength() == 1) { 2508 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2509 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2510 } 2511 2512 SmallString<512> IntegerBuffer; 2513 // Add padding so that NumericLiteralParser can overread by one character. 2514 IntegerBuffer.resize(Tok.getLength()+1); 2515 const char *ThisTokBegin = &IntegerBuffer[0]; 2516 2517 // Get the spelling of the token, which eliminates trigraphs, etc. 2518 bool Invalid = false; 2519 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 2520 if (Invalid) 2521 return ExprError(); 2522 2523 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 2524 Tok.getLocation(), PP); 2525 if (Literal.hadError) 2526 return ExprError(); 2527 2528 if (Literal.hasUDSuffix()) { 2529 // We're building a user-defined literal. 2530 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2531 SourceLocation UDSuffixLoc = 2532 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2533 2534 // Make sure we're allowed user-defined literals here. 2535 if (!UDLScope) 2536 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2537 2538 QualType CookedTy; 2539 if (Literal.isFloatingLiteral()) { 2540 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2541 // long double, the literal is treated as a call of the form 2542 // operator "" X (f L) 2543 CookedTy = Context.LongDoubleTy; 2544 } else { 2545 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2546 // unsigned long long, the literal is treated as a call of the form 2547 // operator "" X (n ULL) 2548 CookedTy = Context.UnsignedLongLongTy; 2549 } 2550 2551 DeclarationName OpName = 2552 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2553 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2554 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2555 2556 // Perform literal operator lookup to determine if we're building a raw 2557 // literal or a cooked one. 2558 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2559 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1), 2560 /*AllowRawAndTemplate*/true)) { 2561 case LOLR_Error: 2562 return ExprError(); 2563 2564 case LOLR_Cooked: { 2565 Expr *Lit; 2566 if (Literal.isFloatingLiteral()) { 2567 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2568 } else { 2569 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2570 if (Literal.GetIntegerValue(ResultVal)) 2571 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2572 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2573 Tok.getLocation()); 2574 } 2575 return BuildLiteralOperatorCall(R, OpNameInfo, 2576 llvm::makeArrayRef(&Lit, 1), 2577 Tok.getLocation()); 2578 } 2579 2580 case LOLR_Raw: { 2581 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2582 // literal is treated as a call of the form 2583 // operator "" X ("n") 2584 SourceLocation TokLoc = Tok.getLocation(); 2585 unsigned Length = Literal.getUDSuffixOffset(); 2586 QualType StrTy = Context.getConstantArrayType( 2587 Context.CharTy, llvm::APInt(32, Length + 1), 2588 ArrayType::Normal, 0); 2589 Expr *Lit = StringLiteral::Create( 2590 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii, 2591 /*Pascal*/false, StrTy, &TokLoc, 1); 2592 return BuildLiteralOperatorCall(R, OpNameInfo, 2593 llvm::makeArrayRef(&Lit, 1), TokLoc); 2594 } 2595 2596 case LOLR_Template: 2597 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2598 // template), L is treated as a call fo the form 2599 // operator "" X <'c1', 'c2', ... 'ck'>() 2600 // where n is the source character sequence c1 c2 ... ck. 2601 TemplateArgumentListInfo ExplicitArgs; 2602 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2603 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2604 llvm::APSInt Value(CharBits, CharIsUnsigned); 2605 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2606 Value = ThisTokBegin[I]; 2607 TemplateArgument Arg(Value, Context.CharTy); 2608 TemplateArgumentLocInfo ArgInfo; 2609 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2610 } 2611 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(), 2612 Tok.getLocation(), &ExplicitArgs); 2613 } 2614 2615 llvm_unreachable("unexpected literal operator lookup result"); 2616 } 2617 2618 Expr *Res; 2619 2620 if (Literal.isFloatingLiteral()) { 2621 QualType Ty; 2622 if (Literal.isFloat) 2623 Ty = Context.FloatTy; 2624 else if (!Literal.isLong) 2625 Ty = Context.DoubleTy; 2626 else 2627 Ty = Context.LongDoubleTy; 2628 2629 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 2630 2631 if (Ty == Context.DoubleTy) { 2632 if (getLangOpts().SinglePrecisionConstants) { 2633 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2634 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2635 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2636 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2637 } 2638 } 2639 } else if (!Literal.isIntegerLiteral()) { 2640 return ExprError(); 2641 } else { 2642 QualType Ty; 2643 2644 // long long is a C99 feature. 2645 if (!getLangOpts().C99 && Literal.isLongLong) 2646 Diag(Tok.getLocation(), 2647 getLangOpts().CPlusPlus0x ? 2648 diag::warn_cxx98_compat_longlong : diag::ext_longlong); 2649 2650 // Get the value in the widest-possible width. 2651 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 2652 // The microsoft literal suffix extensions support 128-bit literals, which 2653 // may be wider than [u]intmax_t. 2654 if (Literal.isMicrosoftInteger && MaxWidth < 128) 2655 MaxWidth = 128; 2656 llvm::APInt ResultVal(MaxWidth, 0); 2657 2658 if (Literal.GetIntegerValue(ResultVal)) { 2659 // If this value didn't fit into uintmax_t, warn and force to ull. 2660 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2661 Ty = Context.UnsignedLongLongTy; 2662 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2663 "long long is not intmax_t?"); 2664 } else { 2665 // If this value fits into a ULL, try to figure out what else it fits into 2666 // according to the rules of C99 6.4.4.1p5. 2667 2668 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2669 // be an unsigned int. 2670 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2671 2672 // Check from smallest to largest, picking the smallest type we can. 2673 unsigned Width = 0; 2674 if (!Literal.isLong && !Literal.isLongLong) { 2675 // Are int/unsigned possibilities? 2676 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2677 2678 // Does it fit in a unsigned int? 2679 if (ResultVal.isIntN(IntSize)) { 2680 // Does it fit in a signed int? 2681 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2682 Ty = Context.IntTy; 2683 else if (AllowUnsigned) 2684 Ty = Context.UnsignedIntTy; 2685 Width = IntSize; 2686 } 2687 } 2688 2689 // Are long/unsigned long possibilities? 2690 if (Ty.isNull() && !Literal.isLongLong) { 2691 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 2692 2693 // Does it fit in a unsigned long? 2694 if (ResultVal.isIntN(LongSize)) { 2695 // Does it fit in a signed long? 2696 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2697 Ty = Context.LongTy; 2698 else if (AllowUnsigned) 2699 Ty = Context.UnsignedLongTy; 2700 Width = LongSize; 2701 } 2702 } 2703 2704 // Check long long if needed. 2705 if (Ty.isNull()) { 2706 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 2707 2708 // Does it fit in a unsigned long long? 2709 if (ResultVal.isIntN(LongLongSize)) { 2710 // Does it fit in a signed long long? 2711 // To be compatible with MSVC, hex integer literals ending with the 2712 // LL or i64 suffix are always signed in Microsoft mode. 2713 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 2714 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 2715 Ty = Context.LongLongTy; 2716 else if (AllowUnsigned) 2717 Ty = Context.UnsignedLongLongTy; 2718 Width = LongLongSize; 2719 } 2720 } 2721 2722 // If it doesn't fit in unsigned long long, and we're using Microsoft 2723 // extensions, then its a 128-bit integer literal. 2724 if (Ty.isNull() && Literal.isMicrosoftInteger) { 2725 if (Literal.isUnsigned) 2726 Ty = Context.UnsignedInt128Ty; 2727 else 2728 Ty = Context.Int128Ty; 2729 Width = 128; 2730 } 2731 2732 // If we still couldn't decide a type, we probably have something that 2733 // does not fit in a signed long long, but has no U suffix. 2734 if (Ty.isNull()) { 2735 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2736 Ty = Context.UnsignedLongLongTy; 2737 Width = Context.getTargetInfo().getLongLongWidth(); 2738 } 2739 2740 if (ResultVal.getBitWidth() != Width) 2741 ResultVal = ResultVal.trunc(Width); 2742 } 2743 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2744 } 2745 2746 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2747 if (Literal.isImaginary) 2748 Res = new (Context) ImaginaryLiteral(Res, 2749 Context.getComplexType(Res->getType())); 2750 2751 return Owned(Res); 2752} 2753 2754ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 2755 assert((E != 0) && "ActOnParenExpr() missing expr"); 2756 return Owned(new (Context) ParenExpr(L, R, E)); 2757} 2758 2759static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 2760 SourceLocation Loc, 2761 SourceRange ArgRange) { 2762 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 2763 // scalar or vector data type argument..." 2764 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 2765 // type (C99 6.2.5p18) or void. 2766 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 2767 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 2768 << T << ArgRange; 2769 return true; 2770 } 2771 2772 assert((T->isVoidType() || !T->isIncompleteType()) && 2773 "Scalar types should always be complete"); 2774 return false; 2775} 2776 2777static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 2778 SourceLocation Loc, 2779 SourceRange ArgRange, 2780 UnaryExprOrTypeTrait TraitKind) { 2781 // C99 6.5.3.4p1: 2782 if (T->isFunctionType()) { 2783 // alignof(function) is allowed as an extension. 2784 if (TraitKind == UETT_SizeOf) 2785 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange; 2786 return false; 2787 } 2788 2789 // Allow sizeof(void)/alignof(void) as an extension. 2790 if (T->isVoidType()) { 2791 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange; 2792 return false; 2793 } 2794 2795 return true; 2796} 2797 2798static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 2799 SourceLocation Loc, 2800 SourceRange ArgRange, 2801 UnaryExprOrTypeTrait TraitKind) { 2802 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 2803 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) { 2804 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 2805 << T << (TraitKind == UETT_SizeOf) 2806 << ArgRange; 2807 return true; 2808 } 2809 2810 return false; 2811} 2812 2813/// \brief Check the constrains on expression operands to unary type expression 2814/// and type traits. 2815/// 2816/// Completes any types necessary and validates the constraints on the operand 2817/// expression. The logic mostly mirrors the type-based overload, but may modify 2818/// the expression as it completes the type for that expression through template 2819/// instantiation, etc. 2820bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 2821 UnaryExprOrTypeTrait ExprKind) { 2822 QualType ExprTy = E->getType(); 2823 2824 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2825 // the result is the size of the referenced type." 2826 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2827 // result shall be the alignment of the referenced type." 2828 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2829 ExprTy = Ref->getPointeeType(); 2830 2831 if (ExprKind == UETT_VecStep) 2832 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 2833 E->getSourceRange()); 2834 2835 // Whitelist some types as extensions 2836 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 2837 E->getSourceRange(), ExprKind)) 2838 return false; 2839 2840 if (RequireCompleteExprType(E, 2841 diag::err_sizeof_alignof_incomplete_type, 2842 ExprKind, E->getSourceRange())) 2843 return true; 2844 2845 // Completeing the expression's type may have changed it. 2846 ExprTy = E->getType(); 2847 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2848 ExprTy = Ref->getPointeeType(); 2849 2850 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 2851 E->getSourceRange(), ExprKind)) 2852 return true; 2853 2854 if (ExprKind == UETT_SizeOf) { 2855 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 2856 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 2857 QualType OType = PVD->getOriginalType(); 2858 QualType Type = PVD->getType(); 2859 if (Type->isPointerType() && OType->isArrayType()) { 2860 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 2861 << Type << OType; 2862 Diag(PVD->getLocation(), diag::note_declared_at); 2863 } 2864 } 2865 } 2866 } 2867 2868 return false; 2869} 2870 2871/// \brief Check the constraints on operands to unary expression and type 2872/// traits. 2873/// 2874/// This will complete any types necessary, and validate the various constraints 2875/// on those operands. 2876/// 2877/// The UsualUnaryConversions() function is *not* called by this routine. 2878/// C99 6.3.2.1p[2-4] all state: 2879/// Except when it is the operand of the sizeof operator ... 2880/// 2881/// C++ [expr.sizeof]p4 2882/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 2883/// standard conversions are not applied to the operand of sizeof. 2884/// 2885/// This policy is followed for all of the unary trait expressions. 2886bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 2887 SourceLocation OpLoc, 2888 SourceRange ExprRange, 2889 UnaryExprOrTypeTrait ExprKind) { 2890 if (ExprType->isDependentType()) 2891 return false; 2892 2893 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2894 // the result is the size of the referenced type." 2895 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2896 // result shall be the alignment of the referenced type." 2897 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 2898 ExprType = Ref->getPointeeType(); 2899 2900 if (ExprKind == UETT_VecStep) 2901 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 2902 2903 // Whitelist some types as extensions 2904 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 2905 ExprKind)) 2906 return false; 2907 2908 if (RequireCompleteType(OpLoc, ExprType, 2909 diag::err_sizeof_alignof_incomplete_type, 2910 ExprKind, ExprRange)) 2911 return true; 2912 2913 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 2914 ExprKind)) 2915 return true; 2916 2917 return false; 2918} 2919 2920static bool CheckAlignOfExpr(Sema &S, Expr *E) { 2921 E = E->IgnoreParens(); 2922 2923 // alignof decl is always ok. 2924 if (isa<DeclRefExpr>(E)) 2925 return false; 2926 2927 // Cannot know anything else if the expression is dependent. 2928 if (E->isTypeDependent()) 2929 return false; 2930 2931 if (E->getBitField()) { 2932 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 2933 << 1 << E->getSourceRange(); 2934 return true; 2935 } 2936 2937 // Alignment of a field access is always okay, so long as it isn't a 2938 // bit-field. 2939 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2940 if (isa<FieldDecl>(ME->getMemberDecl())) 2941 return false; 2942 2943 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 2944} 2945 2946bool Sema::CheckVecStepExpr(Expr *E) { 2947 E = E->IgnoreParens(); 2948 2949 // Cannot know anything else if the expression is dependent. 2950 if (E->isTypeDependent()) 2951 return false; 2952 2953 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 2954} 2955 2956/// \brief Build a sizeof or alignof expression given a type operand. 2957ExprResult 2958Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2959 SourceLocation OpLoc, 2960 UnaryExprOrTypeTrait ExprKind, 2961 SourceRange R) { 2962 if (!TInfo) 2963 return ExprError(); 2964 2965 QualType T = TInfo->getType(); 2966 2967 if (!T->isDependentType() && 2968 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 2969 return ExprError(); 2970 2971 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2972 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 2973 Context.getSizeType(), 2974 OpLoc, R.getEnd())); 2975} 2976 2977/// \brief Build a sizeof or alignof expression given an expression 2978/// operand. 2979ExprResult 2980Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2981 UnaryExprOrTypeTrait ExprKind) { 2982 ExprResult PE = CheckPlaceholderExpr(E); 2983 if (PE.isInvalid()) 2984 return ExprError(); 2985 2986 E = PE.get(); 2987 2988 // Verify that the operand is valid. 2989 bool isInvalid = false; 2990 if (E->isTypeDependent()) { 2991 // Delay type-checking for type-dependent expressions. 2992 } else if (ExprKind == UETT_AlignOf) { 2993 isInvalid = CheckAlignOfExpr(*this, E); 2994 } else if (ExprKind == UETT_VecStep) { 2995 isInvalid = CheckVecStepExpr(E); 2996 } else if (E->getBitField()) { // C99 6.5.3.4p1. 2997 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 2998 isInvalid = true; 2999 } else { 3000 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3001 } 3002 3003 if (isInvalid) 3004 return ExprError(); 3005 3006 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3007 PE = TranformToPotentiallyEvaluated(E); 3008 if (PE.isInvalid()) return ExprError(); 3009 E = PE.take(); 3010 } 3011 3012 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3013 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3014 ExprKind, E, Context.getSizeType(), OpLoc, 3015 E->getSourceRange().getEnd())); 3016} 3017 3018/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3019/// expr and the same for @c alignof and @c __alignof 3020/// Note that the ArgRange is invalid if isType is false. 3021ExprResult 3022Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3023 UnaryExprOrTypeTrait ExprKind, bool IsType, 3024 void *TyOrEx, const SourceRange &ArgRange) { 3025 // If error parsing type, ignore. 3026 if (TyOrEx == 0) return ExprError(); 3027 3028 if (IsType) { 3029 TypeSourceInfo *TInfo; 3030 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3031 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3032 } 3033 3034 Expr *ArgEx = (Expr *)TyOrEx; 3035 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3036 return move(Result); 3037} 3038 3039static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3040 bool IsReal) { 3041 if (V.get()->isTypeDependent()) 3042 return S.Context.DependentTy; 3043 3044 // _Real and _Imag are only l-values for normal l-values. 3045 if (V.get()->getObjectKind() != OK_Ordinary) { 3046 V = S.DefaultLvalueConversion(V.take()); 3047 if (V.isInvalid()) 3048 return QualType(); 3049 } 3050 3051 // These operators return the element type of a complex type. 3052 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3053 return CT->getElementType(); 3054 3055 // Otherwise they pass through real integer and floating point types here. 3056 if (V.get()->getType()->isArithmeticType()) 3057 return V.get()->getType(); 3058 3059 // Test for placeholders. 3060 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3061 if (PR.isInvalid()) return QualType(); 3062 if (PR.get() != V.get()) { 3063 V = move(PR); 3064 return CheckRealImagOperand(S, V, Loc, IsReal); 3065 } 3066 3067 // Reject anything else. 3068 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3069 << (IsReal ? "__real" : "__imag"); 3070 return QualType(); 3071} 3072 3073 3074 3075ExprResult 3076Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3077 tok::TokenKind Kind, Expr *Input) { 3078 UnaryOperatorKind Opc; 3079 switch (Kind) { 3080 default: llvm_unreachable("Unknown unary op!"); 3081 case tok::plusplus: Opc = UO_PostInc; break; 3082 case tok::minusminus: Opc = UO_PostDec; break; 3083 } 3084 3085 // Since this might is a postfix expression, get rid of ParenListExprs. 3086 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3087 if (Result.isInvalid()) return ExprError(); 3088 Input = Result.take(); 3089 3090 return BuildUnaryOp(S, OpLoc, Opc, Input); 3091} 3092 3093ExprResult 3094Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3095 Expr *Idx, SourceLocation RLoc) { 3096 // Since this might be a postfix expression, get rid of ParenListExprs. 3097 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 3098 if (Result.isInvalid()) return ExprError(); 3099 Base = Result.take(); 3100 3101 Expr *LHSExp = Base, *RHSExp = Idx; 3102 3103 if (getLangOpts().CPlusPlus && 3104 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 3105 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3106 Context.DependentTy, 3107 VK_LValue, OK_Ordinary, 3108 RLoc)); 3109 } 3110 3111 if (getLangOpts().CPlusPlus && 3112 (LHSExp->getType()->isRecordType() || 3113 LHSExp->getType()->isEnumeralType() || 3114 RHSExp->getType()->isRecordType() || 3115 RHSExp->getType()->isEnumeralType()) && 3116 !LHSExp->getType()->isObjCObjectPointerType()) { 3117 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 3118 } 3119 3120 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 3121} 3122 3123 3124ExprResult 3125Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3126 Expr *Idx, SourceLocation RLoc) { 3127 Expr *LHSExp = Base; 3128 Expr *RHSExp = Idx; 3129 3130 // Perform default conversions. 3131 if (!LHSExp->getType()->getAs<VectorType>()) { 3132 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3133 if (Result.isInvalid()) 3134 return ExprError(); 3135 LHSExp = Result.take(); 3136 } 3137 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3138 if (Result.isInvalid()) 3139 return ExprError(); 3140 RHSExp = Result.take(); 3141 3142 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3143 ExprValueKind VK = VK_LValue; 3144 ExprObjectKind OK = OK_Ordinary; 3145 3146 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3147 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3148 // in the subscript position. As a result, we need to derive the array base 3149 // and index from the expression types. 3150 Expr *BaseExpr, *IndexExpr; 3151 QualType ResultType; 3152 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3153 BaseExpr = LHSExp; 3154 IndexExpr = RHSExp; 3155 ResultType = Context.DependentTy; 3156 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3157 BaseExpr = LHSExp; 3158 IndexExpr = RHSExp; 3159 ResultType = PTy->getPointeeType(); 3160 } else if (const ObjCObjectPointerType *PTy = 3161 LHSTy->getAs<ObjCObjectPointerType>()) { 3162 BaseExpr = LHSExp; 3163 IndexExpr = RHSExp; 3164 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3165 if (!Result.isInvalid()) 3166 return Owned(Result.take()); 3167 ResultType = PTy->getPointeeType(); 3168 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3169 // Handle the uncommon case of "123[Ptr]". 3170 BaseExpr = RHSExp; 3171 IndexExpr = LHSExp; 3172 ResultType = PTy->getPointeeType(); 3173 } else if (const ObjCObjectPointerType *PTy = 3174 RHSTy->getAs<ObjCObjectPointerType>()) { 3175 // Handle the uncommon case of "123[Ptr]". 3176 BaseExpr = RHSExp; 3177 IndexExpr = LHSExp; 3178 ResultType = PTy->getPointeeType(); 3179 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3180 BaseExpr = LHSExp; // vectors: V[123] 3181 IndexExpr = RHSExp; 3182 VK = LHSExp->getValueKind(); 3183 if (VK != VK_RValue) 3184 OK = OK_VectorComponent; 3185 3186 // FIXME: need to deal with const... 3187 ResultType = VTy->getElementType(); 3188 } else if (LHSTy->isArrayType()) { 3189 // If we see an array that wasn't promoted by 3190 // DefaultFunctionArrayLvalueConversion, it must be an array that 3191 // wasn't promoted because of the C90 rule that doesn't 3192 // allow promoting non-lvalue arrays. Warn, then 3193 // force the promotion here. 3194 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3195 LHSExp->getSourceRange(); 3196 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3197 CK_ArrayToPointerDecay).take(); 3198 LHSTy = LHSExp->getType(); 3199 3200 BaseExpr = LHSExp; 3201 IndexExpr = RHSExp; 3202 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3203 } else if (RHSTy->isArrayType()) { 3204 // Same as previous, except for 123[f().a] case 3205 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3206 RHSExp->getSourceRange(); 3207 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3208 CK_ArrayToPointerDecay).take(); 3209 RHSTy = RHSExp->getType(); 3210 3211 BaseExpr = RHSExp; 3212 IndexExpr = LHSExp; 3213 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3214 } else { 3215 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3216 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3217 } 3218 // C99 6.5.2.1p1 3219 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3220 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3221 << IndexExpr->getSourceRange()); 3222 3223 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3224 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3225 && !IndexExpr->isTypeDependent()) 3226 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3227 3228 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3229 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3230 // type. Note that Functions are not objects, and that (in C99 parlance) 3231 // incomplete types are not object types. 3232 if (ResultType->isFunctionType()) { 3233 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3234 << ResultType << BaseExpr->getSourceRange(); 3235 return ExprError(); 3236 } 3237 3238 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3239 // GNU extension: subscripting on pointer to void 3240 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3241 << BaseExpr->getSourceRange(); 3242 3243 // C forbids expressions of unqualified void type from being l-values. 3244 // See IsCForbiddenLValueType. 3245 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3246 } else if (!ResultType->isDependentType() && 3247 RequireCompleteType(LLoc, ResultType, 3248 diag::err_subscript_incomplete_type, BaseExpr)) 3249 return ExprError(); 3250 3251 // Diagnose bad cases where we step over interface counts. 3252 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 3253 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3254 << ResultType << BaseExpr->getSourceRange(); 3255 return ExprError(); 3256 } 3257 3258 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3259 !ResultType.isCForbiddenLValueType()); 3260 3261 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3262 ResultType, VK, OK, RLoc)); 3263} 3264 3265ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3266 FunctionDecl *FD, 3267 ParmVarDecl *Param) { 3268 if (Param->hasUnparsedDefaultArg()) { 3269 Diag(CallLoc, 3270 diag::err_use_of_default_argument_to_function_declared_later) << 3271 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3272 Diag(UnparsedDefaultArgLocs[Param], 3273 diag::note_default_argument_declared_here); 3274 return ExprError(); 3275 } 3276 3277 if (Param->hasUninstantiatedDefaultArg()) { 3278 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3279 3280 // Instantiate the expression. 3281 MultiLevelTemplateArgumentList ArgList 3282 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3283 3284 std::pair<const TemplateArgument *, unsigned> Innermost 3285 = ArgList.getInnermost(); 3286 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first, 3287 Innermost.second); 3288 3289 ExprResult Result; 3290 { 3291 // C++ [dcl.fct.default]p5: 3292 // The names in the [default argument] expression are bound, and 3293 // the semantic constraints are checked, at the point where the 3294 // default argument expression appears. 3295 ContextRAII SavedContext(*this, FD); 3296 LocalInstantiationScope Local(*this); 3297 Result = SubstExpr(UninstExpr, ArgList); 3298 } 3299 if (Result.isInvalid()) 3300 return ExprError(); 3301 3302 // Check the expression as an initializer for the parameter. 3303 InitializedEntity Entity 3304 = InitializedEntity::InitializeParameter(Context, Param); 3305 InitializationKind Kind 3306 = InitializationKind::CreateCopy(Param->getLocation(), 3307 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3308 Expr *ResultE = Result.takeAs<Expr>(); 3309 3310 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3311 Result = InitSeq.Perform(*this, Entity, Kind, 3312 MultiExprArg(*this, &ResultE, 1)); 3313 if (Result.isInvalid()) 3314 return ExprError(); 3315 3316 Expr *Arg = Result.takeAs<Expr>(); 3317 CheckImplicitConversions(Arg, Arg->getExprLoc()); 3318 // Build the default argument expression. 3319 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3320 } 3321 3322 // If the default expression creates temporaries, we need to 3323 // push them to the current stack of expression temporaries so they'll 3324 // be properly destroyed. 3325 // FIXME: We should really be rebuilding the default argument with new 3326 // bound temporaries; see the comment in PR5810. 3327 // We don't need to do that with block decls, though, because 3328 // blocks in default argument expression can never capture anything. 3329 if (isa<ExprWithCleanups>(Param->getInit())) { 3330 // Set the "needs cleanups" bit regardless of whether there are 3331 // any explicit objects. 3332 ExprNeedsCleanups = true; 3333 3334 // Append all the objects to the cleanup list. Right now, this 3335 // should always be a no-op, because blocks in default argument 3336 // expressions should never be able to capture anything. 3337 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3338 "default argument expression has capturing blocks?"); 3339 } 3340 3341 // We already type-checked the argument, so we know it works. 3342 // Just mark all of the declarations in this potentially-evaluated expression 3343 // as being "referenced". 3344 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3345 /*SkipLocalVariables=*/true); 3346 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3347} 3348 3349/// ConvertArgumentsForCall - Converts the arguments specified in 3350/// Args/NumArgs to the parameter types of the function FDecl with 3351/// function prototype Proto. Call is the call expression itself, and 3352/// Fn is the function expression. For a C++ member function, this 3353/// routine does not attempt to convert the object argument. Returns 3354/// true if the call is ill-formed. 3355bool 3356Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3357 FunctionDecl *FDecl, 3358 const FunctionProtoType *Proto, 3359 Expr **Args, unsigned NumArgs, 3360 SourceLocation RParenLoc, 3361 bool IsExecConfig) { 3362 // Bail out early if calling a builtin with custom typechecking. 3363 // We don't need to do this in the 3364 if (FDecl) 3365 if (unsigned ID = FDecl->getBuiltinID()) 3366 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3367 return false; 3368 3369 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3370 // assignment, to the types of the corresponding parameter, ... 3371 unsigned NumArgsInProto = Proto->getNumArgs(); 3372 bool Invalid = false; 3373 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3374 unsigned FnKind = Fn->getType()->isBlockPointerType() 3375 ? 1 /* block */ 3376 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3377 : 0 /* function */); 3378 3379 // If too few arguments are available (and we don't have default 3380 // arguments for the remaining parameters), don't make the call. 3381 if (NumArgs < NumArgsInProto) { 3382 if (NumArgs < MinArgs) { 3383 Diag(RParenLoc, MinArgs == NumArgsInProto 3384 ? diag::err_typecheck_call_too_few_args 3385 : diag::err_typecheck_call_too_few_args_at_least) 3386 << FnKind 3387 << MinArgs << NumArgs << Fn->getSourceRange(); 3388 3389 // Emit the location of the prototype. 3390 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3391 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3392 << FDecl; 3393 3394 return true; 3395 } 3396 Call->setNumArgs(Context, NumArgsInProto); 3397 } 3398 3399 // If too many are passed and not variadic, error on the extras and drop 3400 // them. 3401 if (NumArgs > NumArgsInProto) { 3402 if (!Proto->isVariadic()) { 3403 Diag(Args[NumArgsInProto]->getLocStart(), 3404 MinArgs == NumArgsInProto 3405 ? diag::err_typecheck_call_too_many_args 3406 : diag::err_typecheck_call_too_many_args_at_most) 3407 << FnKind 3408 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3409 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3410 Args[NumArgs-1]->getLocEnd()); 3411 3412 // Emit the location of the prototype. 3413 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3414 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3415 << FDecl; 3416 3417 // This deletes the extra arguments. 3418 Call->setNumArgs(Context, NumArgsInProto); 3419 return true; 3420 } 3421 } 3422 SmallVector<Expr *, 8> AllArgs; 3423 VariadicCallType CallType = 3424 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 3425 if (Fn->getType()->isBlockPointerType()) 3426 CallType = VariadicBlock; // Block 3427 else if (isa<MemberExpr>(Fn)) 3428 CallType = VariadicMethod; 3429 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 3430 Proto, 0, Args, NumArgs, AllArgs, CallType); 3431 if (Invalid) 3432 return true; 3433 unsigned TotalNumArgs = AllArgs.size(); 3434 for (unsigned i = 0; i < TotalNumArgs; ++i) 3435 Call->setArg(i, AllArgs[i]); 3436 3437 return false; 3438} 3439 3440bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3441 FunctionDecl *FDecl, 3442 const FunctionProtoType *Proto, 3443 unsigned FirstProtoArg, 3444 Expr **Args, unsigned NumArgs, 3445 SmallVector<Expr *, 8> &AllArgs, 3446 VariadicCallType CallType, 3447 bool AllowExplicit) { 3448 unsigned NumArgsInProto = Proto->getNumArgs(); 3449 unsigned NumArgsToCheck = NumArgs; 3450 bool Invalid = false; 3451 if (NumArgs != NumArgsInProto) 3452 // Use default arguments for missing arguments 3453 NumArgsToCheck = NumArgsInProto; 3454 unsigned ArgIx = 0; 3455 // Continue to check argument types (even if we have too few/many args). 3456 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3457 QualType ProtoArgType = Proto->getArgType(i); 3458 3459 Expr *Arg; 3460 ParmVarDecl *Param; 3461 if (ArgIx < NumArgs) { 3462 Arg = Args[ArgIx++]; 3463 3464 if (RequireCompleteType(Arg->getLocStart(), 3465 ProtoArgType, 3466 diag::err_call_incomplete_argument, Arg)) 3467 return true; 3468 3469 // Pass the argument 3470 Param = 0; 3471 if (FDecl && i < FDecl->getNumParams()) 3472 Param = FDecl->getParamDecl(i); 3473 3474 // Strip the unbridged-cast placeholder expression off, if applicable. 3475 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3476 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3477 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3478 Arg = stripARCUnbridgedCast(Arg); 3479 3480 InitializedEntity Entity = 3481 Param? InitializedEntity::InitializeParameter(Context, Param) 3482 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3483 Proto->isArgConsumed(i)); 3484 ExprResult ArgE = PerformCopyInitialization(Entity, 3485 SourceLocation(), 3486 Owned(Arg), 3487 /*TopLevelOfInitList=*/false, 3488 AllowExplicit); 3489 if (ArgE.isInvalid()) 3490 return true; 3491 3492 Arg = ArgE.takeAs<Expr>(); 3493 } else { 3494 Param = FDecl->getParamDecl(i); 3495 3496 ExprResult ArgExpr = 3497 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3498 if (ArgExpr.isInvalid()) 3499 return true; 3500 3501 Arg = ArgExpr.takeAs<Expr>(); 3502 } 3503 3504 // Check for array bounds violations for each argument to the call. This 3505 // check only triggers warnings when the argument isn't a more complex Expr 3506 // with its own checking, such as a BinaryOperator. 3507 CheckArrayAccess(Arg); 3508 3509 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3510 CheckStaticArrayArgument(CallLoc, Param, Arg); 3511 3512 AllArgs.push_back(Arg); 3513 } 3514 3515 // If this is a variadic call, handle args passed through "...". 3516 if (CallType != VariadicDoesNotApply) { 3517 3518 // Assume that extern "C" functions with variadic arguments that 3519 // return __unknown_anytype aren't *really* variadic. 3520 if (Proto->getResultType() == Context.UnknownAnyTy && 3521 FDecl && FDecl->isExternC()) { 3522 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3523 ExprResult arg; 3524 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens())) 3525 arg = DefaultFunctionArrayLvalueConversion(Args[i]); 3526 else 3527 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl); 3528 Invalid |= arg.isInvalid(); 3529 AllArgs.push_back(arg.take()); 3530 } 3531 3532 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3533 } else { 3534 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3535 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 3536 FDecl); 3537 Invalid |= Arg.isInvalid(); 3538 AllArgs.push_back(Arg.take()); 3539 } 3540 } 3541 3542 // Check for array bounds violations. 3543 for (unsigned i = ArgIx; i != NumArgs; ++i) 3544 CheckArrayAccess(Args[i]); 3545 } 3546 return Invalid; 3547} 3548 3549static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 3550 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 3551 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL)) 3552 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 3553 << ATL->getLocalSourceRange(); 3554} 3555 3556/// CheckStaticArrayArgument - If the given argument corresponds to a static 3557/// array parameter, check that it is non-null, and that if it is formed by 3558/// array-to-pointer decay, the underlying array is sufficiently large. 3559/// 3560/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 3561/// array type derivation, then for each call to the function, the value of the 3562/// corresponding actual argument shall provide access to the first element of 3563/// an array with at least as many elements as specified by the size expression. 3564void 3565Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 3566 ParmVarDecl *Param, 3567 const Expr *ArgExpr) { 3568 // Static array parameters are not supported in C++. 3569 if (!Param || getLangOpts().CPlusPlus) 3570 return; 3571 3572 QualType OrigTy = Param->getOriginalType(); 3573 3574 const ArrayType *AT = Context.getAsArrayType(OrigTy); 3575 if (!AT || AT->getSizeModifier() != ArrayType::Static) 3576 return; 3577 3578 if (ArgExpr->isNullPointerConstant(Context, 3579 Expr::NPC_NeverValueDependent)) { 3580 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 3581 DiagnoseCalleeStaticArrayParam(*this, Param); 3582 return; 3583 } 3584 3585 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 3586 if (!CAT) 3587 return; 3588 3589 const ConstantArrayType *ArgCAT = 3590 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 3591 if (!ArgCAT) 3592 return; 3593 3594 if (ArgCAT->getSize().ult(CAT->getSize())) { 3595 Diag(CallLoc, diag::warn_static_array_too_small) 3596 << ArgExpr->getSourceRange() 3597 << (unsigned) ArgCAT->getSize().getZExtValue() 3598 << (unsigned) CAT->getSize().getZExtValue(); 3599 DiagnoseCalleeStaticArrayParam(*this, Param); 3600 } 3601} 3602 3603/// Given a function expression of unknown-any type, try to rebuild it 3604/// to have a function type. 3605static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 3606 3607/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3608/// This provides the location of the left/right parens and a list of comma 3609/// locations. 3610ExprResult 3611Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3612 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3613 Expr *ExecConfig, bool IsExecConfig) { 3614 unsigned NumArgs = ArgExprs.size(); 3615 3616 // Since this might be a postfix expression, get rid of ParenListExprs. 3617 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3618 if (Result.isInvalid()) return ExprError(); 3619 Fn = Result.take(); 3620 3621 Expr **Args = ArgExprs.release(); 3622 3623 if (getLangOpts().CPlusPlus) { 3624 // If this is a pseudo-destructor expression, build the call immediately. 3625 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3626 if (NumArgs > 0) { 3627 // Pseudo-destructor calls should not have any arguments. 3628 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3629 << FixItHint::CreateRemoval( 3630 SourceRange(Args[0]->getLocStart(), 3631 Args[NumArgs-1]->getLocEnd())); 3632 } 3633 3634 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 3635 VK_RValue, RParenLoc)); 3636 } 3637 3638 // Determine whether this is a dependent call inside a C++ template, 3639 // in which case we won't do any semantic analysis now. 3640 // FIXME: Will need to cache the results of name lookup (including ADL) in 3641 // Fn. 3642 bool Dependent = false; 3643 if (Fn->isTypeDependent()) 3644 Dependent = true; 3645 else if (Expr::hasAnyTypeDependentArguments( 3646 llvm::makeArrayRef(Args, NumArgs))) 3647 Dependent = true; 3648 3649 if (Dependent) { 3650 if (ExecConfig) { 3651 return Owned(new (Context) CUDAKernelCallExpr( 3652 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs, 3653 Context.DependentTy, VK_RValue, RParenLoc)); 3654 } else { 3655 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 3656 Context.DependentTy, VK_RValue, 3657 RParenLoc)); 3658 } 3659 } 3660 3661 // Determine whether this is a call to an object (C++ [over.call.object]). 3662 if (Fn->getType()->isRecordType()) 3663 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 3664 RParenLoc)); 3665 3666 if (Fn->getType() == Context.UnknownAnyTy) { 3667 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3668 if (result.isInvalid()) return ExprError(); 3669 Fn = result.take(); 3670 } 3671 3672 if (Fn->getType() == Context.BoundMemberTy) { 3673 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3674 RParenLoc); 3675 } 3676 } 3677 3678 // Check for overloaded calls. This can happen even in C due to extensions. 3679 if (Fn->getType() == Context.OverloadTy) { 3680 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 3681 3682 // We aren't supposed to apply this logic for if there's an '&' involved. 3683 if (!find.HasFormOfMemberPointer) { 3684 OverloadExpr *ovl = find.Expression; 3685 if (isa<UnresolvedLookupExpr>(ovl)) { 3686 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 3687 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs, 3688 RParenLoc, ExecConfig); 3689 } else { 3690 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3691 RParenLoc); 3692 } 3693 } 3694 } 3695 3696 // If we're directly calling a function, get the appropriate declaration. 3697 if (Fn->getType() == Context.UnknownAnyTy) { 3698 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3699 if (result.isInvalid()) return ExprError(); 3700 Fn = result.take(); 3701 } 3702 3703 Expr *NakedFn = Fn->IgnoreParens(); 3704 3705 NamedDecl *NDecl = 0; 3706 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 3707 if (UnOp->getOpcode() == UO_AddrOf) 3708 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 3709 3710 if (isa<DeclRefExpr>(NakedFn)) 3711 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3712 else if (isa<MemberExpr>(NakedFn)) 3713 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 3714 3715 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc, 3716 ExecConfig, IsExecConfig); 3717} 3718 3719ExprResult 3720Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3721 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 3722 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 3723 if (!ConfigDecl) 3724 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 3725 << "cudaConfigureCall"); 3726 QualType ConfigQTy = ConfigDecl->getType(); 3727 3728 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 3729 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 3730 MarkFunctionReferenced(LLLLoc, ConfigDecl); 3731 3732 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 3733 /*IsExecConfig=*/true); 3734} 3735 3736/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 3737/// 3738/// __builtin_astype( value, dst type ) 3739/// 3740ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3741 SourceLocation BuiltinLoc, 3742 SourceLocation RParenLoc) { 3743 ExprValueKind VK = VK_RValue; 3744 ExprObjectKind OK = OK_Ordinary; 3745 QualType DstTy = GetTypeFromParser(ParsedDestTy); 3746 QualType SrcTy = E->getType(); 3747 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 3748 return ExprError(Diag(BuiltinLoc, 3749 diag::err_invalid_astype_of_different_size) 3750 << DstTy 3751 << SrcTy 3752 << E->getSourceRange()); 3753 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 3754 RParenLoc)); 3755} 3756 3757/// BuildResolvedCallExpr - Build a call to a resolved expression, 3758/// i.e. an expression not of \p OverloadTy. The expression should 3759/// unary-convert to an expression of function-pointer or 3760/// block-pointer type. 3761/// 3762/// \param NDecl the declaration being called, if available 3763ExprResult 3764Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3765 SourceLocation LParenLoc, 3766 Expr **Args, unsigned NumArgs, 3767 SourceLocation RParenLoc, 3768 Expr *Config, bool IsExecConfig) { 3769 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 3770 3771 // Promote the function operand. 3772 ExprResult Result = UsualUnaryConversions(Fn); 3773 if (Result.isInvalid()) 3774 return ExprError(); 3775 Fn = Result.take(); 3776 3777 // Make the call expr early, before semantic checks. This guarantees cleanup 3778 // of arguments and function on error. 3779 CallExpr *TheCall; 3780 if (Config) { 3781 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 3782 cast<CallExpr>(Config), 3783 Args, NumArgs, 3784 Context.BoolTy, 3785 VK_RValue, 3786 RParenLoc); 3787 } else { 3788 TheCall = new (Context) CallExpr(Context, Fn, 3789 Args, NumArgs, 3790 Context.BoolTy, 3791 VK_RValue, 3792 RParenLoc); 3793 } 3794 3795 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 3796 3797 // Bail out early if calling a builtin with custom typechecking. 3798 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 3799 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3800 3801 retry: 3802 const FunctionType *FuncT; 3803 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 3804 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 3805 // have type pointer to function". 3806 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 3807 if (FuncT == 0) 3808 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3809 << Fn->getType() << Fn->getSourceRange()); 3810 } else if (const BlockPointerType *BPT = 3811 Fn->getType()->getAs<BlockPointerType>()) { 3812 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 3813 } else { 3814 // Handle calls to expressions of unknown-any type. 3815 if (Fn->getType() == Context.UnknownAnyTy) { 3816 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 3817 if (rewrite.isInvalid()) return ExprError(); 3818 Fn = rewrite.take(); 3819 TheCall->setCallee(Fn); 3820 goto retry; 3821 } 3822 3823 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3824 << Fn->getType() << Fn->getSourceRange()); 3825 } 3826 3827 if (getLangOpts().CUDA) { 3828 if (Config) { 3829 // CUDA: Kernel calls must be to global functions 3830 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 3831 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 3832 << FDecl->getName() << Fn->getSourceRange()); 3833 3834 // CUDA: Kernel function must have 'void' return type 3835 if (!FuncT->getResultType()->isVoidType()) 3836 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 3837 << Fn->getType() << Fn->getSourceRange()); 3838 } else { 3839 // CUDA: Calls to global functions must be configured 3840 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 3841 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 3842 << FDecl->getName() << Fn->getSourceRange()); 3843 } 3844 } 3845 3846 // Check for a valid return type 3847 if (CheckCallReturnType(FuncT->getResultType(), 3848 Fn->getLocStart(), TheCall, 3849 FDecl)) 3850 return ExprError(); 3851 3852 // We know the result type of the call, set it. 3853 TheCall->setType(FuncT->getCallResultType(Context)); 3854 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 3855 3856 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 3857 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 3858 RParenLoc, IsExecConfig)) 3859 return ExprError(); 3860 } else { 3861 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 3862 3863 if (FDecl) { 3864 // Check if we have too few/too many template arguments, based 3865 // on our knowledge of the function definition. 3866 const FunctionDecl *Def = 0; 3867 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 3868 const FunctionProtoType *Proto 3869 = Def->getType()->getAs<FunctionProtoType>(); 3870 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 3871 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 3872 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 3873 } 3874 3875 // If the function we're calling isn't a function prototype, but we have 3876 // a function prototype from a prior declaratiom, use that prototype. 3877 if (!FDecl->hasPrototype()) 3878 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 3879 } 3880 3881 // Promote the arguments (C99 6.5.2.2p6). 3882 for (unsigned i = 0; i != NumArgs; i++) { 3883 Expr *Arg = Args[i]; 3884 3885 if (Proto && i < Proto->getNumArgs()) { 3886 InitializedEntity Entity 3887 = InitializedEntity::InitializeParameter(Context, 3888 Proto->getArgType(i), 3889 Proto->isArgConsumed(i)); 3890 ExprResult ArgE = PerformCopyInitialization(Entity, 3891 SourceLocation(), 3892 Owned(Arg)); 3893 if (ArgE.isInvalid()) 3894 return true; 3895 3896 Arg = ArgE.takeAs<Expr>(); 3897 3898 } else { 3899 ExprResult ArgE = DefaultArgumentPromotion(Arg); 3900 3901 if (ArgE.isInvalid()) 3902 return true; 3903 3904 Arg = ArgE.takeAs<Expr>(); 3905 } 3906 3907 if (RequireCompleteType(Arg->getLocStart(), 3908 Arg->getType(), 3909 diag::err_call_incomplete_argument, Arg)) 3910 return ExprError(); 3911 3912 TheCall->setArg(i, Arg); 3913 } 3914 } 3915 3916 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3917 if (!Method->isStatic()) 3918 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 3919 << Fn->getSourceRange()); 3920 3921 // Check for sentinels 3922 if (NDecl) 3923 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 3924 3925 // Do special checking on direct calls to functions. 3926 if (FDecl) { 3927 if (CheckFunctionCall(FDecl, TheCall)) 3928 return ExprError(); 3929 3930 if (BuiltinID) 3931 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3932 } else if (NDecl) { 3933 if (CheckBlockCall(NDecl, TheCall)) 3934 return ExprError(); 3935 } 3936 3937 return MaybeBindToTemporary(TheCall); 3938} 3939 3940ExprResult 3941Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 3942 SourceLocation RParenLoc, Expr *InitExpr) { 3943 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 3944 // FIXME: put back this assert when initializers are worked out. 3945 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 3946 3947 TypeSourceInfo *TInfo; 3948 QualType literalType = GetTypeFromParser(Ty, &TInfo); 3949 if (!TInfo) 3950 TInfo = Context.getTrivialTypeSourceInfo(literalType); 3951 3952 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 3953} 3954 3955ExprResult 3956Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 3957 SourceLocation RParenLoc, Expr *LiteralExpr) { 3958 QualType literalType = TInfo->getType(); 3959 3960 if (literalType->isArrayType()) { 3961 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 3962 diag::err_illegal_decl_array_incomplete_type, 3963 SourceRange(LParenLoc, 3964 LiteralExpr->getSourceRange().getEnd()))) 3965 return ExprError(); 3966 if (literalType->isVariableArrayType()) 3967 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3968 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 3969 } else if (!literalType->isDependentType() && 3970 RequireCompleteType(LParenLoc, literalType, 3971 diag::err_typecheck_decl_incomplete_type, 3972 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 3973 return ExprError(); 3974 3975 InitializedEntity Entity 3976 = InitializedEntity::InitializeTemporary(literalType); 3977 InitializationKind Kind 3978 = InitializationKind::CreateCStyleCast(LParenLoc, 3979 SourceRange(LParenLoc, RParenLoc), 3980 /*InitList=*/true); 3981 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1); 3982 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3983 MultiExprArg(*this, &LiteralExpr, 1), 3984 &literalType); 3985 if (Result.isInvalid()) 3986 return ExprError(); 3987 LiteralExpr = Result.get(); 3988 3989 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3990 if (isFileScope) { // 6.5.2.5p3 3991 if (CheckForConstantInitializer(LiteralExpr, literalType)) 3992 return ExprError(); 3993 } 3994 3995 // In C, compound literals are l-values for some reason. 3996 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 3997 3998 return MaybeBindToTemporary( 3999 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4000 VK, LiteralExpr, isFileScope)); 4001} 4002 4003ExprResult 4004Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4005 SourceLocation RBraceLoc) { 4006 unsigned NumInit = InitArgList.size(); 4007 Expr **InitList = InitArgList.release(); 4008 4009 // Immediately handle non-overload placeholders. Overloads can be 4010 // resolved contextually, but everything else here can't. 4011 for (unsigned I = 0; I != NumInit; ++I) { 4012 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) { 4013 ExprResult result = CheckPlaceholderExpr(InitList[I]); 4014 4015 // Ignore failures; dropping the entire initializer list because 4016 // of one failure would be terrible for indexing/etc. 4017 if (result.isInvalid()) continue; 4018 4019 InitList[I] = result.take(); 4020 } 4021 } 4022 4023 // Semantic analysis for initializers is done by ActOnDeclarator() and 4024 // CheckInitializer() - it requires knowledge of the object being intialized. 4025 4026 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList, 4027 NumInit, RBraceLoc); 4028 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4029 return Owned(E); 4030} 4031 4032/// Do an explicit extend of the given block pointer if we're in ARC. 4033static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4034 assert(E.get()->getType()->isBlockPointerType()); 4035 assert(E.get()->isRValue()); 4036 4037 // Only do this in an r-value context. 4038 if (!S.getLangOpts().ObjCAutoRefCount) return; 4039 4040 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4041 CK_ARCExtendBlockObject, E.get(), 4042 /*base path*/ 0, VK_RValue); 4043 S.ExprNeedsCleanups = true; 4044} 4045 4046/// Prepare a conversion of the given expression to an ObjC object 4047/// pointer type. 4048CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4049 QualType type = E.get()->getType(); 4050 if (type->isObjCObjectPointerType()) { 4051 return CK_BitCast; 4052 } else if (type->isBlockPointerType()) { 4053 maybeExtendBlockObject(*this, E); 4054 return CK_BlockPointerToObjCPointerCast; 4055 } else { 4056 assert(type->isPointerType()); 4057 return CK_CPointerToObjCPointerCast; 4058 } 4059} 4060 4061/// Prepares for a scalar cast, performing all the necessary stages 4062/// except the final cast and returning the kind required. 4063CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4064 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4065 // Also, callers should have filtered out the invalid cases with 4066 // pointers. Everything else should be possible. 4067 4068 QualType SrcTy = Src.get()->getType(); 4069 if (const AtomicType *SrcAtomicTy = SrcTy->getAs<AtomicType>()) 4070 SrcTy = SrcAtomicTy->getValueType(); 4071 if (const AtomicType *DestAtomicTy = DestTy->getAs<AtomicType>()) 4072 DestTy = DestAtomicTy->getValueType(); 4073 4074 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4075 return CK_NoOp; 4076 4077 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4078 case Type::STK_MemberPointer: 4079 llvm_unreachable("member pointer type in C"); 4080 4081 case Type::STK_CPointer: 4082 case Type::STK_BlockPointer: 4083 case Type::STK_ObjCObjectPointer: 4084 switch (DestTy->getScalarTypeKind()) { 4085 case Type::STK_CPointer: 4086 return CK_BitCast; 4087 case Type::STK_BlockPointer: 4088 return (SrcKind == Type::STK_BlockPointer 4089 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4090 case Type::STK_ObjCObjectPointer: 4091 if (SrcKind == Type::STK_ObjCObjectPointer) 4092 return CK_BitCast; 4093 if (SrcKind == Type::STK_CPointer) 4094 return CK_CPointerToObjCPointerCast; 4095 maybeExtendBlockObject(*this, Src); 4096 return CK_BlockPointerToObjCPointerCast; 4097 case Type::STK_Bool: 4098 return CK_PointerToBoolean; 4099 case Type::STK_Integral: 4100 return CK_PointerToIntegral; 4101 case Type::STK_Floating: 4102 case Type::STK_FloatingComplex: 4103 case Type::STK_IntegralComplex: 4104 case Type::STK_MemberPointer: 4105 llvm_unreachable("illegal cast from pointer"); 4106 } 4107 llvm_unreachable("Should have returned before this"); 4108 4109 case Type::STK_Bool: // casting from bool is like casting from an integer 4110 case Type::STK_Integral: 4111 switch (DestTy->getScalarTypeKind()) { 4112 case Type::STK_CPointer: 4113 case Type::STK_ObjCObjectPointer: 4114 case Type::STK_BlockPointer: 4115 if (Src.get()->isNullPointerConstant(Context, 4116 Expr::NPC_ValueDependentIsNull)) 4117 return CK_NullToPointer; 4118 return CK_IntegralToPointer; 4119 case Type::STK_Bool: 4120 return CK_IntegralToBoolean; 4121 case Type::STK_Integral: 4122 return CK_IntegralCast; 4123 case Type::STK_Floating: 4124 return CK_IntegralToFloating; 4125 case Type::STK_IntegralComplex: 4126 Src = ImpCastExprToType(Src.take(), 4127 DestTy->castAs<ComplexType>()->getElementType(), 4128 CK_IntegralCast); 4129 return CK_IntegralRealToComplex; 4130 case Type::STK_FloatingComplex: 4131 Src = ImpCastExprToType(Src.take(), 4132 DestTy->castAs<ComplexType>()->getElementType(), 4133 CK_IntegralToFloating); 4134 return CK_FloatingRealToComplex; 4135 case Type::STK_MemberPointer: 4136 llvm_unreachable("member pointer type in C"); 4137 } 4138 llvm_unreachable("Should have returned before this"); 4139 4140 case Type::STK_Floating: 4141 switch (DestTy->getScalarTypeKind()) { 4142 case Type::STK_Floating: 4143 return CK_FloatingCast; 4144 case Type::STK_Bool: 4145 return CK_FloatingToBoolean; 4146 case Type::STK_Integral: 4147 return CK_FloatingToIntegral; 4148 case Type::STK_FloatingComplex: 4149 Src = ImpCastExprToType(Src.take(), 4150 DestTy->castAs<ComplexType>()->getElementType(), 4151 CK_FloatingCast); 4152 return CK_FloatingRealToComplex; 4153 case Type::STK_IntegralComplex: 4154 Src = ImpCastExprToType(Src.take(), 4155 DestTy->castAs<ComplexType>()->getElementType(), 4156 CK_FloatingToIntegral); 4157 return CK_IntegralRealToComplex; 4158 case Type::STK_CPointer: 4159 case Type::STK_ObjCObjectPointer: 4160 case Type::STK_BlockPointer: 4161 llvm_unreachable("valid float->pointer cast?"); 4162 case Type::STK_MemberPointer: 4163 llvm_unreachable("member pointer type in C"); 4164 } 4165 llvm_unreachable("Should have returned before this"); 4166 4167 case Type::STK_FloatingComplex: 4168 switch (DestTy->getScalarTypeKind()) { 4169 case Type::STK_FloatingComplex: 4170 return CK_FloatingComplexCast; 4171 case Type::STK_IntegralComplex: 4172 return CK_FloatingComplexToIntegralComplex; 4173 case Type::STK_Floating: { 4174 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4175 if (Context.hasSameType(ET, DestTy)) 4176 return CK_FloatingComplexToReal; 4177 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4178 return CK_FloatingCast; 4179 } 4180 case Type::STK_Bool: 4181 return CK_FloatingComplexToBoolean; 4182 case Type::STK_Integral: 4183 Src = ImpCastExprToType(Src.take(), 4184 SrcTy->castAs<ComplexType>()->getElementType(), 4185 CK_FloatingComplexToReal); 4186 return CK_FloatingToIntegral; 4187 case Type::STK_CPointer: 4188 case Type::STK_ObjCObjectPointer: 4189 case Type::STK_BlockPointer: 4190 llvm_unreachable("valid complex float->pointer cast?"); 4191 case Type::STK_MemberPointer: 4192 llvm_unreachable("member pointer type in C"); 4193 } 4194 llvm_unreachable("Should have returned before this"); 4195 4196 case Type::STK_IntegralComplex: 4197 switch (DestTy->getScalarTypeKind()) { 4198 case Type::STK_FloatingComplex: 4199 return CK_IntegralComplexToFloatingComplex; 4200 case Type::STK_IntegralComplex: 4201 return CK_IntegralComplexCast; 4202 case Type::STK_Integral: { 4203 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4204 if (Context.hasSameType(ET, DestTy)) 4205 return CK_IntegralComplexToReal; 4206 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4207 return CK_IntegralCast; 4208 } 4209 case Type::STK_Bool: 4210 return CK_IntegralComplexToBoolean; 4211 case Type::STK_Floating: 4212 Src = ImpCastExprToType(Src.take(), 4213 SrcTy->castAs<ComplexType>()->getElementType(), 4214 CK_IntegralComplexToReal); 4215 return CK_IntegralToFloating; 4216 case Type::STK_CPointer: 4217 case Type::STK_ObjCObjectPointer: 4218 case Type::STK_BlockPointer: 4219 llvm_unreachable("valid complex int->pointer cast?"); 4220 case Type::STK_MemberPointer: 4221 llvm_unreachable("member pointer type in C"); 4222 } 4223 llvm_unreachable("Should have returned before this"); 4224 } 4225 4226 llvm_unreachable("Unhandled scalar cast"); 4227} 4228 4229bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4230 CastKind &Kind) { 4231 assert(VectorTy->isVectorType() && "Not a vector type!"); 4232 4233 if (Ty->isVectorType() || Ty->isIntegerType()) { 4234 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4235 return Diag(R.getBegin(), 4236 Ty->isVectorType() ? 4237 diag::err_invalid_conversion_between_vectors : 4238 diag::err_invalid_conversion_between_vector_and_integer) 4239 << VectorTy << Ty << R; 4240 } else 4241 return Diag(R.getBegin(), 4242 diag::err_invalid_conversion_between_vector_and_scalar) 4243 << VectorTy << Ty << R; 4244 4245 Kind = CK_BitCast; 4246 return false; 4247} 4248 4249ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4250 Expr *CastExpr, CastKind &Kind) { 4251 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4252 4253 QualType SrcTy = CastExpr->getType(); 4254 4255 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4256 // an ExtVectorType. 4257 // In OpenCL, casts between vectors of different types are not allowed. 4258 // (See OpenCL 6.2). 4259 if (SrcTy->isVectorType()) { 4260 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4261 || (getLangOpts().OpenCL && 4262 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4263 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4264 << DestTy << SrcTy << R; 4265 return ExprError(); 4266 } 4267 Kind = CK_BitCast; 4268 return Owned(CastExpr); 4269 } 4270 4271 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4272 // conversion will take place first from scalar to elt type, and then 4273 // splat from elt type to vector. 4274 if (SrcTy->isPointerType()) 4275 return Diag(R.getBegin(), 4276 diag::err_invalid_conversion_between_vector_and_scalar) 4277 << DestTy << SrcTy << R; 4278 4279 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4280 ExprResult CastExprRes = Owned(CastExpr); 4281 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4282 if (CastExprRes.isInvalid()) 4283 return ExprError(); 4284 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4285 4286 Kind = CK_VectorSplat; 4287 return Owned(CastExpr); 4288} 4289 4290ExprResult 4291Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4292 Declarator &D, ParsedType &Ty, 4293 SourceLocation RParenLoc, Expr *CastExpr) { 4294 assert(!D.isInvalidType() && (CastExpr != 0) && 4295 "ActOnCastExpr(): missing type or expr"); 4296 4297 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4298 if (D.isInvalidType()) 4299 return ExprError(); 4300 4301 if (getLangOpts().CPlusPlus) { 4302 // Check that there are no default arguments (C++ only). 4303 CheckExtraCXXDefaultArguments(D); 4304 } 4305 4306 checkUnusedDeclAttributes(D); 4307 4308 QualType castType = castTInfo->getType(); 4309 Ty = CreateParsedType(castType, castTInfo); 4310 4311 bool isVectorLiteral = false; 4312 4313 // Check for an altivec or OpenCL literal, 4314 // i.e. all the elements are integer constants. 4315 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4316 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4317 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 4318 && castType->isVectorType() && (PE || PLE)) { 4319 if (PLE && PLE->getNumExprs() == 0) { 4320 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4321 return ExprError(); 4322 } 4323 if (PE || PLE->getNumExprs() == 1) { 4324 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4325 if (!E->getType()->isVectorType()) 4326 isVectorLiteral = true; 4327 } 4328 else 4329 isVectorLiteral = true; 4330 } 4331 4332 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4333 // then handle it as such. 4334 if (isVectorLiteral) 4335 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4336 4337 // If the Expr being casted is a ParenListExpr, handle it specially. 4338 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4339 // sequence of BinOp comma operators. 4340 if (isa<ParenListExpr>(CastExpr)) { 4341 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4342 if (Result.isInvalid()) return ExprError(); 4343 CastExpr = Result.take(); 4344 } 4345 4346 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4347} 4348 4349ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4350 SourceLocation RParenLoc, Expr *E, 4351 TypeSourceInfo *TInfo) { 4352 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4353 "Expected paren or paren list expression"); 4354 4355 Expr **exprs; 4356 unsigned numExprs; 4357 Expr *subExpr; 4358 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4359 exprs = PE->getExprs(); 4360 numExprs = PE->getNumExprs(); 4361 } else { 4362 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4363 exprs = &subExpr; 4364 numExprs = 1; 4365 } 4366 4367 QualType Ty = TInfo->getType(); 4368 assert(Ty->isVectorType() && "Expected vector type"); 4369 4370 SmallVector<Expr *, 8> initExprs; 4371 const VectorType *VTy = Ty->getAs<VectorType>(); 4372 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4373 4374 // '(...)' form of vector initialization in AltiVec: the number of 4375 // initializers must be one or must match the size of the vector. 4376 // If a single value is specified in the initializer then it will be 4377 // replicated to all the components of the vector 4378 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4379 // The number of initializers must be one or must match the size of the 4380 // vector. If a single value is specified in the initializer then it will 4381 // be replicated to all the components of the vector 4382 if (numExprs == 1) { 4383 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4384 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4385 if (Literal.isInvalid()) 4386 return ExprError(); 4387 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4388 PrepareScalarCast(Literal, ElemTy)); 4389 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4390 } 4391 else if (numExprs < numElems) { 4392 Diag(E->getExprLoc(), 4393 diag::err_incorrect_number_of_vector_initializers); 4394 return ExprError(); 4395 } 4396 else 4397 initExprs.append(exprs, exprs + numExprs); 4398 } 4399 else { 4400 // For OpenCL, when the number of initializers is a single value, 4401 // it will be replicated to all components of the vector. 4402 if (getLangOpts().OpenCL && 4403 VTy->getVectorKind() == VectorType::GenericVector && 4404 numExprs == 1) { 4405 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4406 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4407 if (Literal.isInvalid()) 4408 return ExprError(); 4409 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4410 PrepareScalarCast(Literal, ElemTy)); 4411 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4412 } 4413 4414 initExprs.append(exprs, exprs + numExprs); 4415 } 4416 // FIXME: This means that pretty-printing the final AST will produce curly 4417 // braces instead of the original commas. 4418 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc, 4419 &initExprs[0], 4420 initExprs.size(), RParenLoc); 4421 initE->setType(Ty); 4422 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4423} 4424 4425/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4426/// the ParenListExpr into a sequence of comma binary operators. 4427ExprResult 4428Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4429 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4430 if (!E) 4431 return Owned(OrigExpr); 4432 4433 ExprResult Result(E->getExpr(0)); 4434 4435 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4436 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4437 E->getExpr(i)); 4438 4439 if (Result.isInvalid()) return ExprError(); 4440 4441 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4442} 4443 4444ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4445 SourceLocation R, 4446 MultiExprArg Val) { 4447 unsigned nexprs = Val.size(); 4448 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 4449 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 4450 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 4451 return Owned(expr); 4452} 4453 4454/// \brief Emit a specialized diagnostic when one expression is a null pointer 4455/// constant and the other is not a pointer. Returns true if a diagnostic is 4456/// emitted. 4457bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4458 SourceLocation QuestionLoc) { 4459 Expr *NullExpr = LHSExpr; 4460 Expr *NonPointerExpr = RHSExpr; 4461 Expr::NullPointerConstantKind NullKind = 4462 NullExpr->isNullPointerConstant(Context, 4463 Expr::NPC_ValueDependentIsNotNull); 4464 4465 if (NullKind == Expr::NPCK_NotNull) { 4466 NullExpr = RHSExpr; 4467 NonPointerExpr = LHSExpr; 4468 NullKind = 4469 NullExpr->isNullPointerConstant(Context, 4470 Expr::NPC_ValueDependentIsNotNull); 4471 } 4472 4473 if (NullKind == Expr::NPCK_NotNull) 4474 return false; 4475 4476 if (NullKind == Expr::NPCK_ZeroInteger) { 4477 // In this case, check to make sure that we got here from a "NULL" 4478 // string in the source code. 4479 NullExpr = NullExpr->IgnoreParenImpCasts(); 4480 SourceLocation loc = NullExpr->getExprLoc(); 4481 if (!findMacroSpelling(loc, "NULL")) 4482 return false; 4483 } 4484 4485 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr); 4486 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 4487 << NonPointerExpr->getType() << DiagType 4488 << NonPointerExpr->getSourceRange(); 4489 return true; 4490} 4491 4492/// \brief Return false if the condition expression is valid, true otherwise. 4493static bool checkCondition(Sema &S, Expr *Cond) { 4494 QualType CondTy = Cond->getType(); 4495 4496 // C99 6.5.15p2 4497 if (CondTy->isScalarType()) return false; 4498 4499 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 4500 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 4501 return false; 4502 4503 // Emit the proper error message. 4504 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 4505 diag::err_typecheck_cond_expect_scalar : 4506 diag::err_typecheck_cond_expect_scalar_or_vector) 4507 << CondTy; 4508 return true; 4509} 4510 4511/// \brief Return false if the two expressions can be converted to a vector, 4512/// true otherwise 4513static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 4514 ExprResult &RHS, 4515 QualType CondTy) { 4516 // Both operands should be of scalar type. 4517 if (!LHS.get()->getType()->isScalarType()) { 4518 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4519 << CondTy; 4520 return true; 4521 } 4522 if (!RHS.get()->getType()->isScalarType()) { 4523 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4524 << CondTy; 4525 return true; 4526 } 4527 4528 // Implicity convert these scalars to the type of the condition. 4529 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 4530 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 4531 return false; 4532} 4533 4534/// \brief Handle when one or both operands are void type. 4535static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 4536 ExprResult &RHS) { 4537 Expr *LHSExpr = LHS.get(); 4538 Expr *RHSExpr = RHS.get(); 4539 4540 if (!LHSExpr->getType()->isVoidType()) 4541 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4542 << RHSExpr->getSourceRange(); 4543 if (!RHSExpr->getType()->isVoidType()) 4544 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4545 << LHSExpr->getSourceRange(); 4546 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 4547 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 4548 return S.Context.VoidTy; 4549} 4550 4551/// \brief Return false if the NullExpr can be promoted to PointerTy, 4552/// true otherwise. 4553static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 4554 QualType PointerTy) { 4555 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 4556 !NullExpr.get()->isNullPointerConstant(S.Context, 4557 Expr::NPC_ValueDependentIsNull)) 4558 return true; 4559 4560 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 4561 return false; 4562} 4563 4564/// \brief Checks compatibility between two pointers and return the resulting 4565/// type. 4566static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 4567 ExprResult &RHS, 4568 SourceLocation Loc) { 4569 QualType LHSTy = LHS.get()->getType(); 4570 QualType RHSTy = RHS.get()->getType(); 4571 4572 if (S.Context.hasSameType(LHSTy, RHSTy)) { 4573 // Two identical pointers types are always compatible. 4574 return LHSTy; 4575 } 4576 4577 QualType lhptee, rhptee; 4578 4579 // Get the pointee types. 4580 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 4581 lhptee = LHSBTy->getPointeeType(); 4582 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 4583 } else { 4584 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 4585 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 4586 } 4587 4588 // C99 6.5.15p6: If both operands are pointers to compatible types or to 4589 // differently qualified versions of compatible types, the result type is 4590 // a pointer to an appropriately qualified version of the composite 4591 // type. 4592 4593 // Only CVR-qualifiers exist in the standard, and the differently-qualified 4594 // clause doesn't make sense for our extensions. E.g. address space 2 should 4595 // be incompatible with address space 3: they may live on different devices or 4596 // anything. 4597 Qualifiers lhQual = lhptee.getQualifiers(); 4598 Qualifiers rhQual = rhptee.getQualifiers(); 4599 4600 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 4601 lhQual.removeCVRQualifiers(); 4602 rhQual.removeCVRQualifiers(); 4603 4604 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 4605 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 4606 4607 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 4608 4609 if (CompositeTy.isNull()) { 4610 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 4611 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4612 << RHS.get()->getSourceRange(); 4613 // In this situation, we assume void* type. No especially good 4614 // reason, but this is what gcc does, and we do have to pick 4615 // to get a consistent AST. 4616 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 4617 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4618 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4619 return incompatTy; 4620 } 4621 4622 // The pointer types are compatible. 4623 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 4624 ResultTy = S.Context.getPointerType(ResultTy); 4625 4626 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 4627 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 4628 return ResultTy; 4629} 4630 4631/// \brief Return the resulting type when the operands are both block pointers. 4632static QualType checkConditionalBlockPointerCompatibility(Sema &S, 4633 ExprResult &LHS, 4634 ExprResult &RHS, 4635 SourceLocation Loc) { 4636 QualType LHSTy = LHS.get()->getType(); 4637 QualType RHSTy = RHS.get()->getType(); 4638 4639 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4640 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4641 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 4642 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4643 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4644 return destType; 4645 } 4646 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 4647 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4648 << RHS.get()->getSourceRange(); 4649 return QualType(); 4650 } 4651 4652 // We have 2 block pointer types. 4653 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4654} 4655 4656/// \brief Return the resulting type when the operands are both pointers. 4657static QualType 4658checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 4659 ExprResult &RHS, 4660 SourceLocation Loc) { 4661 // get the pointer types 4662 QualType LHSTy = LHS.get()->getType(); 4663 QualType RHSTy = RHS.get()->getType(); 4664 4665 // get the "pointed to" types 4666 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4667 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4668 4669 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4670 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4671 // Figure out necessary qualifiers (C99 6.5.15p6) 4672 QualType destPointee 4673 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4674 QualType destType = S.Context.getPointerType(destPointee); 4675 // Add qualifiers if necessary. 4676 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4677 // Promote to void*. 4678 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4679 return destType; 4680 } 4681 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4682 QualType destPointee 4683 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4684 QualType destType = S.Context.getPointerType(destPointee); 4685 // Add qualifiers if necessary. 4686 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4687 // Promote to void*. 4688 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4689 return destType; 4690 } 4691 4692 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4693} 4694 4695/// \brief Return false if the first expression is not an integer and the second 4696/// expression is not a pointer, true otherwise. 4697static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 4698 Expr* PointerExpr, SourceLocation Loc, 4699 bool IsIntFirstExpr) { 4700 if (!PointerExpr->getType()->isPointerType() || 4701 !Int.get()->getType()->isIntegerType()) 4702 return false; 4703 4704 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 4705 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 4706 4707 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4708 << Expr1->getType() << Expr2->getType() 4709 << Expr1->getSourceRange() << Expr2->getSourceRange(); 4710 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 4711 CK_IntegralToPointer); 4712 return true; 4713} 4714 4715/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 4716/// In that case, LHS = cond. 4717/// C99 6.5.15 4718QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4719 ExprResult &RHS, ExprValueKind &VK, 4720 ExprObjectKind &OK, 4721 SourceLocation QuestionLoc) { 4722 4723 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 4724 if (!LHSResult.isUsable()) return QualType(); 4725 LHS = move(LHSResult); 4726 4727 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 4728 if (!RHSResult.isUsable()) return QualType(); 4729 RHS = move(RHSResult); 4730 4731 // C++ is sufficiently different to merit its own checker. 4732 if (getLangOpts().CPlusPlus) 4733 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 4734 4735 VK = VK_RValue; 4736 OK = OK_Ordinary; 4737 4738 Cond = UsualUnaryConversions(Cond.take()); 4739 if (Cond.isInvalid()) 4740 return QualType(); 4741 LHS = UsualUnaryConversions(LHS.take()); 4742 if (LHS.isInvalid()) 4743 return QualType(); 4744 RHS = UsualUnaryConversions(RHS.take()); 4745 if (RHS.isInvalid()) 4746 return QualType(); 4747 4748 QualType CondTy = Cond.get()->getType(); 4749 QualType LHSTy = LHS.get()->getType(); 4750 QualType RHSTy = RHS.get()->getType(); 4751 4752 // first, check the condition. 4753 if (checkCondition(*this, Cond.get())) 4754 return QualType(); 4755 4756 // Now check the two expressions. 4757 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 4758 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 4759 4760 // OpenCL: If the condition is a vector, and both operands are scalar, 4761 // attempt to implicity convert them to the vector type to act like the 4762 // built in select. 4763 if (getLangOpts().OpenCL && CondTy->isVectorType()) 4764 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 4765 return QualType(); 4766 4767 // If both operands have arithmetic type, do the usual arithmetic conversions 4768 // to find a common type: C99 6.5.15p3,5. 4769 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 4770 UsualArithmeticConversions(LHS, RHS); 4771 if (LHS.isInvalid() || RHS.isInvalid()) 4772 return QualType(); 4773 return LHS.get()->getType(); 4774 } 4775 4776 // If both operands are the same structure or union type, the result is that 4777 // type. 4778 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 4779 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 4780 if (LHSRT->getDecl() == RHSRT->getDecl()) 4781 // "If both the operands have structure or union type, the result has 4782 // that type." This implies that CV qualifiers are dropped. 4783 return LHSTy.getUnqualifiedType(); 4784 // FIXME: Type of conditional expression must be complete in C mode. 4785 } 4786 4787 // C99 6.5.15p5: "If both operands have void type, the result has void type." 4788 // The following || allows only one side to be void (a GCC-ism). 4789 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 4790 return checkConditionalVoidType(*this, LHS, RHS); 4791 } 4792 4793 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 4794 // the type of the other operand." 4795 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 4796 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 4797 4798 // All objective-c pointer type analysis is done here. 4799 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 4800 QuestionLoc); 4801 if (LHS.isInvalid() || RHS.isInvalid()) 4802 return QualType(); 4803 if (!compositeType.isNull()) 4804 return compositeType; 4805 4806 4807 // Handle block pointer types. 4808 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 4809 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 4810 QuestionLoc); 4811 4812 // Check constraints for C object pointers types (C99 6.5.15p3,6). 4813 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 4814 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 4815 QuestionLoc); 4816 4817 // GCC compatibility: soften pointer/integer mismatch. Note that 4818 // null pointers have been filtered out by this point. 4819 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 4820 /*isIntFirstExpr=*/true)) 4821 return RHSTy; 4822 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 4823 /*isIntFirstExpr=*/false)) 4824 return LHSTy; 4825 4826 // Emit a better diagnostic if one of the expressions is a null pointer 4827 // constant and the other is not a pointer type. In this case, the user most 4828 // likely forgot to take the address of the other expression. 4829 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4830 return QualType(); 4831 4832 // Otherwise, the operands are not compatible. 4833 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4834 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4835 << RHS.get()->getSourceRange(); 4836 return QualType(); 4837} 4838 4839/// FindCompositeObjCPointerType - Helper method to find composite type of 4840/// two objective-c pointer types of the two input expressions. 4841QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 4842 SourceLocation QuestionLoc) { 4843 QualType LHSTy = LHS.get()->getType(); 4844 QualType RHSTy = RHS.get()->getType(); 4845 4846 // Handle things like Class and struct objc_class*. Here we case the result 4847 // to the pseudo-builtin, because that will be implicitly cast back to the 4848 // redefinition type if an attempt is made to access its fields. 4849 if (LHSTy->isObjCClassType() && 4850 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 4851 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 4852 return LHSTy; 4853 } 4854 if (RHSTy->isObjCClassType() && 4855 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 4856 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 4857 return RHSTy; 4858 } 4859 // And the same for struct objc_object* / id 4860 if (LHSTy->isObjCIdType() && 4861 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 4862 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 4863 return LHSTy; 4864 } 4865 if (RHSTy->isObjCIdType() && 4866 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 4867 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 4868 return RHSTy; 4869 } 4870 // And the same for struct objc_selector* / SEL 4871 if (Context.isObjCSelType(LHSTy) && 4872 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 4873 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4874 return LHSTy; 4875 } 4876 if (Context.isObjCSelType(RHSTy) && 4877 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 4878 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 4879 return RHSTy; 4880 } 4881 // Check constraints for Objective-C object pointers types. 4882 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 4883 4884 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4885 // Two identical object pointer types are always compatible. 4886 return LHSTy; 4887 } 4888 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 4889 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 4890 QualType compositeType = LHSTy; 4891 4892 // If both operands are interfaces and either operand can be 4893 // assigned to the other, use that type as the composite 4894 // type. This allows 4895 // xxx ? (A*) a : (B*) b 4896 // where B is a subclass of A. 4897 // 4898 // Additionally, as for assignment, if either type is 'id' 4899 // allow silent coercion. Finally, if the types are 4900 // incompatible then make sure to use 'id' as the composite 4901 // type so the result is acceptable for sending messages to. 4902 4903 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 4904 // It could return the composite type. 4905 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 4906 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 4907 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 4908 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 4909 } else if ((LHSTy->isObjCQualifiedIdType() || 4910 RHSTy->isObjCQualifiedIdType()) && 4911 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 4912 // Need to handle "id<xx>" explicitly. 4913 // GCC allows qualified id and any Objective-C type to devolve to 4914 // id. Currently localizing to here until clear this should be 4915 // part of ObjCQualifiedIdTypesAreCompatible. 4916 compositeType = Context.getObjCIdType(); 4917 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 4918 compositeType = Context.getObjCIdType(); 4919 } else if (!(compositeType = 4920 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 4921 ; 4922 else { 4923 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 4924 << LHSTy << RHSTy 4925 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4926 QualType incompatTy = Context.getObjCIdType(); 4927 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4928 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4929 return incompatTy; 4930 } 4931 // The object pointer types are compatible. 4932 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 4933 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 4934 return compositeType; 4935 } 4936 // Check Objective-C object pointer types and 'void *' 4937 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 4938 if (getLangOpts().ObjCAutoRefCount) { 4939 // ARC forbids the implicit conversion of object pointers to 'void *', 4940 // so these types are not compatible. 4941 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 4942 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4943 LHS = RHS = true; 4944 return QualType(); 4945 } 4946 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4947 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4948 QualType destPointee 4949 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4950 QualType destType = Context.getPointerType(destPointee); 4951 // Add qualifiers if necessary. 4952 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4953 // Promote to void*. 4954 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4955 return destType; 4956 } 4957 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 4958 if (getLangOpts().ObjCAutoRefCount) { 4959 // ARC forbids the implicit conversion of object pointers to 'void *', 4960 // so these types are not compatible. 4961 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 4962 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4963 LHS = RHS = true; 4964 return QualType(); 4965 } 4966 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4967 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4968 QualType destPointee 4969 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4970 QualType destType = Context.getPointerType(destPointee); 4971 // Add qualifiers if necessary. 4972 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4973 // Promote to void*. 4974 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4975 return destType; 4976 } 4977 return QualType(); 4978} 4979 4980/// SuggestParentheses - Emit a note with a fixit hint that wraps 4981/// ParenRange in parentheses. 4982static void SuggestParentheses(Sema &Self, SourceLocation Loc, 4983 const PartialDiagnostic &Note, 4984 SourceRange ParenRange) { 4985 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 4986 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 4987 EndLoc.isValid()) { 4988 Self.Diag(Loc, Note) 4989 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 4990 << FixItHint::CreateInsertion(EndLoc, ")"); 4991 } else { 4992 // We can't display the parentheses, so just show the bare note. 4993 Self.Diag(Loc, Note) << ParenRange; 4994 } 4995} 4996 4997static bool IsArithmeticOp(BinaryOperatorKind Opc) { 4998 return Opc >= BO_Mul && Opc <= BO_Shr; 4999} 5000 5001/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5002/// expression, either using a built-in or overloaded operator, 5003/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5004/// expression. 5005static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5006 Expr **RHSExprs) { 5007 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5008 E = E->IgnoreImpCasts(); 5009 E = E->IgnoreConversionOperator(); 5010 E = E->IgnoreImpCasts(); 5011 5012 // Built-in binary operator. 5013 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5014 if (IsArithmeticOp(OP->getOpcode())) { 5015 *Opcode = OP->getOpcode(); 5016 *RHSExprs = OP->getRHS(); 5017 return true; 5018 } 5019 } 5020 5021 // Overloaded operator. 5022 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5023 if (Call->getNumArgs() != 2) 5024 return false; 5025 5026 // Make sure this is really a binary operator that is safe to pass into 5027 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5028 OverloadedOperatorKind OO = Call->getOperator(); 5029 if (OO < OO_Plus || OO > OO_Arrow) 5030 return false; 5031 5032 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5033 if (IsArithmeticOp(OpKind)) { 5034 *Opcode = OpKind; 5035 *RHSExprs = Call->getArg(1); 5036 return true; 5037 } 5038 } 5039 5040 return false; 5041} 5042 5043static bool IsLogicOp(BinaryOperatorKind Opc) { 5044 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5045} 5046 5047/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5048/// or is a logical expression such as (x==y) which has int type, but is 5049/// commonly interpreted as boolean. 5050static bool ExprLooksBoolean(Expr *E) { 5051 E = E->IgnoreParenImpCasts(); 5052 5053 if (E->getType()->isBooleanType()) 5054 return true; 5055 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5056 return IsLogicOp(OP->getOpcode()); 5057 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5058 return OP->getOpcode() == UO_LNot; 5059 5060 return false; 5061} 5062 5063/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5064/// and binary operator are mixed in a way that suggests the programmer assumed 5065/// the conditional operator has higher precedence, for example: 5066/// "int x = a + someBinaryCondition ? 1 : 2". 5067static void DiagnoseConditionalPrecedence(Sema &Self, 5068 SourceLocation OpLoc, 5069 Expr *Condition, 5070 Expr *LHSExpr, 5071 Expr *RHSExpr) { 5072 BinaryOperatorKind CondOpcode; 5073 Expr *CondRHS; 5074 5075 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5076 return; 5077 if (!ExprLooksBoolean(CondRHS)) 5078 return; 5079 5080 // The condition is an arithmetic binary expression, with a right- 5081 // hand side that looks boolean, so warn. 5082 5083 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5084 << Condition->getSourceRange() 5085 << BinaryOperator::getOpcodeStr(CondOpcode); 5086 5087 SuggestParentheses(Self, OpLoc, 5088 Self.PDiag(diag::note_precedence_conditional_silence) 5089 << BinaryOperator::getOpcodeStr(CondOpcode), 5090 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5091 5092 SuggestParentheses(Self, OpLoc, 5093 Self.PDiag(diag::note_precedence_conditional_first), 5094 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5095} 5096 5097/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5098/// in the case of a the GNU conditional expr extension. 5099ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5100 SourceLocation ColonLoc, 5101 Expr *CondExpr, Expr *LHSExpr, 5102 Expr *RHSExpr) { 5103 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5104 // was the condition. 5105 OpaqueValueExpr *opaqueValue = 0; 5106 Expr *commonExpr = 0; 5107 if (LHSExpr == 0) { 5108 commonExpr = CondExpr; 5109 5110 // We usually want to apply unary conversions *before* saving, except 5111 // in the special case of a C++ l-value conditional. 5112 if (!(getLangOpts().CPlusPlus 5113 && !commonExpr->isTypeDependent() 5114 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5115 && commonExpr->isGLValue() 5116 && commonExpr->isOrdinaryOrBitFieldObject() 5117 && RHSExpr->isOrdinaryOrBitFieldObject() 5118 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5119 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5120 if (commonRes.isInvalid()) 5121 return ExprError(); 5122 commonExpr = commonRes.take(); 5123 } 5124 5125 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5126 commonExpr->getType(), 5127 commonExpr->getValueKind(), 5128 commonExpr->getObjectKind(), 5129 commonExpr); 5130 LHSExpr = CondExpr = opaqueValue; 5131 } 5132 5133 ExprValueKind VK = VK_RValue; 5134 ExprObjectKind OK = OK_Ordinary; 5135 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5136 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5137 VK, OK, QuestionLoc); 5138 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5139 RHS.isInvalid()) 5140 return ExprError(); 5141 5142 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5143 RHS.get()); 5144 5145 if (!commonExpr) 5146 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5147 LHS.take(), ColonLoc, 5148 RHS.take(), result, VK, OK)); 5149 5150 return Owned(new (Context) 5151 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5152 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5153 OK)); 5154} 5155 5156// checkPointerTypesForAssignment - This is a very tricky routine (despite 5157// being closely modeled after the C99 spec:-). The odd characteristic of this 5158// routine is it effectively iqnores the qualifiers on the top level pointee. 5159// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5160// FIXME: add a couple examples in this comment. 5161static Sema::AssignConvertType 5162checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5163 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5164 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5165 5166 // get the "pointed to" type (ignoring qualifiers at the top level) 5167 const Type *lhptee, *rhptee; 5168 Qualifiers lhq, rhq; 5169 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5170 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5171 5172 Sema::AssignConvertType ConvTy = Sema::Compatible; 5173 5174 // C99 6.5.16.1p1: This following citation is common to constraints 5175 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5176 // qualifiers of the type *pointed to* by the right; 5177 Qualifiers lq; 5178 5179 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5180 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5181 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5182 // Ignore lifetime for further calculation. 5183 lhq.removeObjCLifetime(); 5184 rhq.removeObjCLifetime(); 5185 } 5186 5187 if (!lhq.compatiblyIncludes(rhq)) { 5188 // Treat address-space mismatches as fatal. TODO: address subspaces 5189 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5190 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5191 5192 // It's okay to add or remove GC or lifetime qualifiers when converting to 5193 // and from void*. 5194 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5195 .compatiblyIncludes( 5196 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5197 && (lhptee->isVoidType() || rhptee->isVoidType())) 5198 ; // keep old 5199 5200 // Treat lifetime mismatches as fatal. 5201 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5202 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5203 5204 // For GCC compatibility, other qualifier mismatches are treated 5205 // as still compatible in C. 5206 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5207 } 5208 5209 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5210 // incomplete type and the other is a pointer to a qualified or unqualified 5211 // version of void... 5212 if (lhptee->isVoidType()) { 5213 if (rhptee->isIncompleteOrObjectType()) 5214 return ConvTy; 5215 5216 // As an extension, we allow cast to/from void* to function pointer. 5217 assert(rhptee->isFunctionType()); 5218 return Sema::FunctionVoidPointer; 5219 } 5220 5221 if (rhptee->isVoidType()) { 5222 if (lhptee->isIncompleteOrObjectType()) 5223 return ConvTy; 5224 5225 // As an extension, we allow cast to/from void* to function pointer. 5226 assert(lhptee->isFunctionType()); 5227 return Sema::FunctionVoidPointer; 5228 } 5229 5230 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5231 // unqualified versions of compatible types, ... 5232 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5233 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5234 // Check if the pointee types are compatible ignoring the sign. 5235 // We explicitly check for char so that we catch "char" vs 5236 // "unsigned char" on systems where "char" is unsigned. 5237 if (lhptee->isCharType()) 5238 ltrans = S.Context.UnsignedCharTy; 5239 else if (lhptee->hasSignedIntegerRepresentation()) 5240 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5241 5242 if (rhptee->isCharType()) 5243 rtrans = S.Context.UnsignedCharTy; 5244 else if (rhptee->hasSignedIntegerRepresentation()) 5245 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5246 5247 if (ltrans == rtrans) { 5248 // Types are compatible ignoring the sign. Qualifier incompatibility 5249 // takes priority over sign incompatibility because the sign 5250 // warning can be disabled. 5251 if (ConvTy != Sema::Compatible) 5252 return ConvTy; 5253 5254 return Sema::IncompatiblePointerSign; 5255 } 5256 5257 // If we are a multi-level pointer, it's possible that our issue is simply 5258 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5259 // the eventual target type is the same and the pointers have the same 5260 // level of indirection, this must be the issue. 5261 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5262 do { 5263 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5264 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5265 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5266 5267 if (lhptee == rhptee) 5268 return Sema::IncompatibleNestedPointerQualifiers; 5269 } 5270 5271 // General pointer incompatibility takes priority over qualifiers. 5272 return Sema::IncompatiblePointer; 5273 } 5274 if (!S.getLangOpts().CPlusPlus && 5275 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5276 return Sema::IncompatiblePointer; 5277 return ConvTy; 5278} 5279 5280/// checkBlockPointerTypesForAssignment - This routine determines whether two 5281/// block pointer types are compatible or whether a block and normal pointer 5282/// are compatible. It is more restrict than comparing two function pointer 5283// types. 5284static Sema::AssignConvertType 5285checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5286 QualType RHSType) { 5287 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5288 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5289 5290 QualType lhptee, rhptee; 5291 5292 // get the "pointed to" type (ignoring qualifiers at the top level) 5293 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5294 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5295 5296 // In C++, the types have to match exactly. 5297 if (S.getLangOpts().CPlusPlus) 5298 return Sema::IncompatibleBlockPointer; 5299 5300 Sema::AssignConvertType ConvTy = Sema::Compatible; 5301 5302 // For blocks we enforce that qualifiers are identical. 5303 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5304 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5305 5306 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5307 return Sema::IncompatibleBlockPointer; 5308 5309 return ConvTy; 5310} 5311 5312/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5313/// for assignment compatibility. 5314static Sema::AssignConvertType 5315checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5316 QualType RHSType) { 5317 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5318 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5319 5320 if (LHSType->isObjCBuiltinType()) { 5321 // Class is not compatible with ObjC object pointers. 5322 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5323 !RHSType->isObjCQualifiedClassType()) 5324 return Sema::IncompatiblePointer; 5325 return Sema::Compatible; 5326 } 5327 if (RHSType->isObjCBuiltinType()) { 5328 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5329 !LHSType->isObjCQualifiedClassType()) 5330 return Sema::IncompatiblePointer; 5331 return Sema::Compatible; 5332 } 5333 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5334 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5335 5336 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5337 // make an exception for id<P> 5338 !LHSType->isObjCQualifiedIdType()) 5339 return Sema::CompatiblePointerDiscardsQualifiers; 5340 5341 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5342 return Sema::Compatible; 5343 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5344 return Sema::IncompatibleObjCQualifiedId; 5345 return Sema::IncompatiblePointer; 5346} 5347 5348Sema::AssignConvertType 5349Sema::CheckAssignmentConstraints(SourceLocation Loc, 5350 QualType LHSType, QualType RHSType) { 5351 // Fake up an opaque expression. We don't actually care about what 5352 // cast operations are required, so if CheckAssignmentConstraints 5353 // adds casts to this they'll be wasted, but fortunately that doesn't 5354 // usually happen on valid code. 5355 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5356 ExprResult RHSPtr = &RHSExpr; 5357 CastKind K = CK_Invalid; 5358 5359 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5360} 5361 5362/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5363/// has code to accommodate several GCC extensions when type checking 5364/// pointers. Here are some objectionable examples that GCC considers warnings: 5365/// 5366/// int a, *pint; 5367/// short *pshort; 5368/// struct foo *pfoo; 5369/// 5370/// pint = pshort; // warning: assignment from incompatible pointer type 5371/// a = pint; // warning: assignment makes integer from pointer without a cast 5372/// pint = a; // warning: assignment makes pointer from integer without a cast 5373/// pint = pfoo; // warning: assignment from incompatible pointer type 5374/// 5375/// As a result, the code for dealing with pointers is more complex than the 5376/// C99 spec dictates. 5377/// 5378/// Sets 'Kind' for any result kind except Incompatible. 5379Sema::AssignConvertType 5380Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5381 CastKind &Kind) { 5382 QualType RHSType = RHS.get()->getType(); 5383 QualType OrigLHSType = LHSType; 5384 5385 // Get canonical types. We're not formatting these types, just comparing 5386 // them. 5387 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5388 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5389 5390 5391 // Common case: no conversion required. 5392 if (LHSType == RHSType) { 5393 Kind = CK_NoOp; 5394 return Compatible; 5395 } 5396 5397 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5398 if (AtomicTy->getValueType() == RHSType) { 5399 Kind = CK_NonAtomicToAtomic; 5400 return Compatible; 5401 } 5402 } 5403 5404 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(RHSType)) { 5405 if (AtomicTy->getValueType() == LHSType) { 5406 Kind = CK_AtomicToNonAtomic; 5407 return Compatible; 5408 } 5409 } 5410 5411 5412 // If the left-hand side is a reference type, then we are in a 5413 // (rare!) case where we've allowed the use of references in C, 5414 // e.g., as a parameter type in a built-in function. In this case, 5415 // just make sure that the type referenced is compatible with the 5416 // right-hand side type. The caller is responsible for adjusting 5417 // LHSType so that the resulting expression does not have reference 5418 // type. 5419 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5420 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5421 Kind = CK_LValueBitCast; 5422 return Compatible; 5423 } 5424 return Incompatible; 5425 } 5426 5427 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5428 // to the same ExtVector type. 5429 if (LHSType->isExtVectorType()) { 5430 if (RHSType->isExtVectorType()) 5431 return Incompatible; 5432 if (RHSType->isArithmeticType()) { 5433 // CK_VectorSplat does T -> vector T, so first cast to the 5434 // element type. 5435 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5436 if (elType != RHSType) { 5437 Kind = PrepareScalarCast(RHS, elType); 5438 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5439 } 5440 Kind = CK_VectorSplat; 5441 return Compatible; 5442 } 5443 } 5444 5445 // Conversions to or from vector type. 5446 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5447 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5448 // Allow assignments of an AltiVec vector type to an equivalent GCC 5449 // vector type and vice versa 5450 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5451 Kind = CK_BitCast; 5452 return Compatible; 5453 } 5454 5455 // If we are allowing lax vector conversions, and LHS and RHS are both 5456 // vectors, the total size only needs to be the same. This is a bitcast; 5457 // no bits are changed but the result type is different. 5458 if (getLangOpts().LaxVectorConversions && 5459 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5460 Kind = CK_BitCast; 5461 return IncompatibleVectors; 5462 } 5463 } 5464 return Incompatible; 5465 } 5466 5467 // Arithmetic conversions. 5468 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5469 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 5470 Kind = PrepareScalarCast(RHS, LHSType); 5471 return Compatible; 5472 } 5473 5474 // Conversions to normal pointers. 5475 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5476 // U* -> T* 5477 if (isa<PointerType>(RHSType)) { 5478 Kind = CK_BitCast; 5479 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 5480 } 5481 5482 // int -> T* 5483 if (RHSType->isIntegerType()) { 5484 Kind = CK_IntegralToPointer; // FIXME: null? 5485 return IntToPointer; 5486 } 5487 5488 // C pointers are not compatible with ObjC object pointers, 5489 // with two exceptions: 5490 if (isa<ObjCObjectPointerType>(RHSType)) { 5491 // - conversions to void* 5492 if (LHSPointer->getPointeeType()->isVoidType()) { 5493 Kind = CK_BitCast; 5494 return Compatible; 5495 } 5496 5497 // - conversions from 'Class' to the redefinition type 5498 if (RHSType->isObjCClassType() && 5499 Context.hasSameType(LHSType, 5500 Context.getObjCClassRedefinitionType())) { 5501 Kind = CK_BitCast; 5502 return Compatible; 5503 } 5504 5505 Kind = CK_BitCast; 5506 return IncompatiblePointer; 5507 } 5508 5509 // U^ -> void* 5510 if (RHSType->getAs<BlockPointerType>()) { 5511 if (LHSPointer->getPointeeType()->isVoidType()) { 5512 Kind = CK_BitCast; 5513 return Compatible; 5514 } 5515 } 5516 5517 return Incompatible; 5518 } 5519 5520 // Conversions to block pointers. 5521 if (isa<BlockPointerType>(LHSType)) { 5522 // U^ -> T^ 5523 if (RHSType->isBlockPointerType()) { 5524 Kind = CK_BitCast; 5525 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 5526 } 5527 5528 // int or null -> T^ 5529 if (RHSType->isIntegerType()) { 5530 Kind = CK_IntegralToPointer; // FIXME: null 5531 return IntToBlockPointer; 5532 } 5533 5534 // id -> T^ 5535 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 5536 Kind = CK_AnyPointerToBlockPointerCast; 5537 return Compatible; 5538 } 5539 5540 // void* -> T^ 5541 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 5542 if (RHSPT->getPointeeType()->isVoidType()) { 5543 Kind = CK_AnyPointerToBlockPointerCast; 5544 return Compatible; 5545 } 5546 5547 return Incompatible; 5548 } 5549 5550 // Conversions to Objective-C pointers. 5551 if (isa<ObjCObjectPointerType>(LHSType)) { 5552 // A* -> B* 5553 if (RHSType->isObjCObjectPointerType()) { 5554 Kind = CK_BitCast; 5555 Sema::AssignConvertType result = 5556 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 5557 if (getLangOpts().ObjCAutoRefCount && 5558 result == Compatible && 5559 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 5560 result = IncompatibleObjCWeakRef; 5561 return result; 5562 } 5563 5564 // int or null -> A* 5565 if (RHSType->isIntegerType()) { 5566 Kind = CK_IntegralToPointer; // FIXME: null 5567 return IntToPointer; 5568 } 5569 5570 // In general, C pointers are not compatible with ObjC object pointers, 5571 // with two exceptions: 5572 if (isa<PointerType>(RHSType)) { 5573 Kind = CK_CPointerToObjCPointerCast; 5574 5575 // - conversions from 'void*' 5576 if (RHSType->isVoidPointerType()) { 5577 return Compatible; 5578 } 5579 5580 // - conversions to 'Class' from its redefinition type 5581 if (LHSType->isObjCClassType() && 5582 Context.hasSameType(RHSType, 5583 Context.getObjCClassRedefinitionType())) { 5584 return Compatible; 5585 } 5586 5587 return IncompatiblePointer; 5588 } 5589 5590 // T^ -> A* 5591 if (RHSType->isBlockPointerType()) { 5592 maybeExtendBlockObject(*this, RHS); 5593 Kind = CK_BlockPointerToObjCPointerCast; 5594 return Compatible; 5595 } 5596 5597 return Incompatible; 5598 } 5599 5600 // Conversions from pointers that are not covered by the above. 5601 if (isa<PointerType>(RHSType)) { 5602 // T* -> _Bool 5603 if (LHSType == Context.BoolTy) { 5604 Kind = CK_PointerToBoolean; 5605 return Compatible; 5606 } 5607 5608 // T* -> int 5609 if (LHSType->isIntegerType()) { 5610 Kind = CK_PointerToIntegral; 5611 return PointerToInt; 5612 } 5613 5614 return Incompatible; 5615 } 5616 5617 // Conversions from Objective-C pointers that are not covered by the above. 5618 if (isa<ObjCObjectPointerType>(RHSType)) { 5619 // T* -> _Bool 5620 if (LHSType == Context.BoolTy) { 5621 Kind = CK_PointerToBoolean; 5622 return Compatible; 5623 } 5624 5625 // T* -> int 5626 if (LHSType->isIntegerType()) { 5627 Kind = CK_PointerToIntegral; 5628 return PointerToInt; 5629 } 5630 5631 return Incompatible; 5632 } 5633 5634 // struct A -> struct B 5635 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 5636 if (Context.typesAreCompatible(LHSType, RHSType)) { 5637 Kind = CK_NoOp; 5638 return Compatible; 5639 } 5640 } 5641 5642 return Incompatible; 5643} 5644 5645/// \brief Constructs a transparent union from an expression that is 5646/// used to initialize the transparent union. 5647static void ConstructTransparentUnion(Sema &S, ASTContext &C, 5648 ExprResult &EResult, QualType UnionType, 5649 FieldDecl *Field) { 5650 // Build an initializer list that designates the appropriate member 5651 // of the transparent union. 5652 Expr *E = EResult.take(); 5653 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 5654 &E, 1, 5655 SourceLocation()); 5656 Initializer->setType(UnionType); 5657 Initializer->setInitializedFieldInUnion(Field); 5658 5659 // Build a compound literal constructing a value of the transparent 5660 // union type from this initializer list. 5661 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 5662 EResult = S.Owned( 5663 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 5664 VK_RValue, Initializer, false)); 5665} 5666 5667Sema::AssignConvertType 5668Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 5669 ExprResult &RHS) { 5670 QualType RHSType = RHS.get()->getType(); 5671 5672 // If the ArgType is a Union type, we want to handle a potential 5673 // transparent_union GCC extension. 5674 const RecordType *UT = ArgType->getAsUnionType(); 5675 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5676 return Incompatible; 5677 5678 // The field to initialize within the transparent union. 5679 RecordDecl *UD = UT->getDecl(); 5680 FieldDecl *InitField = 0; 5681 // It's compatible if the expression matches any of the fields. 5682 for (RecordDecl::field_iterator it = UD->field_begin(), 5683 itend = UD->field_end(); 5684 it != itend; ++it) { 5685 if (it->getType()->isPointerType()) { 5686 // If the transparent union contains a pointer type, we allow: 5687 // 1) void pointer 5688 // 2) null pointer constant 5689 if (RHSType->isPointerType()) 5690 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 5691 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 5692 InitField = &*it; 5693 break; 5694 } 5695 5696 if (RHS.get()->isNullPointerConstant(Context, 5697 Expr::NPC_ValueDependentIsNull)) { 5698 RHS = ImpCastExprToType(RHS.take(), it->getType(), 5699 CK_NullToPointer); 5700 InitField = &*it; 5701 break; 5702 } 5703 } 5704 5705 CastKind Kind = CK_Invalid; 5706 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 5707 == Compatible) { 5708 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 5709 InitField = &*it; 5710 break; 5711 } 5712 } 5713 5714 if (!InitField) 5715 return Incompatible; 5716 5717 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 5718 return Compatible; 5719} 5720 5721Sema::AssignConvertType 5722Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5723 bool Diagnose) { 5724 if (getLangOpts().CPlusPlus) { 5725 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 5726 // C++ 5.17p3: If the left operand is not of class type, the 5727 // expression is implicitly converted (C++ 4) to the 5728 // cv-unqualified type of the left operand. 5729 ExprResult Res; 5730 if (Diagnose) { 5731 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5732 AA_Assigning); 5733 } else { 5734 ImplicitConversionSequence ICS = 5735 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5736 /*SuppressUserConversions=*/false, 5737 /*AllowExplicit=*/false, 5738 /*InOverloadResolution=*/false, 5739 /*CStyle=*/false, 5740 /*AllowObjCWritebackConversion=*/false); 5741 if (ICS.isFailure()) 5742 return Incompatible; 5743 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5744 ICS, AA_Assigning); 5745 } 5746 if (Res.isInvalid()) 5747 return Incompatible; 5748 Sema::AssignConvertType result = Compatible; 5749 if (getLangOpts().ObjCAutoRefCount && 5750 !CheckObjCARCUnavailableWeakConversion(LHSType, 5751 RHS.get()->getType())) 5752 result = IncompatibleObjCWeakRef; 5753 RHS = move(Res); 5754 return result; 5755 } 5756 5757 // FIXME: Currently, we fall through and treat C++ classes like C 5758 // structures. 5759 // FIXME: We also fall through for atomics; not sure what should 5760 // happen there, though. 5761 } 5762 5763 // C99 6.5.16.1p1: the left operand is a pointer and the right is 5764 // a null pointer constant. 5765 if ((LHSType->isPointerType() || 5766 LHSType->isObjCObjectPointerType() || 5767 LHSType->isBlockPointerType()) 5768 && RHS.get()->isNullPointerConstant(Context, 5769 Expr::NPC_ValueDependentIsNull)) { 5770 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 5771 return Compatible; 5772 } 5773 5774 // This check seems unnatural, however it is necessary to ensure the proper 5775 // conversion of functions/arrays. If the conversion were done for all 5776 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 5777 // expressions that suppress this implicit conversion (&, sizeof). 5778 // 5779 // Suppress this for references: C++ 8.5.3p5. 5780 if (!LHSType->isReferenceType()) { 5781 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5782 if (RHS.isInvalid()) 5783 return Incompatible; 5784 } 5785 5786 CastKind Kind = CK_Invalid; 5787 Sema::AssignConvertType result = 5788 CheckAssignmentConstraints(LHSType, RHS, Kind); 5789 5790 // C99 6.5.16.1p2: The value of the right operand is converted to the 5791 // type of the assignment expression. 5792 // CheckAssignmentConstraints allows the left-hand side to be a reference, 5793 // so that we can use references in built-in functions even in C. 5794 // The getNonReferenceType() call makes sure that the resulting expression 5795 // does not have reference type. 5796 if (result != Incompatible && RHS.get()->getType() != LHSType) 5797 RHS = ImpCastExprToType(RHS.take(), 5798 LHSType.getNonLValueExprType(Context), Kind); 5799 return result; 5800} 5801 5802QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 5803 ExprResult &RHS) { 5804 Diag(Loc, diag::err_typecheck_invalid_operands) 5805 << LHS.get()->getType() << RHS.get()->getType() 5806 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5807 return QualType(); 5808} 5809 5810QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 5811 SourceLocation Loc, bool IsCompAssign) { 5812 if (!IsCompAssign) { 5813 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 5814 if (LHS.isInvalid()) 5815 return QualType(); 5816 } 5817 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5818 if (RHS.isInvalid()) 5819 return QualType(); 5820 5821 // For conversion purposes, we ignore any qualifiers. 5822 // For example, "const float" and "float" are equivalent. 5823 QualType LHSType = 5824 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 5825 QualType RHSType = 5826 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 5827 5828 // If the vector types are identical, return. 5829 if (LHSType == RHSType) 5830 return LHSType; 5831 5832 // Handle the case of equivalent AltiVec and GCC vector types 5833 if (LHSType->isVectorType() && RHSType->isVectorType() && 5834 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5835 if (LHSType->isExtVectorType()) { 5836 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5837 return LHSType; 5838 } 5839 5840 if (!IsCompAssign) 5841 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 5842 return RHSType; 5843 } 5844 5845 if (getLangOpts().LaxVectorConversions && 5846 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 5847 // If we are allowing lax vector conversions, and LHS and RHS are both 5848 // vectors, the total size only needs to be the same. This is a 5849 // bitcast; no bits are changed but the result type is different. 5850 // FIXME: Should we really be allowing this? 5851 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5852 return LHSType; 5853 } 5854 5855 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 5856 // swap back (so that we don't reverse the inputs to a subtract, for instance. 5857 bool swapped = false; 5858 if (RHSType->isExtVectorType() && !IsCompAssign) { 5859 swapped = true; 5860 std::swap(RHS, LHS); 5861 std::swap(RHSType, LHSType); 5862 } 5863 5864 // Handle the case of an ext vector and scalar. 5865 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 5866 QualType EltTy = LV->getElementType(); 5867 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 5868 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 5869 if (order > 0) 5870 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 5871 if (order >= 0) { 5872 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5873 if (swapped) std::swap(RHS, LHS); 5874 return LHSType; 5875 } 5876 } 5877 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 5878 RHSType->isRealFloatingType()) { 5879 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 5880 if (order > 0) 5881 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 5882 if (order >= 0) { 5883 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5884 if (swapped) std::swap(RHS, LHS); 5885 return LHSType; 5886 } 5887 } 5888 } 5889 5890 // Vectors of different size or scalar and non-ext-vector are errors. 5891 if (swapped) std::swap(RHS, LHS); 5892 Diag(Loc, diag::err_typecheck_vector_not_convertable) 5893 << LHS.get()->getType() << RHS.get()->getType() 5894 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5895 return QualType(); 5896} 5897 5898// checkArithmeticNull - Detect when a NULL constant is used improperly in an 5899// expression. These are mainly cases where the null pointer is used as an 5900// integer instead of a pointer. 5901static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 5902 SourceLocation Loc, bool IsCompare) { 5903 // The canonical way to check for a GNU null is with isNullPointerConstant, 5904 // but we use a bit of a hack here for speed; this is a relatively 5905 // hot path, and isNullPointerConstant is slow. 5906 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 5907 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 5908 5909 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 5910 5911 // Avoid analyzing cases where the result will either be invalid (and 5912 // diagnosed as such) or entirely valid and not something to warn about. 5913 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 5914 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 5915 return; 5916 5917 // Comparison operations would not make sense with a null pointer no matter 5918 // what the other expression is. 5919 if (!IsCompare) { 5920 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 5921 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 5922 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 5923 return; 5924 } 5925 5926 // The rest of the operations only make sense with a null pointer 5927 // if the other expression is a pointer. 5928 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 5929 NonNullType->canDecayToPointerType()) 5930 return; 5931 5932 S.Diag(Loc, diag::warn_null_in_comparison_operation) 5933 << LHSNull /* LHS is NULL */ << NonNullType 5934 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5935} 5936 5937QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 5938 SourceLocation Loc, 5939 bool IsCompAssign, bool IsDiv) { 5940 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 5941 5942 if (LHS.get()->getType()->isVectorType() || 5943 RHS.get()->getType()->isVectorType()) 5944 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 5945 5946 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 5947 if (LHS.isInvalid() || RHS.isInvalid()) 5948 return QualType(); 5949 5950 5951 if (!LHS.get()->getType()->isArithmeticType() || 5952 !RHS.get()->getType()->isArithmeticType()) { 5953 if (IsCompAssign && 5954 LHS.get()->getType()->isAtomicType() && 5955 RHS.get()->getType()->isArithmeticType()) 5956 return compType; 5957 return InvalidOperands(Loc, LHS, RHS); 5958 } 5959 5960 // Check for division by zero. 5961 if (IsDiv && 5962 RHS.get()->isNullPointerConstant(Context, 5963 Expr::NPC_ValueDependentIsNotNull)) 5964 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 5965 << RHS.get()->getSourceRange()); 5966 5967 return compType; 5968} 5969 5970QualType Sema::CheckRemainderOperands( 5971 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 5972 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 5973 5974 if (LHS.get()->getType()->isVectorType() || 5975 RHS.get()->getType()->isVectorType()) { 5976 if (LHS.get()->getType()->hasIntegerRepresentation() && 5977 RHS.get()->getType()->hasIntegerRepresentation()) 5978 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 5979 return InvalidOperands(Loc, LHS, RHS); 5980 } 5981 5982 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 5983 if (LHS.isInvalid() || RHS.isInvalid()) 5984 return QualType(); 5985 5986 if (!LHS.get()->getType()->isIntegerType() || 5987 !RHS.get()->getType()->isIntegerType()) 5988 return InvalidOperands(Loc, LHS, RHS); 5989 5990 // Check for remainder by zero. 5991 if (RHS.get()->isNullPointerConstant(Context, 5992 Expr::NPC_ValueDependentIsNotNull)) 5993 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 5994 << RHS.get()->getSourceRange()); 5995 5996 return compType; 5997} 5998 5999/// \brief Diagnose invalid arithmetic on two void pointers. 6000static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6001 Expr *LHSExpr, Expr *RHSExpr) { 6002 S.Diag(Loc, S.getLangOpts().CPlusPlus 6003 ? diag::err_typecheck_pointer_arith_void_type 6004 : diag::ext_gnu_void_ptr) 6005 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6006 << RHSExpr->getSourceRange(); 6007} 6008 6009/// \brief Diagnose invalid arithmetic on a void pointer. 6010static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6011 Expr *Pointer) { 6012 S.Diag(Loc, S.getLangOpts().CPlusPlus 6013 ? diag::err_typecheck_pointer_arith_void_type 6014 : diag::ext_gnu_void_ptr) 6015 << 0 /* one pointer */ << Pointer->getSourceRange(); 6016} 6017 6018/// \brief Diagnose invalid arithmetic on two function pointers. 6019static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6020 Expr *LHS, Expr *RHS) { 6021 assert(LHS->getType()->isAnyPointerType()); 6022 assert(RHS->getType()->isAnyPointerType()); 6023 S.Diag(Loc, S.getLangOpts().CPlusPlus 6024 ? diag::err_typecheck_pointer_arith_function_type 6025 : diag::ext_gnu_ptr_func_arith) 6026 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6027 // We only show the second type if it differs from the first. 6028 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6029 RHS->getType()) 6030 << RHS->getType()->getPointeeType() 6031 << LHS->getSourceRange() << RHS->getSourceRange(); 6032} 6033 6034/// \brief Diagnose invalid arithmetic on a function pointer. 6035static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6036 Expr *Pointer) { 6037 assert(Pointer->getType()->isAnyPointerType()); 6038 S.Diag(Loc, S.getLangOpts().CPlusPlus 6039 ? diag::err_typecheck_pointer_arith_function_type 6040 : diag::ext_gnu_ptr_func_arith) 6041 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6042 << 0 /* one pointer, so only one type */ 6043 << Pointer->getSourceRange(); 6044} 6045 6046/// \brief Emit error if Operand is incomplete pointer type 6047/// 6048/// \returns True if pointer has incomplete type 6049static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6050 Expr *Operand) { 6051 if ((Operand->getType()->isPointerType() && 6052 !Operand->getType()->isDependentType()) || 6053 Operand->getType()->isObjCObjectPointerType()) { 6054 QualType PointeeTy = Operand->getType()->getPointeeType(); 6055 if (S.RequireCompleteType( 6056 Loc, PointeeTy, 6057 diag::err_typecheck_arithmetic_incomplete_type, 6058 PointeeTy, Operand->getSourceRange())) 6059 return true; 6060 } 6061 return false; 6062} 6063 6064/// \brief Check the validity of an arithmetic pointer operand. 6065/// 6066/// If the operand has pointer type, this code will check for pointer types 6067/// which are invalid in arithmetic operations. These will be diagnosed 6068/// appropriately, including whether or not the use is supported as an 6069/// extension. 6070/// 6071/// \returns True when the operand is valid to use (even if as an extension). 6072static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6073 Expr *Operand) { 6074 if (!Operand->getType()->isAnyPointerType()) return true; 6075 6076 QualType PointeeTy = Operand->getType()->getPointeeType(); 6077 if (PointeeTy->isVoidType()) { 6078 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6079 return !S.getLangOpts().CPlusPlus; 6080 } 6081 if (PointeeTy->isFunctionType()) { 6082 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6083 return !S.getLangOpts().CPlusPlus; 6084 } 6085 6086 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6087 6088 return true; 6089} 6090 6091/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6092/// operands. 6093/// 6094/// This routine will diagnose any invalid arithmetic on pointer operands much 6095/// like \see checkArithmeticOpPointerOperand. However, it has special logic 6096/// for emitting a single diagnostic even for operations where both LHS and RHS 6097/// are (potentially problematic) pointers. 6098/// 6099/// \returns True when the operand is valid to use (even if as an extension). 6100static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6101 Expr *LHSExpr, Expr *RHSExpr) { 6102 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6103 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6104 if (!isLHSPointer && !isRHSPointer) return true; 6105 6106 QualType LHSPointeeTy, RHSPointeeTy; 6107 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6108 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6109 6110 // Check for arithmetic on pointers to incomplete types. 6111 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6112 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6113 if (isLHSVoidPtr || isRHSVoidPtr) { 6114 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6115 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6116 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6117 6118 return !S.getLangOpts().CPlusPlus; 6119 } 6120 6121 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6122 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6123 if (isLHSFuncPtr || isRHSFuncPtr) { 6124 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6125 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6126 RHSExpr); 6127 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6128 6129 return !S.getLangOpts().CPlusPlus; 6130 } 6131 6132 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false; 6133 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false; 6134 6135 return true; 6136} 6137 6138/// \brief Check bad cases where we step over interface counts. 6139static bool checkArithmethicPointerOnNonFragileABI(Sema &S, 6140 SourceLocation OpLoc, 6141 Expr *Op) { 6142 assert(Op->getType()->isAnyPointerType()); 6143 QualType PointeeTy = Op->getType()->getPointeeType(); 6144 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI) 6145 return true; 6146 6147 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 6148 << PointeeTy << Op->getSourceRange(); 6149 return false; 6150} 6151 6152/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6153/// literal. 6154static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6155 Expr *LHSExpr, Expr *RHSExpr) { 6156 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6157 Expr* IndexExpr = RHSExpr; 6158 if (!StrExpr) { 6159 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6160 IndexExpr = LHSExpr; 6161 } 6162 6163 bool IsStringPlusInt = StrExpr && 6164 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6165 if (!IsStringPlusInt) 6166 return; 6167 6168 llvm::APSInt index; 6169 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6170 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6171 if (index.isNonNegative() && 6172 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6173 index.isUnsigned())) 6174 return; 6175 } 6176 6177 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6178 Self.Diag(OpLoc, diag::warn_string_plus_int) 6179 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6180 6181 // Only print a fixit for "str" + int, not for int + "str". 6182 if (IndexExpr == RHSExpr) { 6183 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6184 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6185 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6186 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6187 << FixItHint::CreateInsertion(EndLoc, "]"); 6188 } else 6189 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6190} 6191 6192/// \brief Emit error when two pointers are incompatible. 6193static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6194 Expr *LHSExpr, Expr *RHSExpr) { 6195 assert(LHSExpr->getType()->isAnyPointerType()); 6196 assert(RHSExpr->getType()->isAnyPointerType()); 6197 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6198 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6199 << RHSExpr->getSourceRange(); 6200} 6201 6202QualType Sema::CheckAdditionOperands( // C99 6.5.6 6203 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6204 QualType* CompLHSTy) { 6205 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6206 6207 if (LHS.get()->getType()->isVectorType() || 6208 RHS.get()->getType()->isVectorType()) { 6209 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6210 if (CompLHSTy) *CompLHSTy = compType; 6211 return compType; 6212 } 6213 6214 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6215 if (LHS.isInvalid() || RHS.isInvalid()) 6216 return QualType(); 6217 6218 // Diagnose "string literal" '+' int. 6219 if (Opc == BO_Add) 6220 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6221 6222 // handle the common case first (both operands are arithmetic). 6223 if (LHS.get()->getType()->isArithmeticType() && 6224 RHS.get()->getType()->isArithmeticType()) { 6225 if (CompLHSTy) *CompLHSTy = compType; 6226 return compType; 6227 } 6228 6229 if (LHS.get()->getType()->isAtomicType() && 6230 RHS.get()->getType()->isArithmeticType()) { 6231 *CompLHSTy = LHS.get()->getType(); 6232 return compType; 6233 } 6234 6235 // Put any potential pointer into PExp 6236 Expr* PExp = LHS.get(), *IExp = RHS.get(); 6237 if (IExp->getType()->isAnyPointerType()) 6238 std::swap(PExp, IExp); 6239 6240 if (!PExp->getType()->isAnyPointerType()) 6241 return InvalidOperands(Loc, LHS, RHS); 6242 6243 if (!IExp->getType()->isIntegerType()) 6244 return InvalidOperands(Loc, LHS, RHS); 6245 6246 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6247 return QualType(); 6248 6249 // Diagnose bad cases where we step over interface counts. 6250 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp)) 6251 return QualType(); 6252 6253 // Check array bounds for pointer arithemtic 6254 CheckArrayAccess(PExp, IExp); 6255 6256 if (CompLHSTy) { 6257 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6258 if (LHSTy.isNull()) { 6259 LHSTy = LHS.get()->getType(); 6260 if (LHSTy->isPromotableIntegerType()) 6261 LHSTy = Context.getPromotedIntegerType(LHSTy); 6262 } 6263 *CompLHSTy = LHSTy; 6264 } 6265 6266 return PExp->getType(); 6267} 6268 6269// C99 6.5.6 6270QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6271 SourceLocation Loc, 6272 QualType* CompLHSTy) { 6273 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6274 6275 if (LHS.get()->getType()->isVectorType() || 6276 RHS.get()->getType()->isVectorType()) { 6277 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6278 if (CompLHSTy) *CompLHSTy = compType; 6279 return compType; 6280 } 6281 6282 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6283 if (LHS.isInvalid() || RHS.isInvalid()) 6284 return QualType(); 6285 6286 // Enforce type constraints: C99 6.5.6p3. 6287 6288 // Handle the common case first (both operands are arithmetic). 6289 if (LHS.get()->getType()->isArithmeticType() && 6290 RHS.get()->getType()->isArithmeticType()) { 6291 if (CompLHSTy) *CompLHSTy = compType; 6292 return compType; 6293 } 6294 6295 if (LHS.get()->getType()->isAtomicType() && 6296 RHS.get()->getType()->isArithmeticType()) { 6297 *CompLHSTy = LHS.get()->getType(); 6298 return compType; 6299 } 6300 6301 // Either ptr - int or ptr - ptr. 6302 if (LHS.get()->getType()->isAnyPointerType()) { 6303 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6304 6305 // Diagnose bad cases where we step over interface counts. 6306 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get())) 6307 return QualType(); 6308 6309 // The result type of a pointer-int computation is the pointer type. 6310 if (RHS.get()->getType()->isIntegerType()) { 6311 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6312 return QualType(); 6313 6314 // Check array bounds for pointer arithemtic 6315 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6316 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6317 6318 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6319 return LHS.get()->getType(); 6320 } 6321 6322 // Handle pointer-pointer subtractions. 6323 if (const PointerType *RHSPTy 6324 = RHS.get()->getType()->getAs<PointerType>()) { 6325 QualType rpointee = RHSPTy->getPointeeType(); 6326 6327 if (getLangOpts().CPlusPlus) { 6328 // Pointee types must be the same: C++ [expr.add] 6329 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6330 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6331 } 6332 } else { 6333 // Pointee types must be compatible C99 6.5.6p3 6334 if (!Context.typesAreCompatible( 6335 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6336 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6337 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6338 return QualType(); 6339 } 6340 } 6341 6342 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6343 LHS.get(), RHS.get())) 6344 return QualType(); 6345 6346 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6347 return Context.getPointerDiffType(); 6348 } 6349 } 6350 6351 return InvalidOperands(Loc, LHS, RHS); 6352} 6353 6354static bool isScopedEnumerationType(QualType T) { 6355 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6356 return ET->getDecl()->isScoped(); 6357 return false; 6358} 6359 6360static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6361 SourceLocation Loc, unsigned Opc, 6362 QualType LHSType) { 6363 llvm::APSInt Right; 6364 // Check right/shifter operand 6365 if (RHS.get()->isValueDependent() || 6366 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6367 return; 6368 6369 if (Right.isNegative()) { 6370 S.DiagRuntimeBehavior(Loc, RHS.get(), 6371 S.PDiag(diag::warn_shift_negative) 6372 << RHS.get()->getSourceRange()); 6373 return; 6374 } 6375 llvm::APInt LeftBits(Right.getBitWidth(), 6376 S.Context.getTypeSize(LHS.get()->getType())); 6377 if (Right.uge(LeftBits)) { 6378 S.DiagRuntimeBehavior(Loc, RHS.get(), 6379 S.PDiag(diag::warn_shift_gt_typewidth) 6380 << RHS.get()->getSourceRange()); 6381 return; 6382 } 6383 if (Opc != BO_Shl) 6384 return; 6385 6386 // When left shifting an ICE which is signed, we can check for overflow which 6387 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6388 // integers have defined behavior modulo one more than the maximum value 6389 // representable in the result type, so never warn for those. 6390 llvm::APSInt Left; 6391 if (LHS.get()->isValueDependent() || 6392 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6393 LHSType->hasUnsignedIntegerRepresentation()) 6394 return; 6395 llvm::APInt ResultBits = 6396 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6397 if (LeftBits.uge(ResultBits)) 6398 return; 6399 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6400 Result = Result.shl(Right); 6401 6402 // Print the bit representation of the signed integer as an unsigned 6403 // hexadecimal number. 6404 SmallString<40> HexResult; 6405 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6406 6407 // If we are only missing a sign bit, this is less likely to result in actual 6408 // bugs -- if the result is cast back to an unsigned type, it will have the 6409 // expected value. Thus we place this behind a different warning that can be 6410 // turned off separately if needed. 6411 if (LeftBits == ResultBits - 1) { 6412 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6413 << HexResult.str() << LHSType 6414 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6415 return; 6416 } 6417 6418 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6419 << HexResult.str() << Result.getMinSignedBits() << LHSType 6420 << Left.getBitWidth() << LHS.get()->getSourceRange() 6421 << RHS.get()->getSourceRange(); 6422} 6423 6424// C99 6.5.7 6425QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6426 SourceLocation Loc, unsigned Opc, 6427 bool IsCompAssign) { 6428 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6429 6430 // C99 6.5.7p2: Each of the operands shall have integer type. 6431 if (!LHS.get()->getType()->hasIntegerRepresentation() || 6432 !RHS.get()->getType()->hasIntegerRepresentation()) 6433 return InvalidOperands(Loc, LHS, RHS); 6434 6435 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6436 // hasIntegerRepresentation() above instead of this. 6437 if (isScopedEnumerationType(LHS.get()->getType()) || 6438 isScopedEnumerationType(RHS.get()->getType())) { 6439 return InvalidOperands(Loc, LHS, RHS); 6440 } 6441 6442 // Vector shifts promote their scalar inputs to vector type. 6443 if (LHS.get()->getType()->isVectorType() || 6444 RHS.get()->getType()->isVectorType()) 6445 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6446 6447 // Shifts don't perform usual arithmetic conversions, they just do integer 6448 // promotions on each operand. C99 6.5.7p3 6449 6450 // For the LHS, do usual unary conversions, but then reset them away 6451 // if this is a compound assignment. 6452 ExprResult OldLHS = LHS; 6453 LHS = UsualUnaryConversions(LHS.take()); 6454 if (LHS.isInvalid()) 6455 return QualType(); 6456 QualType LHSType = LHS.get()->getType(); 6457 if (IsCompAssign) LHS = OldLHS; 6458 6459 // The RHS is simpler. 6460 RHS = UsualUnaryConversions(RHS.take()); 6461 if (RHS.isInvalid()) 6462 return QualType(); 6463 6464 // Sanity-check shift operands 6465 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6466 6467 // "The type of the result is that of the promoted left operand." 6468 return LHSType; 6469} 6470 6471static bool IsWithinTemplateSpecialization(Decl *D) { 6472 if (DeclContext *DC = D->getDeclContext()) { 6473 if (isa<ClassTemplateSpecializationDecl>(DC)) 6474 return true; 6475 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6476 return FD->isFunctionTemplateSpecialization(); 6477 } 6478 return false; 6479} 6480 6481/// If two different enums are compared, raise a warning. 6482static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, 6483 ExprResult &RHS) { 6484 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType(); 6485 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType(); 6486 6487 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6488 if (!LHSEnumType) 6489 return; 6490 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6491 if (!RHSEnumType) 6492 return; 6493 6494 // Ignore anonymous enums. 6495 if (!LHSEnumType->getDecl()->getIdentifier()) 6496 return; 6497 if (!RHSEnumType->getDecl()->getIdentifier()) 6498 return; 6499 6500 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 6501 return; 6502 6503 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6504 << LHSStrippedType << RHSStrippedType 6505 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6506} 6507 6508/// \brief Diagnose bad pointer comparisons. 6509static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 6510 ExprResult &LHS, ExprResult &RHS, 6511 bool IsError) { 6512 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 6513 : diag::ext_typecheck_comparison_of_distinct_pointers) 6514 << LHS.get()->getType() << RHS.get()->getType() 6515 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6516} 6517 6518/// \brief Returns false if the pointers are converted to a composite type, 6519/// true otherwise. 6520static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 6521 ExprResult &LHS, ExprResult &RHS) { 6522 // C++ [expr.rel]p2: 6523 // [...] Pointer conversions (4.10) and qualification 6524 // conversions (4.4) are performed on pointer operands (or on 6525 // a pointer operand and a null pointer constant) to bring 6526 // them to their composite pointer type. [...] 6527 // 6528 // C++ [expr.eq]p1 uses the same notion for (in)equality 6529 // comparisons of pointers. 6530 6531 // C++ [expr.eq]p2: 6532 // In addition, pointers to members can be compared, or a pointer to 6533 // member and a null pointer constant. Pointer to member conversions 6534 // (4.11) and qualification conversions (4.4) are performed to bring 6535 // them to a common type. If one operand is a null pointer constant, 6536 // the common type is the type of the other operand. Otherwise, the 6537 // common type is a pointer to member type similar (4.4) to the type 6538 // of one of the operands, with a cv-qualification signature (4.4) 6539 // that is the union of the cv-qualification signatures of the operand 6540 // types. 6541 6542 QualType LHSType = LHS.get()->getType(); 6543 QualType RHSType = RHS.get()->getType(); 6544 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 6545 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 6546 6547 bool NonStandardCompositeType = false; 6548 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 6549 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 6550 if (T.isNull()) { 6551 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 6552 return true; 6553 } 6554 6555 if (NonStandardCompositeType) 6556 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 6557 << LHSType << RHSType << T << LHS.get()->getSourceRange() 6558 << RHS.get()->getSourceRange(); 6559 6560 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 6561 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 6562 return false; 6563} 6564 6565static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 6566 ExprResult &LHS, 6567 ExprResult &RHS, 6568 bool IsError) { 6569 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 6570 : diag::ext_typecheck_comparison_of_fptr_to_void) 6571 << LHS.get()->getType() << RHS.get()->getType() 6572 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6573} 6574 6575// C99 6.5.8, C++ [expr.rel] 6576QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 6577 SourceLocation Loc, unsigned OpaqueOpc, 6578 bool IsRelational) { 6579 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 6580 6581 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 6582 6583 // Handle vector comparisons separately. 6584 if (LHS.get()->getType()->isVectorType() || 6585 RHS.get()->getType()->isVectorType()) 6586 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 6587 6588 QualType LHSType = LHS.get()->getType(); 6589 QualType RHSType = RHS.get()->getType(); 6590 6591 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 6592 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 6593 6594 checkEnumComparison(*this, Loc, LHS, RHS); 6595 6596 if (!LHSType->hasFloatingRepresentation() && 6597 !(LHSType->isBlockPointerType() && IsRelational) && 6598 !LHS.get()->getLocStart().isMacroID() && 6599 !RHS.get()->getLocStart().isMacroID()) { 6600 // For non-floating point types, check for self-comparisons of the form 6601 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6602 // often indicate logic errors in the program. 6603 // 6604 // NOTE: Don't warn about comparison expressions resulting from macro 6605 // expansion. Also don't warn about comparisons which are only self 6606 // comparisons within a template specialization. The warnings should catch 6607 // obvious cases in the definition of the template anyways. The idea is to 6608 // warn when the typed comparison operator will always evaluate to the same 6609 // result. 6610 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 6611 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 6612 if (DRL->getDecl() == DRR->getDecl() && 6613 !IsWithinTemplateSpecialization(DRL->getDecl())) { 6614 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6615 << 0 // self- 6616 << (Opc == BO_EQ 6617 || Opc == BO_LE 6618 || Opc == BO_GE)); 6619 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 6620 !DRL->getDecl()->getType()->isReferenceType() && 6621 !DRR->getDecl()->getType()->isReferenceType()) { 6622 // what is it always going to eval to? 6623 char always_evals_to; 6624 switch(Opc) { 6625 case BO_EQ: // e.g. array1 == array2 6626 always_evals_to = 0; // false 6627 break; 6628 case BO_NE: // e.g. array1 != array2 6629 always_evals_to = 1; // true 6630 break; 6631 default: 6632 // best we can say is 'a constant' 6633 always_evals_to = 2; // e.g. array1 <= array2 6634 break; 6635 } 6636 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6637 << 1 // array 6638 << always_evals_to); 6639 } 6640 } 6641 } 6642 6643 if (isa<CastExpr>(LHSStripped)) 6644 LHSStripped = LHSStripped->IgnoreParenCasts(); 6645 if (isa<CastExpr>(RHSStripped)) 6646 RHSStripped = RHSStripped->IgnoreParenCasts(); 6647 6648 // Warn about comparisons against a string constant (unless the other 6649 // operand is null), the user probably wants strcmp. 6650 Expr *literalString = 0; 6651 Expr *literalStringStripped = 0; 6652 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 6653 !RHSStripped->isNullPointerConstant(Context, 6654 Expr::NPC_ValueDependentIsNull)) { 6655 literalString = LHS.get(); 6656 literalStringStripped = LHSStripped; 6657 } else if ((isa<StringLiteral>(RHSStripped) || 6658 isa<ObjCEncodeExpr>(RHSStripped)) && 6659 !LHSStripped->isNullPointerConstant(Context, 6660 Expr::NPC_ValueDependentIsNull)) { 6661 literalString = RHS.get(); 6662 literalStringStripped = RHSStripped; 6663 } 6664 6665 if (literalString) { 6666 std::string resultComparison; 6667 switch (Opc) { 6668 case BO_LT: resultComparison = ") < 0"; break; 6669 case BO_GT: resultComparison = ") > 0"; break; 6670 case BO_LE: resultComparison = ") <= 0"; break; 6671 case BO_GE: resultComparison = ") >= 0"; break; 6672 case BO_EQ: resultComparison = ") == 0"; break; 6673 case BO_NE: resultComparison = ") != 0"; break; 6674 default: llvm_unreachable("Invalid comparison operator"); 6675 } 6676 6677 DiagRuntimeBehavior(Loc, 0, 6678 PDiag(diag::warn_stringcompare) 6679 << isa<ObjCEncodeExpr>(literalStringStripped) 6680 << literalString->getSourceRange()); 6681 } 6682 } 6683 6684 // C99 6.5.8p3 / C99 6.5.9p4 6685 if (LHS.get()->getType()->isArithmeticType() && 6686 RHS.get()->getType()->isArithmeticType()) { 6687 UsualArithmeticConversions(LHS, RHS); 6688 if (LHS.isInvalid() || RHS.isInvalid()) 6689 return QualType(); 6690 } 6691 else { 6692 LHS = UsualUnaryConversions(LHS.take()); 6693 if (LHS.isInvalid()) 6694 return QualType(); 6695 6696 RHS = UsualUnaryConversions(RHS.take()); 6697 if (RHS.isInvalid()) 6698 return QualType(); 6699 } 6700 6701 LHSType = LHS.get()->getType(); 6702 RHSType = RHS.get()->getType(); 6703 6704 // The result of comparisons is 'bool' in C++, 'int' in C. 6705 QualType ResultTy = Context.getLogicalOperationType(); 6706 6707 if (IsRelational) { 6708 if (LHSType->isRealType() && RHSType->isRealType()) 6709 return ResultTy; 6710 } else { 6711 // Check for comparisons of floating point operands using != and ==. 6712 if (LHSType->hasFloatingRepresentation()) 6713 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 6714 6715 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 6716 return ResultTy; 6717 } 6718 6719 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 6720 Expr::NPC_ValueDependentIsNull); 6721 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 6722 Expr::NPC_ValueDependentIsNull); 6723 6724 // All of the following pointer-related warnings are GCC extensions, except 6725 // when handling null pointer constants. 6726 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 6727 QualType LCanPointeeTy = 6728 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 6729 QualType RCanPointeeTy = 6730 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 6731 6732 if (getLangOpts().CPlusPlus) { 6733 if (LCanPointeeTy == RCanPointeeTy) 6734 return ResultTy; 6735 if (!IsRelational && 6736 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6737 // Valid unless comparison between non-null pointer and function pointer 6738 // This is a gcc extension compatibility comparison. 6739 // In a SFINAE context, we treat this as a hard error to maintain 6740 // conformance with the C++ standard. 6741 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6742 && !LHSIsNull && !RHSIsNull) { 6743 diagnoseFunctionPointerToVoidComparison( 6744 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext()); 6745 6746 if (isSFINAEContext()) 6747 return QualType(); 6748 6749 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6750 return ResultTy; 6751 } 6752 } 6753 6754 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 6755 return QualType(); 6756 else 6757 return ResultTy; 6758 } 6759 // C99 6.5.9p2 and C99 6.5.8p2 6760 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 6761 RCanPointeeTy.getUnqualifiedType())) { 6762 // Valid unless a relational comparison of function pointers 6763 if (IsRelational && LCanPointeeTy->isFunctionType()) { 6764 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 6765 << LHSType << RHSType << LHS.get()->getSourceRange() 6766 << RHS.get()->getSourceRange(); 6767 } 6768 } else if (!IsRelational && 6769 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6770 // Valid unless comparison between non-null pointer and function pointer 6771 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6772 && !LHSIsNull && !RHSIsNull) 6773 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 6774 /*isError*/false); 6775 } else { 6776 // Invalid 6777 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 6778 } 6779 if (LCanPointeeTy != RCanPointeeTy) { 6780 if (LHSIsNull && !RHSIsNull) 6781 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6782 else 6783 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6784 } 6785 return ResultTy; 6786 } 6787 6788 if (getLangOpts().CPlusPlus) { 6789 // Comparison of nullptr_t with itself. 6790 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 6791 return ResultTy; 6792 6793 // Comparison of pointers with null pointer constants and equality 6794 // comparisons of member pointers to null pointer constants. 6795 if (RHSIsNull && 6796 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 6797 (!IsRelational && 6798 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 6799 RHS = ImpCastExprToType(RHS.take(), LHSType, 6800 LHSType->isMemberPointerType() 6801 ? CK_NullToMemberPointer 6802 : CK_NullToPointer); 6803 return ResultTy; 6804 } 6805 if (LHSIsNull && 6806 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 6807 (!IsRelational && 6808 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 6809 LHS = ImpCastExprToType(LHS.take(), RHSType, 6810 RHSType->isMemberPointerType() 6811 ? CK_NullToMemberPointer 6812 : CK_NullToPointer); 6813 return ResultTy; 6814 } 6815 6816 // Comparison of member pointers. 6817 if (!IsRelational && 6818 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 6819 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 6820 return QualType(); 6821 else 6822 return ResultTy; 6823 } 6824 6825 // Handle scoped enumeration types specifically, since they don't promote 6826 // to integers. 6827 if (LHS.get()->getType()->isEnumeralType() && 6828 Context.hasSameUnqualifiedType(LHS.get()->getType(), 6829 RHS.get()->getType())) 6830 return ResultTy; 6831 } 6832 6833 // Handle block pointer types. 6834 if (!IsRelational && LHSType->isBlockPointerType() && 6835 RHSType->isBlockPointerType()) { 6836 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 6837 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 6838 6839 if (!LHSIsNull && !RHSIsNull && 6840 !Context.typesAreCompatible(lpointee, rpointee)) { 6841 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 6842 << LHSType << RHSType << LHS.get()->getSourceRange() 6843 << RHS.get()->getSourceRange(); 6844 } 6845 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6846 return ResultTy; 6847 } 6848 6849 // Allow block pointers to be compared with null pointer constants. 6850 if (!IsRelational 6851 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 6852 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 6853 if (!LHSIsNull && !RHSIsNull) { 6854 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 6855 ->getPointeeType()->isVoidType()) 6856 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 6857 ->getPointeeType()->isVoidType()))) 6858 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 6859 << LHSType << RHSType << LHS.get()->getSourceRange() 6860 << RHS.get()->getSourceRange(); 6861 } 6862 if (LHSIsNull && !RHSIsNull) 6863 LHS = ImpCastExprToType(LHS.take(), RHSType, 6864 RHSType->isPointerType() ? CK_BitCast 6865 : CK_AnyPointerToBlockPointerCast); 6866 else 6867 RHS = ImpCastExprToType(RHS.take(), LHSType, 6868 LHSType->isPointerType() ? CK_BitCast 6869 : CK_AnyPointerToBlockPointerCast); 6870 return ResultTy; 6871 } 6872 6873 if (LHSType->isObjCObjectPointerType() || 6874 RHSType->isObjCObjectPointerType()) { 6875 const PointerType *LPT = LHSType->getAs<PointerType>(); 6876 const PointerType *RPT = RHSType->getAs<PointerType>(); 6877 if (LPT || RPT) { 6878 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 6879 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 6880 6881 if (!LPtrToVoid && !RPtrToVoid && 6882 !Context.typesAreCompatible(LHSType, RHSType)) { 6883 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 6884 /*isError*/false); 6885 } 6886 if (LHSIsNull && !RHSIsNull) 6887 LHS = ImpCastExprToType(LHS.take(), RHSType, 6888 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 6889 else 6890 RHS = ImpCastExprToType(RHS.take(), LHSType, 6891 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 6892 return ResultTy; 6893 } 6894 if (LHSType->isObjCObjectPointerType() && 6895 RHSType->isObjCObjectPointerType()) { 6896 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 6897 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 6898 /*isError*/false); 6899 if (LHSIsNull && !RHSIsNull) 6900 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6901 else 6902 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6903 return ResultTy; 6904 } 6905 } 6906 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 6907 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 6908 unsigned DiagID = 0; 6909 bool isError = false; 6910 if ((LHSIsNull && LHSType->isIntegerType()) || 6911 (RHSIsNull && RHSType->isIntegerType())) { 6912 if (IsRelational && !getLangOpts().CPlusPlus) 6913 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 6914 } else if (IsRelational && !getLangOpts().CPlusPlus) 6915 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 6916 else if (getLangOpts().CPlusPlus) { 6917 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 6918 isError = true; 6919 } else 6920 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 6921 6922 if (DiagID) { 6923 Diag(Loc, DiagID) 6924 << LHSType << RHSType << LHS.get()->getSourceRange() 6925 << RHS.get()->getSourceRange(); 6926 if (isError) 6927 return QualType(); 6928 } 6929 6930 if (LHSType->isIntegerType()) 6931 LHS = ImpCastExprToType(LHS.take(), RHSType, 6932 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 6933 else 6934 RHS = ImpCastExprToType(RHS.take(), LHSType, 6935 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 6936 return ResultTy; 6937 } 6938 6939 // Handle block pointers. 6940 if (!IsRelational && RHSIsNull 6941 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 6942 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6943 return ResultTy; 6944 } 6945 if (!IsRelational && LHSIsNull 6946 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 6947 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 6948 return ResultTy; 6949 } 6950 6951 return InvalidOperands(Loc, LHS, RHS); 6952} 6953 6954 6955// Return a signed type that is of identical size and number of elements. 6956// For floating point vectors, return an integer type of identical size 6957// and number of elements. 6958QualType Sema::GetSignedVectorType(QualType V) { 6959 const VectorType *VTy = V->getAs<VectorType>(); 6960 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 6961 if (TypeSize == Context.getTypeSize(Context.CharTy)) 6962 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 6963 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 6964 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 6965 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 6966 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 6967 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 6968 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 6969 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 6970 "Unhandled vector element size in vector compare"); 6971 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 6972} 6973 6974/// CheckVectorCompareOperands - vector comparisons are a clang extension that 6975/// operates on extended vector types. Instead of producing an IntTy result, 6976/// like a scalar comparison, a vector comparison produces a vector of integer 6977/// types. 6978QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 6979 SourceLocation Loc, 6980 bool IsRelational) { 6981 // Check to make sure we're operating on vectors of the same type and width, 6982 // Allowing one side to be a scalar of element type. 6983 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 6984 if (vType.isNull()) 6985 return vType; 6986 6987 QualType LHSType = LHS.get()->getType(); 6988 6989 // If AltiVec, the comparison results in a numeric type, i.e. 6990 // bool for C++, int for C 6991 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 6992 return Context.getLogicalOperationType(); 6993 6994 // For non-floating point types, check for self-comparisons of the form 6995 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6996 // often indicate logic errors in the program. 6997 if (!LHSType->hasFloatingRepresentation()) { 6998 if (DeclRefExpr* DRL 6999 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7000 if (DeclRefExpr* DRR 7001 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7002 if (DRL->getDecl() == DRR->getDecl()) 7003 DiagRuntimeBehavior(Loc, 0, 7004 PDiag(diag::warn_comparison_always) 7005 << 0 // self- 7006 << 2 // "a constant" 7007 ); 7008 } 7009 7010 // Check for comparisons of floating point operands using != and ==. 7011 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7012 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7013 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7014 } 7015 7016 // Return a signed type for the vector. 7017 return GetSignedVectorType(LHSType); 7018} 7019 7020QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7021 SourceLocation Loc) { 7022 // Ensure that either both operands are of the same vector type, or 7023 // one operand is of a vector type and the other is of its element type. 7024 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7025 if (vType.isNull() || vType->isFloatingType()) 7026 return InvalidOperands(Loc, LHS, RHS); 7027 7028 return GetSignedVectorType(LHS.get()->getType()); 7029} 7030 7031inline QualType Sema::CheckBitwiseOperands( 7032 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7033 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7034 7035 if (LHS.get()->getType()->isVectorType() || 7036 RHS.get()->getType()->isVectorType()) { 7037 if (LHS.get()->getType()->hasIntegerRepresentation() && 7038 RHS.get()->getType()->hasIntegerRepresentation()) 7039 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7040 7041 return InvalidOperands(Loc, LHS, RHS); 7042 } 7043 7044 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7045 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7046 IsCompAssign); 7047 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7048 return QualType(); 7049 LHS = LHSResult.take(); 7050 RHS = RHSResult.take(); 7051 7052 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() && 7053 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType()) 7054 return compType; 7055 return InvalidOperands(Loc, LHS, RHS); 7056} 7057 7058inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7059 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7060 7061 // Check vector operands differently. 7062 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7063 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7064 7065 // Diagnose cases where the user write a logical and/or but probably meant a 7066 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7067 // is a constant. 7068 if (LHS.get()->getType()->isIntegerType() && 7069 !LHS.get()->getType()->isBooleanType() && 7070 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7071 // Don't warn in macros or template instantiations. 7072 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7073 // If the RHS can be constant folded, and if it constant folds to something 7074 // that isn't 0 or 1 (which indicate a potential logical operation that 7075 // happened to fold to true/false) then warn. 7076 // Parens on the RHS are ignored. 7077 llvm::APSInt Result; 7078 if (RHS.get()->EvaluateAsInt(Result, Context)) 7079 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7080 (Result != 0 && Result != 1)) { 7081 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7082 << RHS.get()->getSourceRange() 7083 << (Opc == BO_LAnd ? "&&" : "||"); 7084 // Suggest replacing the logical operator with the bitwise version 7085 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 7086 << (Opc == BO_LAnd ? "&" : "|") 7087 << FixItHint::CreateReplacement(SourceRange( 7088 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 7089 getLangOpts())), 7090 Opc == BO_LAnd ? "&" : "|"); 7091 if (Opc == BO_LAnd) 7092 // Suggest replacing "Foo() && kNonZero" with "Foo()" 7093 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 7094 << FixItHint::CreateRemoval( 7095 SourceRange( 7096 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 7097 0, getSourceManager(), 7098 getLangOpts()), 7099 RHS.get()->getLocEnd())); 7100 } 7101 } 7102 7103 if (!Context.getLangOpts().CPlusPlus) { 7104 LHS = UsualUnaryConversions(LHS.take()); 7105 if (LHS.isInvalid()) 7106 return QualType(); 7107 7108 RHS = UsualUnaryConversions(RHS.take()); 7109 if (RHS.isInvalid()) 7110 return QualType(); 7111 7112 if (!LHS.get()->getType()->isScalarType() || 7113 !RHS.get()->getType()->isScalarType()) 7114 return InvalidOperands(Loc, LHS, RHS); 7115 7116 return Context.IntTy; 7117 } 7118 7119 // The following is safe because we only use this method for 7120 // non-overloadable operands. 7121 7122 // C++ [expr.log.and]p1 7123 // C++ [expr.log.or]p1 7124 // The operands are both contextually converted to type bool. 7125 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 7126 if (LHSRes.isInvalid()) 7127 return InvalidOperands(Loc, LHS, RHS); 7128 LHS = move(LHSRes); 7129 7130 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 7131 if (RHSRes.isInvalid()) 7132 return InvalidOperands(Loc, LHS, RHS); 7133 RHS = move(RHSRes); 7134 7135 // C++ [expr.log.and]p2 7136 // C++ [expr.log.or]p2 7137 // The result is a bool. 7138 return Context.BoolTy; 7139} 7140 7141/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 7142/// is a read-only property; return true if so. A readonly property expression 7143/// depends on various declarations and thus must be treated specially. 7144/// 7145static bool IsReadonlyProperty(Expr *E, Sema &S) { 7146 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 7147 if (!PropExpr) return false; 7148 if (PropExpr->isImplicitProperty()) return false; 7149 7150 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7151 QualType BaseType = PropExpr->isSuperReceiver() ? 7152 PropExpr->getSuperReceiverType() : 7153 PropExpr->getBase()->getType(); 7154 7155 if (const ObjCObjectPointerType *OPT = 7156 BaseType->getAsObjCInterfacePointerType()) 7157 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 7158 if (S.isPropertyReadonly(PDecl, IFace)) 7159 return true; 7160 return false; 7161} 7162 7163static bool IsReadonlyMessage(Expr *E, Sema &S) { 7164 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7165 if (!ME) return false; 7166 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7167 ObjCMessageExpr *Base = 7168 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7169 if (!Base) return false; 7170 return Base->getMethodDecl() != 0; 7171} 7172 7173/// Is the given expression (which must be 'const') a reference to a 7174/// variable which was originally non-const, but which has become 7175/// 'const' due to being captured within a block? 7176enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 7177static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 7178 assert(E->isLValue() && E->getType().isConstQualified()); 7179 E = E->IgnoreParens(); 7180 7181 // Must be a reference to a declaration from an enclosing scope. 7182 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 7183 if (!DRE) return NCCK_None; 7184 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 7185 7186 // The declaration must be a variable which is not declared 'const'. 7187 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 7188 if (!var) return NCCK_None; 7189 if (var->getType().isConstQualified()) return NCCK_None; 7190 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 7191 7192 // Decide whether the first capture was for a block or a lambda. 7193 DeclContext *DC = S.CurContext; 7194 while (DC->getParent() != var->getDeclContext()) 7195 DC = DC->getParent(); 7196 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 7197} 7198 7199/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7200/// emit an error and return true. If so, return false. 7201static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7202 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 7203 SourceLocation OrigLoc = Loc; 7204 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7205 &Loc); 7206 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7207 IsLV = Expr::MLV_ReadonlyProperty; 7208 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7209 IsLV = Expr::MLV_InvalidMessageExpression; 7210 if (IsLV == Expr::MLV_Valid) 7211 return false; 7212 7213 unsigned Diag = 0; 7214 bool NeedType = false; 7215 switch (IsLV) { // C99 6.5.16p2 7216 case Expr::MLV_ConstQualified: 7217 Diag = diag::err_typecheck_assign_const; 7218 7219 // Use a specialized diagnostic when we're assigning to an object 7220 // from an enclosing function or block. 7221 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 7222 if (NCCK == NCCK_Block) 7223 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7224 else 7225 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 7226 break; 7227 } 7228 7229 // In ARC, use some specialized diagnostics for occasions where we 7230 // infer 'const'. These are always pseudo-strong variables. 7231 if (S.getLangOpts().ObjCAutoRefCount) { 7232 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7233 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7234 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7235 7236 // Use the normal diagnostic if it's pseudo-__strong but the 7237 // user actually wrote 'const'. 7238 if (var->isARCPseudoStrong() && 7239 (!var->getTypeSourceInfo() || 7240 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7241 // There are two pseudo-strong cases: 7242 // - self 7243 ObjCMethodDecl *method = S.getCurMethodDecl(); 7244 if (method && var == method->getSelfDecl()) 7245 Diag = method->isClassMethod() 7246 ? diag::err_typecheck_arc_assign_self_class_method 7247 : diag::err_typecheck_arc_assign_self; 7248 7249 // - fast enumeration variables 7250 else 7251 Diag = diag::err_typecheck_arr_assign_enumeration; 7252 7253 SourceRange Assign; 7254 if (Loc != OrigLoc) 7255 Assign = SourceRange(OrigLoc, OrigLoc); 7256 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7257 // We need to preserve the AST regardless, so migration tool 7258 // can do its job. 7259 return false; 7260 } 7261 } 7262 } 7263 7264 break; 7265 case Expr::MLV_ArrayType: 7266 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7267 NeedType = true; 7268 break; 7269 case Expr::MLV_NotObjectType: 7270 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7271 NeedType = true; 7272 break; 7273 case Expr::MLV_LValueCast: 7274 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7275 break; 7276 case Expr::MLV_Valid: 7277 llvm_unreachable("did not take early return for MLV_Valid"); 7278 case Expr::MLV_InvalidExpression: 7279 case Expr::MLV_MemberFunction: 7280 case Expr::MLV_ClassTemporary: 7281 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7282 break; 7283 case Expr::MLV_IncompleteType: 7284 case Expr::MLV_IncompleteVoidType: 7285 return S.RequireCompleteType(Loc, E->getType(), 7286 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 7287 case Expr::MLV_DuplicateVectorComponents: 7288 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7289 break; 7290 case Expr::MLV_ReadonlyProperty: 7291 case Expr::MLV_NoSetterProperty: 7292 llvm_unreachable("readonly properties should be processed differently"); 7293 case Expr::MLV_InvalidMessageExpression: 7294 Diag = diag::error_readonly_message_assignment; 7295 break; 7296 case Expr::MLV_SubObjCPropertySetting: 7297 Diag = diag::error_no_subobject_property_setting; 7298 break; 7299 } 7300 7301 SourceRange Assign; 7302 if (Loc != OrigLoc) 7303 Assign = SourceRange(OrigLoc, OrigLoc); 7304 if (NeedType) 7305 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7306 else 7307 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7308 return true; 7309} 7310 7311 7312 7313// C99 6.5.16.1 7314QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 7315 SourceLocation Loc, 7316 QualType CompoundType) { 7317 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 7318 7319 // Verify that LHS is a modifiable lvalue, and emit error if not. 7320 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 7321 return QualType(); 7322 7323 QualType LHSType = LHSExpr->getType(); 7324 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 7325 CompoundType; 7326 AssignConvertType ConvTy; 7327 if (CompoundType.isNull()) { 7328 QualType LHSTy(LHSType); 7329 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7330 if (RHS.isInvalid()) 7331 return QualType(); 7332 // Special case of NSObject attributes on c-style pointer types. 7333 if (ConvTy == IncompatiblePointer && 7334 ((Context.isObjCNSObjectType(LHSType) && 7335 RHSType->isObjCObjectPointerType()) || 7336 (Context.isObjCNSObjectType(RHSType) && 7337 LHSType->isObjCObjectPointerType()))) 7338 ConvTy = Compatible; 7339 7340 if (ConvTy == Compatible && 7341 LHSType->isObjCObjectType()) 7342 Diag(Loc, diag::err_objc_object_assignment) 7343 << LHSType; 7344 7345 // If the RHS is a unary plus or minus, check to see if they = and + are 7346 // right next to each other. If so, the user may have typo'd "x =+ 4" 7347 // instead of "x += 4". 7348 Expr *RHSCheck = RHS.get(); 7349 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7350 RHSCheck = ICE->getSubExpr(); 7351 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 7352 if ((UO->getOpcode() == UO_Plus || 7353 UO->getOpcode() == UO_Minus) && 7354 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 7355 // Only if the two operators are exactly adjacent. 7356 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 7357 // And there is a space or other character before the subexpr of the 7358 // unary +/-. We don't want to warn on "x=-1". 7359 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 7360 UO->getSubExpr()->getLocStart().isFileID()) { 7361 Diag(Loc, diag::warn_not_compound_assign) 7362 << (UO->getOpcode() == UO_Plus ? "+" : "-") 7363 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 7364 } 7365 } 7366 7367 if (ConvTy == Compatible) { 7368 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) 7369 checkRetainCycles(LHSExpr, RHS.get()); 7370 else if (getLangOpts().ObjCAutoRefCount) 7371 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 7372 } 7373 } else { 7374 // Compound assignment "x += y" 7375 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 7376 } 7377 7378 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 7379 RHS.get(), AA_Assigning)) 7380 return QualType(); 7381 7382 CheckForNullPointerDereference(*this, LHSExpr); 7383 7384 // C99 6.5.16p3: The type of an assignment expression is the type of the 7385 // left operand unless the left operand has qualified type, in which case 7386 // it is the unqualified version of the type of the left operand. 7387 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 7388 // is converted to the type of the assignment expression (above). 7389 // C++ 5.17p1: the type of the assignment expression is that of its left 7390 // operand. 7391 return (getLangOpts().CPlusPlus 7392 ? LHSType : LHSType.getUnqualifiedType()); 7393} 7394 7395// C99 6.5.17 7396static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 7397 SourceLocation Loc) { 7398 S.DiagnoseUnusedExprResult(LHS.get()); 7399 7400 LHS = S.CheckPlaceholderExpr(LHS.take()); 7401 RHS = S.CheckPlaceholderExpr(RHS.take()); 7402 if (LHS.isInvalid() || RHS.isInvalid()) 7403 return QualType(); 7404 7405 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 7406 // operands, but not unary promotions. 7407 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 7408 7409 // So we treat the LHS as a ignored value, and in C++ we allow the 7410 // containing site to determine what should be done with the RHS. 7411 LHS = S.IgnoredValueConversions(LHS.take()); 7412 if (LHS.isInvalid()) 7413 return QualType(); 7414 7415 if (!S.getLangOpts().CPlusPlus) { 7416 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 7417 if (RHS.isInvalid()) 7418 return QualType(); 7419 if (!RHS.get()->getType()->isVoidType()) 7420 S.RequireCompleteType(Loc, RHS.get()->getType(), 7421 diag::err_incomplete_type); 7422 } 7423 7424 return RHS.get()->getType(); 7425} 7426 7427/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 7428/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 7429static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 7430 ExprValueKind &VK, 7431 SourceLocation OpLoc, 7432 bool IsInc, bool IsPrefix) { 7433 if (Op->isTypeDependent()) 7434 return S.Context.DependentTy; 7435 7436 QualType ResType = Op->getType(); 7437 // Atomic types can be used for increment / decrement where the non-atomic 7438 // versions can, so ignore the _Atomic() specifier for the purpose of 7439 // checking. 7440 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7441 ResType = ResAtomicType->getValueType(); 7442 7443 assert(!ResType.isNull() && "no type for increment/decrement expression"); 7444 7445 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 7446 // Decrement of bool is not allowed. 7447 if (!IsInc) { 7448 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 7449 return QualType(); 7450 } 7451 // Increment of bool sets it to true, but is deprecated. 7452 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 7453 } else if (ResType->isRealType()) { 7454 // OK! 7455 } else if (ResType->isAnyPointerType()) { 7456 // C99 6.5.2.4p2, 6.5.6p2 7457 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 7458 return QualType(); 7459 7460 // Diagnose bad cases where we step over interface counts. 7461 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op)) 7462 return QualType(); 7463 } else if (ResType->isAnyComplexType()) { 7464 // C99 does not support ++/-- on complex types, we allow as an extension. 7465 S.Diag(OpLoc, diag::ext_integer_increment_complex) 7466 << ResType << Op->getSourceRange(); 7467 } else if (ResType->isPlaceholderType()) { 7468 ExprResult PR = S.CheckPlaceholderExpr(Op); 7469 if (PR.isInvalid()) return QualType(); 7470 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 7471 IsInc, IsPrefix); 7472 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 7473 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 7474 } else { 7475 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 7476 << ResType << int(IsInc) << Op->getSourceRange(); 7477 return QualType(); 7478 } 7479 // At this point, we know we have a real, complex or pointer type. 7480 // Now make sure the operand is a modifiable lvalue. 7481 if (CheckForModifiableLvalue(Op, OpLoc, S)) 7482 return QualType(); 7483 // In C++, a prefix increment is the same type as the operand. Otherwise 7484 // (in C or with postfix), the increment is the unqualified type of the 7485 // operand. 7486 if (IsPrefix && S.getLangOpts().CPlusPlus) { 7487 VK = VK_LValue; 7488 return ResType; 7489 } else { 7490 VK = VK_RValue; 7491 return ResType.getUnqualifiedType(); 7492 } 7493} 7494 7495 7496/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 7497/// This routine allows us to typecheck complex/recursive expressions 7498/// where the declaration is needed for type checking. We only need to 7499/// handle cases when the expression references a function designator 7500/// or is an lvalue. Here are some examples: 7501/// - &(x) => x 7502/// - &*****f => f for f a function designator. 7503/// - &s.xx => s 7504/// - &s.zz[1].yy -> s, if zz is an array 7505/// - *(x + 1) -> x, if x is an array 7506/// - &"123"[2] -> 0 7507/// - & __real__ x -> x 7508static ValueDecl *getPrimaryDecl(Expr *E) { 7509 switch (E->getStmtClass()) { 7510 case Stmt::DeclRefExprClass: 7511 return cast<DeclRefExpr>(E)->getDecl(); 7512 case Stmt::MemberExprClass: 7513 // If this is an arrow operator, the address is an offset from 7514 // the base's value, so the object the base refers to is 7515 // irrelevant. 7516 if (cast<MemberExpr>(E)->isArrow()) 7517 return 0; 7518 // Otherwise, the expression refers to a part of the base 7519 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 7520 case Stmt::ArraySubscriptExprClass: { 7521 // FIXME: This code shouldn't be necessary! We should catch the implicit 7522 // promotion of register arrays earlier. 7523 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 7524 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 7525 if (ICE->getSubExpr()->getType()->isArrayType()) 7526 return getPrimaryDecl(ICE->getSubExpr()); 7527 } 7528 return 0; 7529 } 7530 case Stmt::UnaryOperatorClass: { 7531 UnaryOperator *UO = cast<UnaryOperator>(E); 7532 7533 switch(UO->getOpcode()) { 7534 case UO_Real: 7535 case UO_Imag: 7536 case UO_Extension: 7537 return getPrimaryDecl(UO->getSubExpr()); 7538 default: 7539 return 0; 7540 } 7541 } 7542 case Stmt::ParenExprClass: 7543 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 7544 case Stmt::ImplicitCastExprClass: 7545 // If the result of an implicit cast is an l-value, we care about 7546 // the sub-expression; otherwise, the result here doesn't matter. 7547 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 7548 default: 7549 return 0; 7550 } 7551} 7552 7553namespace { 7554 enum { 7555 AO_Bit_Field = 0, 7556 AO_Vector_Element = 1, 7557 AO_Property_Expansion = 2, 7558 AO_Register_Variable = 3, 7559 AO_No_Error = 4 7560 }; 7561} 7562/// \brief Diagnose invalid operand for address of operations. 7563/// 7564/// \param Type The type of operand which cannot have its address taken. 7565static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 7566 Expr *E, unsigned Type) { 7567 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 7568} 7569 7570/// CheckAddressOfOperand - The operand of & must be either a function 7571/// designator or an lvalue designating an object. If it is an lvalue, the 7572/// object cannot be declared with storage class register or be a bit field. 7573/// Note: The usual conversions are *not* applied to the operand of the & 7574/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 7575/// In C++, the operand might be an overloaded function name, in which case 7576/// we allow the '&' but retain the overloaded-function type. 7577static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 7578 SourceLocation OpLoc) { 7579 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 7580 if (PTy->getKind() == BuiltinType::Overload) { 7581 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 7582 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7583 << OrigOp.get()->getSourceRange(); 7584 return QualType(); 7585 } 7586 7587 return S.Context.OverloadTy; 7588 } 7589 7590 if (PTy->getKind() == BuiltinType::UnknownAny) 7591 return S.Context.UnknownAnyTy; 7592 7593 if (PTy->getKind() == BuiltinType::BoundMember) { 7594 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7595 << OrigOp.get()->getSourceRange(); 7596 return QualType(); 7597 } 7598 7599 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 7600 if (OrigOp.isInvalid()) return QualType(); 7601 } 7602 7603 if (OrigOp.get()->isTypeDependent()) 7604 return S.Context.DependentTy; 7605 7606 assert(!OrigOp.get()->getType()->isPlaceholderType()); 7607 7608 // Make sure to ignore parentheses in subsequent checks 7609 Expr *op = OrigOp.get()->IgnoreParens(); 7610 7611 if (S.getLangOpts().C99) { 7612 // Implement C99-only parts of addressof rules. 7613 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 7614 if (uOp->getOpcode() == UO_Deref) 7615 // Per C99 6.5.3.2, the address of a deref always returns a valid result 7616 // (assuming the deref expression is valid). 7617 return uOp->getSubExpr()->getType(); 7618 } 7619 // Technically, there should be a check for array subscript 7620 // expressions here, but the result of one is always an lvalue anyway. 7621 } 7622 ValueDecl *dcl = getPrimaryDecl(op); 7623 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 7624 unsigned AddressOfError = AO_No_Error; 7625 7626 if (lval == Expr::LV_ClassTemporary) { 7627 bool sfinae = S.isSFINAEContext(); 7628 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary 7629 : diag::ext_typecheck_addrof_class_temporary) 7630 << op->getType() << op->getSourceRange(); 7631 if (sfinae) 7632 return QualType(); 7633 } else if (isa<ObjCSelectorExpr>(op)) { 7634 return S.Context.getPointerType(op->getType()); 7635 } else if (lval == Expr::LV_MemberFunction) { 7636 // If it's an instance method, make a member pointer. 7637 // The expression must have exactly the form &A::foo. 7638 7639 // If the underlying expression isn't a decl ref, give up. 7640 if (!isa<DeclRefExpr>(op)) { 7641 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7642 << OrigOp.get()->getSourceRange(); 7643 return QualType(); 7644 } 7645 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 7646 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 7647 7648 // The id-expression was parenthesized. 7649 if (OrigOp.get() != DRE) { 7650 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 7651 << OrigOp.get()->getSourceRange(); 7652 7653 // The method was named without a qualifier. 7654 } else if (!DRE->getQualifier()) { 7655 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 7656 << op->getSourceRange(); 7657 } 7658 7659 return S.Context.getMemberPointerType(op->getType(), 7660 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 7661 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 7662 // C99 6.5.3.2p1 7663 // The operand must be either an l-value or a function designator 7664 if (!op->getType()->isFunctionType()) { 7665 // Use a special diagnostic for loads from property references. 7666 if (isa<PseudoObjectExpr>(op)) { 7667 AddressOfError = AO_Property_Expansion; 7668 } else { 7669 // FIXME: emit more specific diag... 7670 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7671 << op->getSourceRange(); 7672 return QualType(); 7673 } 7674 } 7675 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 7676 // The operand cannot be a bit-field 7677 AddressOfError = AO_Bit_Field; 7678 } else if (op->getObjectKind() == OK_VectorComponent) { 7679 // The operand cannot be an element of a vector 7680 AddressOfError = AO_Vector_Element; 7681 } else if (dcl) { // C99 6.5.3.2p1 7682 // We have an lvalue with a decl. Make sure the decl is not declared 7683 // with the register storage-class specifier. 7684 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 7685 // in C++ it is not error to take address of a register 7686 // variable (c++03 7.1.1P3) 7687 if (vd->getStorageClass() == SC_Register && 7688 !S.getLangOpts().CPlusPlus) { 7689 AddressOfError = AO_Register_Variable; 7690 } 7691 } else if (isa<FunctionTemplateDecl>(dcl)) { 7692 return S.Context.OverloadTy; 7693 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 7694 // Okay: we can take the address of a field. 7695 // Could be a pointer to member, though, if there is an explicit 7696 // scope qualifier for the class. 7697 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 7698 DeclContext *Ctx = dcl->getDeclContext(); 7699 if (Ctx && Ctx->isRecord()) { 7700 if (dcl->getType()->isReferenceType()) { 7701 S.Diag(OpLoc, 7702 diag::err_cannot_form_pointer_to_member_of_reference_type) 7703 << dcl->getDeclName() << dcl->getType(); 7704 return QualType(); 7705 } 7706 7707 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 7708 Ctx = Ctx->getParent(); 7709 return S.Context.getMemberPointerType(op->getType(), 7710 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 7711 } 7712 } 7713 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 7714 llvm_unreachable("Unknown/unexpected decl type"); 7715 } 7716 7717 if (AddressOfError != AO_No_Error) { 7718 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 7719 return QualType(); 7720 } 7721 7722 if (lval == Expr::LV_IncompleteVoidType) { 7723 // Taking the address of a void variable is technically illegal, but we 7724 // allow it in cases which are otherwise valid. 7725 // Example: "extern void x; void* y = &x;". 7726 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 7727 } 7728 7729 // If the operand has type "type", the result has type "pointer to type". 7730 if (op->getType()->isObjCObjectType()) 7731 return S.Context.getObjCObjectPointerType(op->getType()); 7732 return S.Context.getPointerType(op->getType()); 7733} 7734 7735/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 7736static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 7737 SourceLocation OpLoc) { 7738 if (Op->isTypeDependent()) 7739 return S.Context.DependentTy; 7740 7741 ExprResult ConvResult = S.UsualUnaryConversions(Op); 7742 if (ConvResult.isInvalid()) 7743 return QualType(); 7744 Op = ConvResult.take(); 7745 QualType OpTy = Op->getType(); 7746 QualType Result; 7747 7748 if (isa<CXXReinterpretCastExpr>(Op)) { 7749 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 7750 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 7751 Op->getSourceRange()); 7752 } 7753 7754 // Note that per both C89 and C99, indirection is always legal, even if OpTy 7755 // is an incomplete type or void. It would be possible to warn about 7756 // dereferencing a void pointer, but it's completely well-defined, and such a 7757 // warning is unlikely to catch any mistakes. 7758 if (const PointerType *PT = OpTy->getAs<PointerType>()) 7759 Result = PT->getPointeeType(); 7760 else if (const ObjCObjectPointerType *OPT = 7761 OpTy->getAs<ObjCObjectPointerType>()) 7762 Result = OPT->getPointeeType(); 7763 else { 7764 ExprResult PR = S.CheckPlaceholderExpr(Op); 7765 if (PR.isInvalid()) return QualType(); 7766 if (PR.take() != Op) 7767 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 7768 } 7769 7770 if (Result.isNull()) { 7771 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 7772 << OpTy << Op->getSourceRange(); 7773 return QualType(); 7774 } 7775 7776 // Dereferences are usually l-values... 7777 VK = VK_LValue; 7778 7779 // ...except that certain expressions are never l-values in C. 7780 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 7781 VK = VK_RValue; 7782 7783 return Result; 7784} 7785 7786static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 7787 tok::TokenKind Kind) { 7788 BinaryOperatorKind Opc; 7789 switch (Kind) { 7790 default: llvm_unreachable("Unknown binop!"); 7791 case tok::periodstar: Opc = BO_PtrMemD; break; 7792 case tok::arrowstar: Opc = BO_PtrMemI; break; 7793 case tok::star: Opc = BO_Mul; break; 7794 case tok::slash: Opc = BO_Div; break; 7795 case tok::percent: Opc = BO_Rem; break; 7796 case tok::plus: Opc = BO_Add; break; 7797 case tok::minus: Opc = BO_Sub; break; 7798 case tok::lessless: Opc = BO_Shl; break; 7799 case tok::greatergreater: Opc = BO_Shr; break; 7800 case tok::lessequal: Opc = BO_LE; break; 7801 case tok::less: Opc = BO_LT; break; 7802 case tok::greaterequal: Opc = BO_GE; break; 7803 case tok::greater: Opc = BO_GT; break; 7804 case tok::exclaimequal: Opc = BO_NE; break; 7805 case tok::equalequal: Opc = BO_EQ; break; 7806 case tok::amp: Opc = BO_And; break; 7807 case tok::caret: Opc = BO_Xor; break; 7808 case tok::pipe: Opc = BO_Or; break; 7809 case tok::ampamp: Opc = BO_LAnd; break; 7810 case tok::pipepipe: Opc = BO_LOr; break; 7811 case tok::equal: Opc = BO_Assign; break; 7812 case tok::starequal: Opc = BO_MulAssign; break; 7813 case tok::slashequal: Opc = BO_DivAssign; break; 7814 case tok::percentequal: Opc = BO_RemAssign; break; 7815 case tok::plusequal: Opc = BO_AddAssign; break; 7816 case tok::minusequal: Opc = BO_SubAssign; break; 7817 case tok::lesslessequal: Opc = BO_ShlAssign; break; 7818 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 7819 case tok::ampequal: Opc = BO_AndAssign; break; 7820 case tok::caretequal: Opc = BO_XorAssign; break; 7821 case tok::pipeequal: Opc = BO_OrAssign; break; 7822 case tok::comma: Opc = BO_Comma; break; 7823 } 7824 return Opc; 7825} 7826 7827static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 7828 tok::TokenKind Kind) { 7829 UnaryOperatorKind Opc; 7830 switch (Kind) { 7831 default: llvm_unreachable("Unknown unary op!"); 7832 case tok::plusplus: Opc = UO_PreInc; break; 7833 case tok::minusminus: Opc = UO_PreDec; break; 7834 case tok::amp: Opc = UO_AddrOf; break; 7835 case tok::star: Opc = UO_Deref; break; 7836 case tok::plus: Opc = UO_Plus; break; 7837 case tok::minus: Opc = UO_Minus; break; 7838 case tok::tilde: Opc = UO_Not; break; 7839 case tok::exclaim: Opc = UO_LNot; break; 7840 case tok::kw___real: Opc = UO_Real; break; 7841 case tok::kw___imag: Opc = UO_Imag; break; 7842 case tok::kw___extension__: Opc = UO_Extension; break; 7843 } 7844 return Opc; 7845} 7846 7847/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 7848/// This warning is only emitted for builtin assignment operations. It is also 7849/// suppressed in the event of macro expansions. 7850static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 7851 SourceLocation OpLoc) { 7852 if (!S.ActiveTemplateInstantiations.empty()) 7853 return; 7854 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 7855 return; 7856 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 7857 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 7858 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 7859 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 7860 if (!LHSDeclRef || !RHSDeclRef || 7861 LHSDeclRef->getLocation().isMacroID() || 7862 RHSDeclRef->getLocation().isMacroID()) 7863 return; 7864 const ValueDecl *LHSDecl = 7865 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 7866 const ValueDecl *RHSDecl = 7867 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 7868 if (LHSDecl != RHSDecl) 7869 return; 7870 if (LHSDecl->getType().isVolatileQualified()) 7871 return; 7872 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 7873 if (RefTy->getPointeeType().isVolatileQualified()) 7874 return; 7875 7876 S.Diag(OpLoc, diag::warn_self_assignment) 7877 << LHSDeclRef->getType() 7878 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7879} 7880 7881/// CreateBuiltinBinOp - Creates a new built-in binary operation with 7882/// operator @p Opc at location @c TokLoc. This routine only supports 7883/// built-in operations; ActOnBinOp handles overloaded operators. 7884ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 7885 BinaryOperatorKind Opc, 7886 Expr *LHSExpr, Expr *RHSExpr) { 7887 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) { 7888 // The syntax only allows initializer lists on the RHS of assignment, 7889 // so we don't need to worry about accepting invalid code for 7890 // non-assignment operators. 7891 // C++11 5.17p9: 7892 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 7893 // of x = {} is x = T(). 7894 InitializationKind Kind = 7895 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 7896 InitializedEntity Entity = 7897 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 7898 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1); 7899 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 7900 MultiExprArg(&RHSExpr, 1)); 7901 if (Init.isInvalid()) 7902 return Init; 7903 RHSExpr = Init.take(); 7904 } 7905 7906 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 7907 QualType ResultTy; // Result type of the binary operator. 7908 // The following two variables are used for compound assignment operators 7909 QualType CompLHSTy; // Type of LHS after promotions for computation 7910 QualType CompResultTy; // Type of computation result 7911 ExprValueKind VK = VK_RValue; 7912 ExprObjectKind OK = OK_Ordinary; 7913 7914 switch (Opc) { 7915 case BO_Assign: 7916 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 7917 if (getLangOpts().CPlusPlus && 7918 LHS.get()->getObjectKind() != OK_ObjCProperty) { 7919 VK = LHS.get()->getValueKind(); 7920 OK = LHS.get()->getObjectKind(); 7921 } 7922 if (!ResultTy.isNull()) 7923 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 7924 break; 7925 case BO_PtrMemD: 7926 case BO_PtrMemI: 7927 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 7928 Opc == BO_PtrMemI); 7929 break; 7930 case BO_Mul: 7931 case BO_Div: 7932 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 7933 Opc == BO_Div); 7934 break; 7935 case BO_Rem: 7936 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 7937 break; 7938 case BO_Add: 7939 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 7940 break; 7941 case BO_Sub: 7942 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 7943 break; 7944 case BO_Shl: 7945 case BO_Shr: 7946 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 7947 break; 7948 case BO_LE: 7949 case BO_LT: 7950 case BO_GE: 7951 case BO_GT: 7952 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 7953 break; 7954 case BO_EQ: 7955 case BO_NE: 7956 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 7957 break; 7958 case BO_And: 7959 case BO_Xor: 7960 case BO_Or: 7961 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 7962 break; 7963 case BO_LAnd: 7964 case BO_LOr: 7965 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 7966 break; 7967 case BO_MulAssign: 7968 case BO_DivAssign: 7969 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 7970 Opc == BO_DivAssign); 7971 CompLHSTy = CompResultTy; 7972 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7973 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7974 break; 7975 case BO_RemAssign: 7976 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 7977 CompLHSTy = CompResultTy; 7978 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7979 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7980 break; 7981 case BO_AddAssign: 7982 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 7983 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7984 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7985 break; 7986 case BO_SubAssign: 7987 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 7988 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7989 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7990 break; 7991 case BO_ShlAssign: 7992 case BO_ShrAssign: 7993 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 7994 CompLHSTy = CompResultTy; 7995 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7996 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7997 break; 7998 case BO_AndAssign: 7999 case BO_XorAssign: 8000 case BO_OrAssign: 8001 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 8002 CompLHSTy = CompResultTy; 8003 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8004 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8005 break; 8006 case BO_Comma: 8007 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 8008 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 8009 VK = RHS.get()->getValueKind(); 8010 OK = RHS.get()->getObjectKind(); 8011 } 8012 break; 8013 } 8014 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 8015 return ExprError(); 8016 8017 // Check for array bounds violations for both sides of the BinaryOperator 8018 CheckArrayAccess(LHS.get()); 8019 CheckArrayAccess(RHS.get()); 8020 8021 if (CompResultTy.isNull()) 8022 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 8023 ResultTy, VK, OK, OpLoc)); 8024 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 8025 OK_ObjCProperty) { 8026 VK = VK_LValue; 8027 OK = LHS.get()->getObjectKind(); 8028 } 8029 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 8030 ResultTy, VK, OK, CompLHSTy, 8031 CompResultTy, OpLoc)); 8032} 8033 8034/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8035/// operators are mixed in a way that suggests that the programmer forgot that 8036/// comparison operators have higher precedence. The most typical example of 8037/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8038static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8039 SourceLocation OpLoc, Expr *LHSExpr, 8040 Expr *RHSExpr) { 8041 typedef BinaryOperator BinOp; 8042 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1), 8043 RHSopc = static_cast<BinOp::Opcode>(-1); 8044 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr)) 8045 LHSopc = BO->getOpcode(); 8046 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr)) 8047 RHSopc = BO->getOpcode(); 8048 8049 // Subs are not binary operators. 8050 if (LHSopc == -1 && RHSopc == -1) 8051 return; 8052 8053 // Bitwise operations are sometimes used as eager logical ops. 8054 // Don't diagnose this. 8055 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) && 8056 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc))) 8057 return; 8058 8059 bool isLeftComp = BinOp::isComparisonOp(LHSopc); 8060 bool isRightComp = BinOp::isComparisonOp(RHSopc); 8061 if (!isLeftComp && !isRightComp) return; 8062 8063 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 8064 OpLoc) 8065 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 8066 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc) 8067 : BinOp::getOpcodeStr(RHSopc); 8068 SourceRange ParensRange = isLeftComp ? 8069 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(), 8070 RHSExpr->getLocEnd()) 8071 : SourceRange(LHSExpr->getLocStart(), 8072 cast<BinOp>(RHSExpr)->getLHS()->getLocStart()); 8073 8074 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 8075 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr; 8076 SuggestParentheses(Self, OpLoc, 8077 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr, 8078 RHSExpr->getSourceRange()); 8079 SuggestParentheses(Self, OpLoc, 8080 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc), 8081 ParensRange); 8082} 8083 8084/// \brief It accepts a '&' expr that is inside a '|' one. 8085/// Emit a diagnostic together with a fixit hint that wraps the '&' expression 8086/// in parentheses. 8087static void 8088EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 8089 BinaryOperator *Bop) { 8090 assert(Bop->getOpcode() == BO_And); 8091 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 8092 << Bop->getSourceRange() << OpLoc; 8093 SuggestParentheses(Self, Bop->getOperatorLoc(), 8094 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence), 8095 Bop->getSourceRange()); 8096} 8097 8098/// \brief It accepts a '&&' expr that is inside a '||' one. 8099/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8100/// in parentheses. 8101static void 8102EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8103 BinaryOperator *Bop) { 8104 assert(Bop->getOpcode() == BO_LAnd); 8105 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 8106 << Bop->getSourceRange() << OpLoc; 8107 SuggestParentheses(Self, Bop->getOperatorLoc(), 8108 Self.PDiag(diag::note_logical_and_in_logical_or_silence), 8109 Bop->getSourceRange()); 8110} 8111 8112/// \brief Returns true if the given expression can be evaluated as a constant 8113/// 'true'. 8114static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8115 bool Res; 8116 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8117} 8118 8119/// \brief Returns true if the given expression can be evaluated as a constant 8120/// 'false'. 8121static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8122 bool Res; 8123 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8124} 8125 8126/// \brief Look for '&&' in the left hand of a '||' expr. 8127static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8128 Expr *LHSExpr, Expr *RHSExpr) { 8129 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 8130 if (Bop->getOpcode() == BO_LAnd) { 8131 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8132 if (EvaluatesAsFalse(S, RHSExpr)) 8133 return; 8134 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8135 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8136 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8137 } else if (Bop->getOpcode() == BO_LOr) { 8138 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8139 // If it's "a || b && 1 || c" we didn't warn earlier for 8140 // "a || b && 1", but warn now. 8141 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8142 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8143 } 8144 } 8145 } 8146} 8147 8148/// \brief Look for '&&' in the right hand of a '||' expr. 8149static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8150 Expr *LHSExpr, Expr *RHSExpr) { 8151 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 8152 if (Bop->getOpcode() == BO_LAnd) { 8153 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8154 if (EvaluatesAsFalse(S, LHSExpr)) 8155 return; 8156 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8157 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8158 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8159 } 8160 } 8161} 8162 8163/// \brief Look for '&' in the left or right hand of a '|' expr. 8164static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 8165 Expr *OrArg) { 8166 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 8167 if (Bop->getOpcode() == BO_And) 8168 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 8169 } 8170} 8171 8172/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 8173/// precedence. 8174static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 8175 SourceLocation OpLoc, Expr *LHSExpr, 8176 Expr *RHSExpr){ 8177 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 8178 if (BinaryOperator::isBitwiseOp(Opc)) 8179 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 8180 8181 // Diagnose "arg1 & arg2 | arg3" 8182 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8183 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 8184 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 8185 } 8186 8187 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 8188 // We don't warn for 'assert(a || b && "bad")' since this is safe. 8189 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8190 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 8191 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 8192 } 8193} 8194 8195// Binary Operators. 'Tok' is the token for the operator. 8196ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 8197 tok::TokenKind Kind, 8198 Expr *LHSExpr, Expr *RHSExpr) { 8199 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 8200 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 8201 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 8202 8203 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 8204 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 8205 8206 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 8207} 8208 8209/// Build an overloaded binary operator expression in the given scope. 8210static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 8211 BinaryOperatorKind Opc, 8212 Expr *LHS, Expr *RHS) { 8213 // Find all of the overloaded operators visible from this 8214 // point. We perform both an operator-name lookup from the local 8215 // scope and an argument-dependent lookup based on the types of 8216 // the arguments. 8217 UnresolvedSet<16> Functions; 8218 OverloadedOperatorKind OverOp 8219 = BinaryOperator::getOverloadedOperator(Opc); 8220 if (Sc && OverOp != OO_None) 8221 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 8222 RHS->getType(), Functions); 8223 8224 // Build the (potentially-overloaded, potentially-dependent) 8225 // binary operation. 8226 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 8227} 8228 8229ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 8230 BinaryOperatorKind Opc, 8231 Expr *LHSExpr, Expr *RHSExpr) { 8232 // We want to end up calling one of checkPseudoObjectAssignment 8233 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 8234 // both expressions are overloadable or either is type-dependent), 8235 // or CreateBuiltinBinOp (in any other case). We also want to get 8236 // any placeholder types out of the way. 8237 8238 // Handle pseudo-objects in the LHS. 8239 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 8240 // Assignments with a pseudo-object l-value need special analysis. 8241 if (pty->getKind() == BuiltinType::PseudoObject && 8242 BinaryOperator::isAssignmentOp(Opc)) 8243 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 8244 8245 // Don't resolve overloads if the other type is overloadable. 8246 if (pty->getKind() == BuiltinType::Overload) { 8247 // We can't actually test that if we still have a placeholder, 8248 // though. Fortunately, none of the exceptions we see in that 8249 // code below are valid when the LHS is an overload set. Note 8250 // that an overload set can be dependently-typed, but it never 8251 // instantiates to having an overloadable type. 8252 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8253 if (resolvedRHS.isInvalid()) return ExprError(); 8254 RHSExpr = resolvedRHS.take(); 8255 8256 if (RHSExpr->isTypeDependent() || 8257 RHSExpr->getType()->isOverloadableType()) 8258 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8259 } 8260 8261 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 8262 if (LHS.isInvalid()) return ExprError(); 8263 LHSExpr = LHS.take(); 8264 } 8265 8266 // Handle pseudo-objects in the RHS. 8267 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 8268 // An overload in the RHS can potentially be resolved by the type 8269 // being assigned to. 8270 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 8271 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8272 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8273 8274 if (LHSExpr->getType()->isOverloadableType()) 8275 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8276 8277 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8278 } 8279 8280 // Don't resolve overloads if the other type is overloadable. 8281 if (pty->getKind() == BuiltinType::Overload && 8282 LHSExpr->getType()->isOverloadableType()) 8283 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8284 8285 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8286 if (!resolvedRHS.isUsable()) return ExprError(); 8287 RHSExpr = resolvedRHS.take(); 8288 } 8289 8290 if (getLangOpts().CPlusPlus) { 8291 // If either expression is type-dependent, always build an 8292 // overloaded op. 8293 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8294 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8295 8296 // Otherwise, build an overloaded op if either expression has an 8297 // overloadable type. 8298 if (LHSExpr->getType()->isOverloadableType() || 8299 RHSExpr->getType()->isOverloadableType()) 8300 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8301 } 8302 8303 // Build a built-in binary operation. 8304 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8305} 8306 8307ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 8308 UnaryOperatorKind Opc, 8309 Expr *InputExpr) { 8310 ExprResult Input = Owned(InputExpr); 8311 ExprValueKind VK = VK_RValue; 8312 ExprObjectKind OK = OK_Ordinary; 8313 QualType resultType; 8314 switch (Opc) { 8315 case UO_PreInc: 8316 case UO_PreDec: 8317 case UO_PostInc: 8318 case UO_PostDec: 8319 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 8320 Opc == UO_PreInc || 8321 Opc == UO_PostInc, 8322 Opc == UO_PreInc || 8323 Opc == UO_PreDec); 8324 break; 8325 case UO_AddrOf: 8326 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 8327 break; 8328 case UO_Deref: { 8329 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8330 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 8331 break; 8332 } 8333 case UO_Plus: 8334 case UO_Minus: 8335 Input = UsualUnaryConversions(Input.take()); 8336 if (Input.isInvalid()) return ExprError(); 8337 resultType = Input.get()->getType(); 8338 if (resultType->isDependentType()) 8339 break; 8340 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 8341 resultType->isVectorType()) 8342 break; 8343 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 8344 resultType->isEnumeralType()) 8345 break; 8346 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 8347 Opc == UO_Plus && 8348 resultType->isPointerType()) 8349 break; 8350 8351 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8352 << resultType << Input.get()->getSourceRange()); 8353 8354 case UO_Not: // bitwise complement 8355 Input = UsualUnaryConversions(Input.take()); 8356 if (Input.isInvalid()) return ExprError(); 8357 resultType = Input.get()->getType(); 8358 if (resultType->isDependentType()) 8359 break; 8360 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 8361 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 8362 // C99 does not support '~' for complex conjugation. 8363 Diag(OpLoc, diag::ext_integer_complement_complex) 8364 << resultType << Input.get()->getSourceRange(); 8365 else if (resultType->hasIntegerRepresentation()) 8366 break; 8367 else { 8368 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8369 << resultType << Input.get()->getSourceRange()); 8370 } 8371 break; 8372 8373 case UO_LNot: // logical negation 8374 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 8375 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8376 if (Input.isInvalid()) return ExprError(); 8377 resultType = Input.get()->getType(); 8378 8379 // Though we still have to promote half FP to float... 8380 if (resultType->isHalfType()) { 8381 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 8382 resultType = Context.FloatTy; 8383 } 8384 8385 if (resultType->isDependentType()) 8386 break; 8387 if (resultType->isScalarType()) { 8388 // C99 6.5.3.3p1: ok, fallthrough; 8389 if (Context.getLangOpts().CPlusPlus) { 8390 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 8391 // operand contextually converted to bool. 8392 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 8393 ScalarTypeToBooleanCastKind(resultType)); 8394 } 8395 } else if (resultType->isExtVectorType()) { 8396 // Vector logical not returns the signed variant of the operand type. 8397 resultType = GetSignedVectorType(resultType); 8398 break; 8399 } else { 8400 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8401 << resultType << Input.get()->getSourceRange()); 8402 } 8403 8404 // LNot always has type int. C99 6.5.3.3p5. 8405 // In C++, it's bool. C++ 5.3.1p8 8406 resultType = Context.getLogicalOperationType(); 8407 break; 8408 case UO_Real: 8409 case UO_Imag: 8410 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 8411 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 8412 // complex l-values to ordinary l-values and all other values to r-values. 8413 if (Input.isInvalid()) return ExprError(); 8414 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 8415 if (Input.get()->getValueKind() != VK_RValue && 8416 Input.get()->getObjectKind() == OK_Ordinary) 8417 VK = Input.get()->getValueKind(); 8418 } else if (!getLangOpts().CPlusPlus) { 8419 // In C, a volatile scalar is read by __imag. In C++, it is not. 8420 Input = DefaultLvalueConversion(Input.take()); 8421 } 8422 break; 8423 case UO_Extension: 8424 resultType = Input.get()->getType(); 8425 VK = Input.get()->getValueKind(); 8426 OK = Input.get()->getObjectKind(); 8427 break; 8428 } 8429 if (resultType.isNull() || Input.isInvalid()) 8430 return ExprError(); 8431 8432 // Check for array bounds violations in the operand of the UnaryOperator, 8433 // except for the '*' and '&' operators that have to be handled specially 8434 // by CheckArrayAccess (as there are special cases like &array[arraysize] 8435 // that are explicitly defined as valid by the standard). 8436 if (Opc != UO_AddrOf && Opc != UO_Deref) 8437 CheckArrayAccess(Input.get()); 8438 8439 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 8440 VK, OK, OpLoc)); 8441} 8442 8443/// \brief Determine whether the given expression is a qualified member 8444/// access expression, of a form that could be turned into a pointer to member 8445/// with the address-of operator. 8446static bool isQualifiedMemberAccess(Expr *E) { 8447 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8448 if (!DRE->getQualifier()) 8449 return false; 8450 8451 ValueDecl *VD = DRE->getDecl(); 8452 if (!VD->isCXXClassMember()) 8453 return false; 8454 8455 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 8456 return true; 8457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 8458 return Method->isInstance(); 8459 8460 return false; 8461 } 8462 8463 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 8464 if (!ULE->getQualifier()) 8465 return false; 8466 8467 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 8468 DEnd = ULE->decls_end(); 8469 D != DEnd; ++D) { 8470 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 8471 if (Method->isInstance()) 8472 return true; 8473 } else { 8474 // Overload set does not contain methods. 8475 break; 8476 } 8477 } 8478 8479 return false; 8480 } 8481 8482 return false; 8483} 8484 8485ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 8486 UnaryOperatorKind Opc, Expr *Input) { 8487 // First things first: handle placeholders so that the 8488 // overloaded-operator check considers the right type. 8489 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 8490 // Increment and decrement of pseudo-object references. 8491 if (pty->getKind() == BuiltinType::PseudoObject && 8492 UnaryOperator::isIncrementDecrementOp(Opc)) 8493 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 8494 8495 // extension is always a builtin operator. 8496 if (Opc == UO_Extension) 8497 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8498 8499 // & gets special logic for several kinds of placeholder. 8500 // The builtin code knows what to do. 8501 if (Opc == UO_AddrOf && 8502 (pty->getKind() == BuiltinType::Overload || 8503 pty->getKind() == BuiltinType::UnknownAny || 8504 pty->getKind() == BuiltinType::BoundMember)) 8505 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8506 8507 // Anything else needs to be handled now. 8508 ExprResult Result = CheckPlaceholderExpr(Input); 8509 if (Result.isInvalid()) return ExprError(); 8510 Input = Result.take(); 8511 } 8512 8513 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 8514 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 8515 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 8516 // Find all of the overloaded operators visible from this 8517 // point. We perform both an operator-name lookup from the local 8518 // scope and an argument-dependent lookup based on the types of 8519 // the arguments. 8520 UnresolvedSet<16> Functions; 8521 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 8522 if (S && OverOp != OO_None) 8523 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 8524 Functions); 8525 8526 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 8527 } 8528 8529 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8530} 8531 8532// Unary Operators. 'Tok' is the token for the operator. 8533ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 8534 tok::TokenKind Op, Expr *Input) { 8535 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 8536} 8537 8538/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 8539ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 8540 LabelDecl *TheDecl) { 8541 TheDecl->setUsed(); 8542 // Create the AST node. The address of a label always has type 'void*'. 8543 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 8544 Context.getPointerType(Context.VoidTy))); 8545} 8546 8547/// Given the last statement in a statement-expression, check whether 8548/// the result is a producing expression (like a call to an 8549/// ns_returns_retained function) and, if so, rebuild it to hoist the 8550/// release out of the full-expression. Otherwise, return null. 8551/// Cannot fail. 8552static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 8553 // Should always be wrapped with one of these. 8554 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 8555 if (!cleanups) return 0; 8556 8557 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 8558 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 8559 return 0; 8560 8561 // Splice out the cast. This shouldn't modify any interesting 8562 // features of the statement. 8563 Expr *producer = cast->getSubExpr(); 8564 assert(producer->getType() == cast->getType()); 8565 assert(producer->getValueKind() == cast->getValueKind()); 8566 cleanups->setSubExpr(producer); 8567 return cleanups; 8568} 8569 8570void Sema::ActOnStartStmtExpr() { 8571 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 8572} 8573 8574void Sema::ActOnStmtExprError() { 8575 // Note that function is also called by TreeTransform when leaving a 8576 // StmtExpr scope without rebuilding anything. 8577 8578 DiscardCleanupsInEvaluationContext(); 8579 PopExpressionEvaluationContext(); 8580} 8581 8582ExprResult 8583Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 8584 SourceLocation RPLoc) { // "({..})" 8585 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 8586 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 8587 8588 if (hasAnyUnrecoverableErrorsInThisFunction()) 8589 DiscardCleanupsInEvaluationContext(); 8590 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 8591 PopExpressionEvaluationContext(); 8592 8593 bool isFileScope 8594 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 8595 if (isFileScope) 8596 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 8597 8598 // FIXME: there are a variety of strange constraints to enforce here, for 8599 // example, it is not possible to goto into a stmt expression apparently. 8600 // More semantic analysis is needed. 8601 8602 // If there are sub stmts in the compound stmt, take the type of the last one 8603 // as the type of the stmtexpr. 8604 QualType Ty = Context.VoidTy; 8605 bool StmtExprMayBindToTemp = false; 8606 if (!Compound->body_empty()) { 8607 Stmt *LastStmt = Compound->body_back(); 8608 LabelStmt *LastLabelStmt = 0; 8609 // If LastStmt is a label, skip down through into the body. 8610 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 8611 LastLabelStmt = Label; 8612 LastStmt = Label->getSubStmt(); 8613 } 8614 8615 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 8616 // Do function/array conversion on the last expression, but not 8617 // lvalue-to-rvalue. However, initialize an unqualified type. 8618 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 8619 if (LastExpr.isInvalid()) 8620 return ExprError(); 8621 Ty = LastExpr.get()->getType().getUnqualifiedType(); 8622 8623 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 8624 // In ARC, if the final expression ends in a consume, splice 8625 // the consume out and bind it later. In the alternate case 8626 // (when dealing with a retainable type), the result 8627 // initialization will create a produce. In both cases the 8628 // result will be +1, and we'll need to balance that out with 8629 // a bind. 8630 if (Expr *rebuiltLastStmt 8631 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 8632 LastExpr = rebuiltLastStmt; 8633 } else { 8634 LastExpr = PerformCopyInitialization( 8635 InitializedEntity::InitializeResult(LPLoc, 8636 Ty, 8637 false), 8638 SourceLocation(), 8639 LastExpr); 8640 } 8641 8642 if (LastExpr.isInvalid()) 8643 return ExprError(); 8644 if (LastExpr.get() != 0) { 8645 if (!LastLabelStmt) 8646 Compound->setLastStmt(LastExpr.take()); 8647 else 8648 LastLabelStmt->setSubStmt(LastExpr.take()); 8649 StmtExprMayBindToTemp = true; 8650 } 8651 } 8652 } 8653 } 8654 8655 // FIXME: Check that expression type is complete/non-abstract; statement 8656 // expressions are not lvalues. 8657 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 8658 if (StmtExprMayBindToTemp) 8659 return MaybeBindToTemporary(ResStmtExpr); 8660 return Owned(ResStmtExpr); 8661} 8662 8663ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 8664 TypeSourceInfo *TInfo, 8665 OffsetOfComponent *CompPtr, 8666 unsigned NumComponents, 8667 SourceLocation RParenLoc) { 8668 QualType ArgTy = TInfo->getType(); 8669 bool Dependent = ArgTy->isDependentType(); 8670 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 8671 8672 // We must have at least one component that refers to the type, and the first 8673 // one is known to be a field designator. Verify that the ArgTy represents 8674 // a struct/union/class. 8675 if (!Dependent && !ArgTy->isRecordType()) 8676 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 8677 << ArgTy << TypeRange); 8678 8679 // Type must be complete per C99 7.17p3 because a declaring a variable 8680 // with an incomplete type would be ill-formed. 8681 if (!Dependent 8682 && RequireCompleteType(BuiltinLoc, ArgTy, 8683 diag::err_offsetof_incomplete_type, TypeRange)) 8684 return ExprError(); 8685 8686 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 8687 // GCC extension, diagnose them. 8688 // FIXME: This diagnostic isn't actually visible because the location is in 8689 // a system header! 8690 if (NumComponents != 1) 8691 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 8692 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 8693 8694 bool DidWarnAboutNonPOD = false; 8695 QualType CurrentType = ArgTy; 8696 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 8697 SmallVector<OffsetOfNode, 4> Comps; 8698 SmallVector<Expr*, 4> Exprs; 8699 for (unsigned i = 0; i != NumComponents; ++i) { 8700 const OffsetOfComponent &OC = CompPtr[i]; 8701 if (OC.isBrackets) { 8702 // Offset of an array sub-field. TODO: Should we allow vector elements? 8703 if (!CurrentType->isDependentType()) { 8704 const ArrayType *AT = Context.getAsArrayType(CurrentType); 8705 if(!AT) 8706 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 8707 << CurrentType); 8708 CurrentType = AT->getElementType(); 8709 } else 8710 CurrentType = Context.DependentTy; 8711 8712 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 8713 if (IdxRval.isInvalid()) 8714 return ExprError(); 8715 Expr *Idx = IdxRval.take(); 8716 8717 // The expression must be an integral expression. 8718 // FIXME: An integral constant expression? 8719 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 8720 !Idx->getType()->isIntegerType()) 8721 return ExprError(Diag(Idx->getLocStart(), 8722 diag::err_typecheck_subscript_not_integer) 8723 << Idx->getSourceRange()); 8724 8725 // Record this array index. 8726 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 8727 Exprs.push_back(Idx); 8728 continue; 8729 } 8730 8731 // Offset of a field. 8732 if (CurrentType->isDependentType()) { 8733 // We have the offset of a field, but we can't look into the dependent 8734 // type. Just record the identifier of the field. 8735 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 8736 CurrentType = Context.DependentTy; 8737 continue; 8738 } 8739 8740 // We need to have a complete type to look into. 8741 if (RequireCompleteType(OC.LocStart, CurrentType, 8742 diag::err_offsetof_incomplete_type)) 8743 return ExprError(); 8744 8745 // Look for the designated field. 8746 const RecordType *RC = CurrentType->getAs<RecordType>(); 8747 if (!RC) 8748 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 8749 << CurrentType); 8750 RecordDecl *RD = RC->getDecl(); 8751 8752 // C++ [lib.support.types]p5: 8753 // The macro offsetof accepts a restricted set of type arguments in this 8754 // International Standard. type shall be a POD structure or a POD union 8755 // (clause 9). 8756 // C++11 [support.types]p4: 8757 // If type is not a standard-layout class (Clause 9), the results are 8758 // undefined. 8759 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 8760 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD(); 8761 unsigned DiagID = 8762 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type 8763 : diag::warn_offsetof_non_pod_type; 8764 8765 if (!IsSafe && !DidWarnAboutNonPOD && 8766 DiagRuntimeBehavior(BuiltinLoc, 0, 8767 PDiag(DiagID) 8768 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 8769 << CurrentType)) 8770 DidWarnAboutNonPOD = true; 8771 } 8772 8773 // Look for the field. 8774 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 8775 LookupQualifiedName(R, RD); 8776 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 8777 IndirectFieldDecl *IndirectMemberDecl = 0; 8778 if (!MemberDecl) { 8779 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 8780 MemberDecl = IndirectMemberDecl->getAnonField(); 8781 } 8782 8783 if (!MemberDecl) 8784 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 8785 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 8786 OC.LocEnd)); 8787 8788 // C99 7.17p3: 8789 // (If the specified member is a bit-field, the behavior is undefined.) 8790 // 8791 // We diagnose this as an error. 8792 if (MemberDecl->isBitField()) { 8793 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 8794 << MemberDecl->getDeclName() 8795 << SourceRange(BuiltinLoc, RParenLoc); 8796 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 8797 return ExprError(); 8798 } 8799 8800 RecordDecl *Parent = MemberDecl->getParent(); 8801 if (IndirectMemberDecl) 8802 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 8803 8804 // If the member was found in a base class, introduce OffsetOfNodes for 8805 // the base class indirections. 8806 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8807 /*DetectVirtual=*/false); 8808 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 8809 CXXBasePath &Path = Paths.front(); 8810 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 8811 B != BEnd; ++B) 8812 Comps.push_back(OffsetOfNode(B->Base)); 8813 } 8814 8815 if (IndirectMemberDecl) { 8816 for (IndirectFieldDecl::chain_iterator FI = 8817 IndirectMemberDecl->chain_begin(), 8818 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 8819 assert(isa<FieldDecl>(*FI)); 8820 Comps.push_back(OffsetOfNode(OC.LocStart, 8821 cast<FieldDecl>(*FI), OC.LocEnd)); 8822 } 8823 } else 8824 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 8825 8826 CurrentType = MemberDecl->getType().getNonReferenceType(); 8827 } 8828 8829 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 8830 TInfo, Comps.data(), Comps.size(), 8831 Exprs.data(), Exprs.size(), RParenLoc)); 8832} 8833 8834ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 8835 SourceLocation BuiltinLoc, 8836 SourceLocation TypeLoc, 8837 ParsedType ParsedArgTy, 8838 OffsetOfComponent *CompPtr, 8839 unsigned NumComponents, 8840 SourceLocation RParenLoc) { 8841 8842 TypeSourceInfo *ArgTInfo; 8843 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 8844 if (ArgTy.isNull()) 8845 return ExprError(); 8846 8847 if (!ArgTInfo) 8848 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 8849 8850 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 8851 RParenLoc); 8852} 8853 8854 8855ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 8856 Expr *CondExpr, 8857 Expr *LHSExpr, Expr *RHSExpr, 8858 SourceLocation RPLoc) { 8859 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 8860 8861 ExprValueKind VK = VK_RValue; 8862 ExprObjectKind OK = OK_Ordinary; 8863 QualType resType; 8864 bool ValueDependent = false; 8865 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 8866 resType = Context.DependentTy; 8867 ValueDependent = true; 8868 } else { 8869 // The conditional expression is required to be a constant expression. 8870 llvm::APSInt condEval(32); 8871 ExprResult CondICE 8872 = VerifyIntegerConstantExpression(CondExpr, &condEval, 8873 diag::err_typecheck_choose_expr_requires_constant, false); 8874 if (CondICE.isInvalid()) 8875 return ExprError(); 8876 CondExpr = CondICE.take(); 8877 8878 // If the condition is > zero, then the AST type is the same as the LSHExpr. 8879 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 8880 8881 resType = ActiveExpr->getType(); 8882 ValueDependent = ActiveExpr->isValueDependent(); 8883 VK = ActiveExpr->getValueKind(); 8884 OK = ActiveExpr->getObjectKind(); 8885 } 8886 8887 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 8888 resType, VK, OK, RPLoc, 8889 resType->isDependentType(), 8890 ValueDependent)); 8891} 8892 8893//===----------------------------------------------------------------------===// 8894// Clang Extensions. 8895//===----------------------------------------------------------------------===// 8896 8897/// ActOnBlockStart - This callback is invoked when a block literal is started. 8898void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 8899 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 8900 PushBlockScope(CurScope, Block); 8901 CurContext->addDecl(Block); 8902 if (CurScope) 8903 PushDeclContext(CurScope, Block); 8904 else 8905 CurContext = Block; 8906 8907 getCurBlock()->HasImplicitReturnType = true; 8908 8909 // Enter a new evaluation context to insulate the block from any 8910 // cleanups from the enclosing full-expression. 8911 PushExpressionEvaluationContext(PotentiallyEvaluated); 8912} 8913 8914void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 8915 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 8916 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 8917 BlockScopeInfo *CurBlock = getCurBlock(); 8918 8919 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 8920 QualType T = Sig->getType(); 8921 8922 // GetTypeForDeclarator always produces a function type for a block 8923 // literal signature. Furthermore, it is always a FunctionProtoType 8924 // unless the function was written with a typedef. 8925 assert(T->isFunctionType() && 8926 "GetTypeForDeclarator made a non-function block signature"); 8927 8928 // Look for an explicit signature in that function type. 8929 FunctionProtoTypeLoc ExplicitSignature; 8930 8931 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 8932 if (isa<FunctionProtoTypeLoc>(tmp)) { 8933 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp); 8934 8935 // Check whether that explicit signature was synthesized by 8936 // GetTypeForDeclarator. If so, don't save that as part of the 8937 // written signature. 8938 if (ExplicitSignature.getLocalRangeBegin() == 8939 ExplicitSignature.getLocalRangeEnd()) { 8940 // This would be much cheaper if we stored TypeLocs instead of 8941 // TypeSourceInfos. 8942 TypeLoc Result = ExplicitSignature.getResultLoc(); 8943 unsigned Size = Result.getFullDataSize(); 8944 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 8945 Sig->getTypeLoc().initializeFullCopy(Result, Size); 8946 8947 ExplicitSignature = FunctionProtoTypeLoc(); 8948 } 8949 } 8950 8951 CurBlock->TheDecl->setSignatureAsWritten(Sig); 8952 CurBlock->FunctionType = T; 8953 8954 const FunctionType *Fn = T->getAs<FunctionType>(); 8955 QualType RetTy = Fn->getResultType(); 8956 bool isVariadic = 8957 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 8958 8959 CurBlock->TheDecl->setIsVariadic(isVariadic); 8960 8961 // Don't allow returning a objc interface by value. 8962 if (RetTy->isObjCObjectType()) { 8963 Diag(ParamInfo.getLocStart(), 8964 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 8965 return; 8966 } 8967 8968 // Context.DependentTy is used as a placeholder for a missing block 8969 // return type. TODO: what should we do with declarators like: 8970 // ^ * { ... } 8971 // If the answer is "apply template argument deduction".... 8972 if (RetTy != Context.DependentTy) { 8973 CurBlock->ReturnType = RetTy; 8974 CurBlock->TheDecl->setBlockMissingReturnType(false); 8975 CurBlock->HasImplicitReturnType = false; 8976 } 8977 8978 // Push block parameters from the declarator if we had them. 8979 SmallVector<ParmVarDecl*, 8> Params; 8980 if (ExplicitSignature) { 8981 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 8982 ParmVarDecl *Param = ExplicitSignature.getArg(I); 8983 if (Param->getIdentifier() == 0 && 8984 !Param->isImplicit() && 8985 !Param->isInvalidDecl() && 8986 !getLangOpts().CPlusPlus) 8987 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 8988 Params.push_back(Param); 8989 } 8990 8991 // Fake up parameter variables if we have a typedef, like 8992 // ^ fntype { ... } 8993 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 8994 for (FunctionProtoType::arg_type_iterator 8995 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 8996 ParmVarDecl *Param = 8997 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 8998 ParamInfo.getLocStart(), 8999 *I); 9000 Params.push_back(Param); 9001 } 9002 } 9003 9004 // Set the parameters on the block decl. 9005 if (!Params.empty()) { 9006 CurBlock->TheDecl->setParams(Params); 9007 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 9008 CurBlock->TheDecl->param_end(), 9009 /*CheckParameterNames=*/false); 9010 } 9011 9012 // Finally we can process decl attributes. 9013 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 9014 9015 // Put the parameter variables in scope. We can bail out immediately 9016 // if we don't have any. 9017 if (Params.empty()) 9018 return; 9019 9020 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 9021 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 9022 (*AI)->setOwningFunction(CurBlock->TheDecl); 9023 9024 // If this has an identifier, add it to the scope stack. 9025 if ((*AI)->getIdentifier()) { 9026 CheckShadow(CurBlock->TheScope, *AI); 9027 9028 PushOnScopeChains(*AI, CurBlock->TheScope); 9029 } 9030 } 9031} 9032 9033/// ActOnBlockError - If there is an error parsing a block, this callback 9034/// is invoked to pop the information about the block from the action impl. 9035void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 9036 // Leave the expression-evaluation context. 9037 DiscardCleanupsInEvaluationContext(); 9038 PopExpressionEvaluationContext(); 9039 9040 // Pop off CurBlock, handle nested blocks. 9041 PopDeclContext(); 9042 PopFunctionScopeInfo(); 9043} 9044 9045/// ActOnBlockStmtExpr - This is called when the body of a block statement 9046/// literal was successfully completed. ^(int x){...} 9047ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 9048 Stmt *Body, Scope *CurScope) { 9049 // If blocks are disabled, emit an error. 9050 if (!LangOpts.Blocks) 9051 Diag(CaretLoc, diag::err_blocks_disable); 9052 9053 // Leave the expression-evaluation context. 9054 if (hasAnyUnrecoverableErrorsInThisFunction()) 9055 DiscardCleanupsInEvaluationContext(); 9056 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 9057 PopExpressionEvaluationContext(); 9058 9059 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 9060 9061 PopDeclContext(); 9062 9063 QualType RetTy = Context.VoidTy; 9064 if (!BSI->ReturnType.isNull()) 9065 RetTy = BSI->ReturnType; 9066 9067 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 9068 QualType BlockTy; 9069 9070 // Set the captured variables on the block. 9071 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 9072 SmallVector<BlockDecl::Capture, 4> Captures; 9073 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 9074 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 9075 if (Cap.isThisCapture()) 9076 continue; 9077 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 9078 Cap.isNested(), Cap.getCopyExpr()); 9079 Captures.push_back(NewCap); 9080 } 9081 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 9082 BSI->CXXThisCaptureIndex != 0); 9083 9084 // If the user wrote a function type in some form, try to use that. 9085 if (!BSI->FunctionType.isNull()) { 9086 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 9087 9088 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 9089 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 9090 9091 // Turn protoless block types into nullary block types. 9092 if (isa<FunctionNoProtoType>(FTy)) { 9093 FunctionProtoType::ExtProtoInfo EPI; 9094 EPI.ExtInfo = Ext; 9095 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 9096 9097 // Otherwise, if we don't need to change anything about the function type, 9098 // preserve its sugar structure. 9099 } else if (FTy->getResultType() == RetTy && 9100 (!NoReturn || FTy->getNoReturnAttr())) { 9101 BlockTy = BSI->FunctionType; 9102 9103 // Otherwise, make the minimal modifications to the function type. 9104 } else { 9105 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 9106 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9107 EPI.TypeQuals = 0; // FIXME: silently? 9108 EPI.ExtInfo = Ext; 9109 BlockTy = Context.getFunctionType(RetTy, 9110 FPT->arg_type_begin(), 9111 FPT->getNumArgs(), 9112 EPI); 9113 } 9114 9115 // If we don't have a function type, just build one from nothing. 9116 } else { 9117 FunctionProtoType::ExtProtoInfo EPI; 9118 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 9119 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 9120 } 9121 9122 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 9123 BSI->TheDecl->param_end()); 9124 BlockTy = Context.getBlockPointerType(BlockTy); 9125 9126 // If needed, diagnose invalid gotos and switches in the block. 9127 if (getCurFunction()->NeedsScopeChecking() && 9128 !hasAnyUnrecoverableErrorsInThisFunction()) 9129 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 9130 9131 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 9132 9133 computeNRVO(Body, getCurBlock()); 9134 9135 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 9136 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 9137 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 9138 9139 // If the block isn't obviously global, i.e. it captures anything at 9140 // all, then we need to do a few things in the surrounding context: 9141 if (Result->getBlockDecl()->hasCaptures()) { 9142 // First, this expression has a new cleanup object. 9143 ExprCleanupObjects.push_back(Result->getBlockDecl()); 9144 ExprNeedsCleanups = true; 9145 9146 // It also gets a branch-protected scope if any of the captured 9147 // variables needs destruction. 9148 for (BlockDecl::capture_const_iterator 9149 ci = Result->getBlockDecl()->capture_begin(), 9150 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 9151 const VarDecl *var = ci->getVariable(); 9152 if (var->getType().isDestructedType() != QualType::DK_none) { 9153 getCurFunction()->setHasBranchProtectedScope(); 9154 break; 9155 } 9156 } 9157 } 9158 9159 return Owned(Result); 9160} 9161 9162ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 9163 Expr *E, ParsedType Ty, 9164 SourceLocation RPLoc) { 9165 TypeSourceInfo *TInfo; 9166 GetTypeFromParser(Ty, &TInfo); 9167 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 9168} 9169 9170ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 9171 Expr *E, TypeSourceInfo *TInfo, 9172 SourceLocation RPLoc) { 9173 Expr *OrigExpr = E; 9174 9175 // Get the va_list type 9176 QualType VaListType = Context.getBuiltinVaListType(); 9177 if (VaListType->isArrayType()) { 9178 // Deal with implicit array decay; for example, on x86-64, 9179 // va_list is an array, but it's supposed to decay to 9180 // a pointer for va_arg. 9181 VaListType = Context.getArrayDecayedType(VaListType); 9182 // Make sure the input expression also decays appropriately. 9183 ExprResult Result = UsualUnaryConversions(E); 9184 if (Result.isInvalid()) 9185 return ExprError(); 9186 E = Result.take(); 9187 } else { 9188 // Otherwise, the va_list argument must be an l-value because 9189 // it is modified by va_arg. 9190 if (!E->isTypeDependent() && 9191 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 9192 return ExprError(); 9193 } 9194 9195 if (!E->isTypeDependent() && 9196 !Context.hasSameType(VaListType, E->getType())) { 9197 return ExprError(Diag(E->getLocStart(), 9198 diag::err_first_argument_to_va_arg_not_of_type_va_list) 9199 << OrigExpr->getType() << E->getSourceRange()); 9200 } 9201 9202 if (!TInfo->getType()->isDependentType()) { 9203 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 9204 diag::err_second_parameter_to_va_arg_incomplete, 9205 TInfo->getTypeLoc())) 9206 return ExprError(); 9207 9208 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 9209 TInfo->getType(), 9210 diag::err_second_parameter_to_va_arg_abstract, 9211 TInfo->getTypeLoc())) 9212 return ExprError(); 9213 9214 if (!TInfo->getType().isPODType(Context)) { 9215 Diag(TInfo->getTypeLoc().getBeginLoc(), 9216 TInfo->getType()->isObjCLifetimeType() 9217 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 9218 : diag::warn_second_parameter_to_va_arg_not_pod) 9219 << TInfo->getType() 9220 << TInfo->getTypeLoc().getSourceRange(); 9221 } 9222 9223 // Check for va_arg where arguments of the given type will be promoted 9224 // (i.e. this va_arg is guaranteed to have undefined behavior). 9225 QualType PromoteType; 9226 if (TInfo->getType()->isPromotableIntegerType()) { 9227 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 9228 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 9229 PromoteType = QualType(); 9230 } 9231 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 9232 PromoteType = Context.DoubleTy; 9233 if (!PromoteType.isNull()) 9234 Diag(TInfo->getTypeLoc().getBeginLoc(), 9235 diag::warn_second_parameter_to_va_arg_never_compatible) 9236 << TInfo->getType() 9237 << PromoteType 9238 << TInfo->getTypeLoc().getSourceRange(); 9239 } 9240 9241 QualType T = TInfo->getType().getNonLValueExprType(Context); 9242 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 9243} 9244 9245ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 9246 // The type of __null will be int or long, depending on the size of 9247 // pointers on the target. 9248 QualType Ty; 9249 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 9250 if (pw == Context.getTargetInfo().getIntWidth()) 9251 Ty = Context.IntTy; 9252 else if (pw == Context.getTargetInfo().getLongWidth()) 9253 Ty = Context.LongTy; 9254 else if (pw == Context.getTargetInfo().getLongLongWidth()) 9255 Ty = Context.LongLongTy; 9256 else { 9257 llvm_unreachable("I don't know size of pointer!"); 9258 } 9259 9260 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 9261} 9262 9263static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 9264 Expr *SrcExpr, FixItHint &Hint) { 9265 if (!SemaRef.getLangOpts().ObjC1) 9266 return; 9267 9268 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 9269 if (!PT) 9270 return; 9271 9272 // Check if the destination is of type 'id'. 9273 if (!PT->isObjCIdType()) { 9274 // Check if the destination is the 'NSString' interface. 9275 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 9276 if (!ID || !ID->getIdentifier()->isStr("NSString")) 9277 return; 9278 } 9279 9280 // Ignore any parens, implicit casts (should only be 9281 // array-to-pointer decays), and not-so-opaque values. The last is 9282 // important for making this trigger for property assignments. 9283 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 9284 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 9285 if (OV->getSourceExpr()) 9286 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 9287 9288 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 9289 if (!SL || !SL->isAscii()) 9290 return; 9291 9292 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 9293} 9294 9295bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 9296 SourceLocation Loc, 9297 QualType DstType, QualType SrcType, 9298 Expr *SrcExpr, AssignmentAction Action, 9299 bool *Complained) { 9300 if (Complained) 9301 *Complained = false; 9302 9303 // Decode the result (notice that AST's are still created for extensions). 9304 bool CheckInferredResultType = false; 9305 bool isInvalid = false; 9306 unsigned DiagKind = 0; 9307 FixItHint Hint; 9308 ConversionFixItGenerator ConvHints; 9309 bool MayHaveConvFixit = false; 9310 bool MayHaveFunctionDiff = false; 9311 9312 switch (ConvTy) { 9313 case Compatible: return false; 9314 case PointerToInt: 9315 DiagKind = diag::ext_typecheck_convert_pointer_int; 9316 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9317 MayHaveConvFixit = true; 9318 break; 9319 case IntToPointer: 9320 DiagKind = diag::ext_typecheck_convert_int_pointer; 9321 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9322 MayHaveConvFixit = true; 9323 break; 9324 case IncompatiblePointer: 9325 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 9326 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 9327 CheckInferredResultType = DstType->isObjCObjectPointerType() && 9328 SrcType->isObjCObjectPointerType(); 9329 if (Hint.isNull() && !CheckInferredResultType) { 9330 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9331 } 9332 MayHaveConvFixit = true; 9333 break; 9334 case IncompatiblePointerSign: 9335 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 9336 break; 9337 case FunctionVoidPointer: 9338 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 9339 break; 9340 case IncompatiblePointerDiscardsQualifiers: { 9341 // Perform array-to-pointer decay if necessary. 9342 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 9343 9344 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 9345 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 9346 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 9347 DiagKind = diag::err_typecheck_incompatible_address_space; 9348 break; 9349 9350 9351 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 9352 DiagKind = diag::err_typecheck_incompatible_ownership; 9353 break; 9354 } 9355 9356 llvm_unreachable("unknown error case for discarding qualifiers!"); 9357 // fallthrough 9358 } 9359 case CompatiblePointerDiscardsQualifiers: 9360 // If the qualifiers lost were because we were applying the 9361 // (deprecated) C++ conversion from a string literal to a char* 9362 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 9363 // Ideally, this check would be performed in 9364 // checkPointerTypesForAssignment. However, that would require a 9365 // bit of refactoring (so that the second argument is an 9366 // expression, rather than a type), which should be done as part 9367 // of a larger effort to fix checkPointerTypesForAssignment for 9368 // C++ semantics. 9369 if (getLangOpts().CPlusPlus && 9370 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 9371 return false; 9372 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 9373 break; 9374 case IncompatibleNestedPointerQualifiers: 9375 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 9376 break; 9377 case IntToBlockPointer: 9378 DiagKind = diag::err_int_to_block_pointer; 9379 break; 9380 case IncompatibleBlockPointer: 9381 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 9382 break; 9383 case IncompatibleObjCQualifiedId: 9384 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 9385 // it can give a more specific diagnostic. 9386 DiagKind = diag::warn_incompatible_qualified_id; 9387 break; 9388 case IncompatibleVectors: 9389 DiagKind = diag::warn_incompatible_vectors; 9390 break; 9391 case IncompatibleObjCWeakRef: 9392 DiagKind = diag::err_arc_weak_unavailable_assign; 9393 break; 9394 case Incompatible: 9395 DiagKind = diag::err_typecheck_convert_incompatible; 9396 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9397 MayHaveConvFixit = true; 9398 isInvalid = true; 9399 MayHaveFunctionDiff = true; 9400 break; 9401 } 9402 9403 QualType FirstType, SecondType; 9404 switch (Action) { 9405 case AA_Assigning: 9406 case AA_Initializing: 9407 // The destination type comes first. 9408 FirstType = DstType; 9409 SecondType = SrcType; 9410 break; 9411 9412 case AA_Returning: 9413 case AA_Passing: 9414 case AA_Converting: 9415 case AA_Sending: 9416 case AA_Casting: 9417 // The source type comes first. 9418 FirstType = SrcType; 9419 SecondType = DstType; 9420 break; 9421 } 9422 9423 PartialDiagnostic FDiag = PDiag(DiagKind); 9424 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 9425 9426 // If we can fix the conversion, suggest the FixIts. 9427 assert(ConvHints.isNull() || Hint.isNull()); 9428 if (!ConvHints.isNull()) { 9429 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 9430 HE = ConvHints.Hints.end(); HI != HE; ++HI) 9431 FDiag << *HI; 9432 } else { 9433 FDiag << Hint; 9434 } 9435 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 9436 9437 if (MayHaveFunctionDiff) 9438 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 9439 9440 Diag(Loc, FDiag); 9441 9442 if (SecondType == Context.OverloadTy) 9443 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 9444 FirstType); 9445 9446 if (CheckInferredResultType) 9447 EmitRelatedResultTypeNote(SrcExpr); 9448 9449 if (Complained) 9450 *Complained = true; 9451 return isInvalid; 9452} 9453 9454ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9455 llvm::APSInt *Result) { 9456 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 9457 public: 9458 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 9459 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 9460 } 9461 } Diagnoser; 9462 9463 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 9464} 9465 9466ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9467 llvm::APSInt *Result, 9468 unsigned DiagID, 9469 bool AllowFold) { 9470 class IDDiagnoser : public VerifyICEDiagnoser { 9471 unsigned DiagID; 9472 9473 public: 9474 IDDiagnoser(unsigned DiagID) 9475 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 9476 9477 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 9478 S.Diag(Loc, DiagID) << SR; 9479 } 9480 } Diagnoser(DiagID); 9481 9482 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 9483} 9484 9485void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 9486 SourceRange SR) { 9487 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 9488} 9489 9490ExprResult 9491Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 9492 VerifyICEDiagnoser &Diagnoser, 9493 bool AllowFold) { 9494 SourceLocation DiagLoc = E->getLocStart(); 9495 9496 if (getLangOpts().CPlusPlus0x) { 9497 // C++11 [expr.const]p5: 9498 // If an expression of literal class type is used in a context where an 9499 // integral constant expression is required, then that class type shall 9500 // have a single non-explicit conversion function to an integral or 9501 // unscoped enumeration type 9502 ExprResult Converted; 9503 if (!Diagnoser.Suppress) { 9504 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 9505 public: 9506 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { } 9507 9508 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9509 QualType T) { 9510 return S.Diag(Loc, diag::err_ice_not_integral) << T; 9511 } 9512 9513 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 9514 SourceLocation Loc, 9515 QualType T) { 9516 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 9517 } 9518 9519 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 9520 SourceLocation Loc, 9521 QualType T, 9522 QualType ConvTy) { 9523 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 9524 } 9525 9526 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 9527 CXXConversionDecl *Conv, 9528 QualType ConvTy) { 9529 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 9530 << ConvTy->isEnumeralType() << ConvTy; 9531 } 9532 9533 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 9534 QualType T) { 9535 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 9536 } 9537 9538 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 9539 CXXConversionDecl *Conv, 9540 QualType ConvTy) { 9541 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 9542 << ConvTy->isEnumeralType() << ConvTy; 9543 } 9544 9545 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 9546 SourceLocation Loc, 9547 QualType T, 9548 QualType ConvTy) { 9549 return DiagnosticBuilder::getEmpty(); 9550 } 9551 } ConvertDiagnoser; 9552 9553 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 9554 ConvertDiagnoser, 9555 /*AllowScopedEnumerations*/ false); 9556 } else { 9557 // The caller wants to silently enquire whether this is an ICE. Don't 9558 // produce any diagnostics if it isn't. 9559 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser { 9560 public: 9561 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { } 9562 9563 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9564 QualType T) { 9565 return DiagnosticBuilder::getEmpty(); 9566 } 9567 9568 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 9569 SourceLocation Loc, 9570 QualType T) { 9571 return DiagnosticBuilder::getEmpty(); 9572 } 9573 9574 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 9575 SourceLocation Loc, 9576 QualType T, 9577 QualType ConvTy) { 9578 return DiagnosticBuilder::getEmpty(); 9579 } 9580 9581 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 9582 CXXConversionDecl *Conv, 9583 QualType ConvTy) { 9584 return DiagnosticBuilder::getEmpty(); 9585 } 9586 9587 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 9588 QualType T) { 9589 return DiagnosticBuilder::getEmpty(); 9590 } 9591 9592 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 9593 CXXConversionDecl *Conv, 9594 QualType ConvTy) { 9595 return DiagnosticBuilder::getEmpty(); 9596 } 9597 9598 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 9599 SourceLocation Loc, 9600 QualType T, 9601 QualType ConvTy) { 9602 return DiagnosticBuilder::getEmpty(); 9603 } 9604 } ConvertDiagnoser; 9605 9606 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 9607 ConvertDiagnoser, false); 9608 } 9609 if (Converted.isInvalid()) 9610 return Converted; 9611 E = Converted.take(); 9612 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 9613 return ExprError(); 9614 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 9615 // An ICE must be of integral or unscoped enumeration type. 9616 if (!Diagnoser.Suppress) 9617 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 9618 return ExprError(); 9619 } 9620 9621 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 9622 // in the non-ICE case. 9623 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) { 9624 if (Result) 9625 *Result = E->EvaluateKnownConstInt(Context); 9626 return Owned(E); 9627 } 9628 9629 Expr::EvalResult EvalResult; 9630 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 9631 EvalResult.Diag = &Notes; 9632 9633 // Try to evaluate the expression, and produce diagnostics explaining why it's 9634 // not a constant expression as a side-effect. 9635 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 9636 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 9637 9638 // In C++11, we can rely on diagnostics being produced for any expression 9639 // which is not a constant expression. If no diagnostics were produced, then 9640 // this is a constant expression. 9641 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) { 9642 if (Result) 9643 *Result = EvalResult.Val.getInt(); 9644 return Owned(E); 9645 } 9646 9647 // If our only note is the usual "invalid subexpression" note, just point 9648 // the caret at its location rather than producing an essentially 9649 // redundant note. 9650 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9651 diag::note_invalid_subexpr_in_const_expr) { 9652 DiagLoc = Notes[0].first; 9653 Notes.clear(); 9654 } 9655 9656 if (!Folded || !AllowFold) { 9657 if (!Diagnoser.Suppress) { 9658 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 9659 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9660 Diag(Notes[I].first, Notes[I].second); 9661 } 9662 9663 return ExprError(); 9664 } 9665 9666 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 9667 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9668 Diag(Notes[I].first, Notes[I].second); 9669 9670 if (Result) 9671 *Result = EvalResult.Val.getInt(); 9672 return Owned(E); 9673} 9674 9675namespace { 9676 // Handle the case where we conclude a expression which we speculatively 9677 // considered to be unevaluated is actually evaluated. 9678 class TransformToPE : public TreeTransform<TransformToPE> { 9679 typedef TreeTransform<TransformToPE> BaseTransform; 9680 9681 public: 9682 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 9683 9684 // Make sure we redo semantic analysis 9685 bool AlwaysRebuild() { return true; } 9686 9687 // Make sure we handle LabelStmts correctly. 9688 // FIXME: This does the right thing, but maybe we need a more general 9689 // fix to TreeTransform? 9690 StmtResult TransformLabelStmt(LabelStmt *S) { 9691 S->getDecl()->setStmt(0); 9692 return BaseTransform::TransformLabelStmt(S); 9693 } 9694 9695 // We need to special-case DeclRefExprs referring to FieldDecls which 9696 // are not part of a member pointer formation; normal TreeTransforming 9697 // doesn't catch this case because of the way we represent them in the AST. 9698 // FIXME: This is a bit ugly; is it really the best way to handle this 9699 // case? 9700 // 9701 // Error on DeclRefExprs referring to FieldDecls. 9702 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 9703 if (isa<FieldDecl>(E->getDecl()) && 9704 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated) 9705 return SemaRef.Diag(E->getLocation(), 9706 diag::err_invalid_non_static_member_use) 9707 << E->getDecl() << E->getSourceRange(); 9708 9709 return BaseTransform::TransformDeclRefExpr(E); 9710 } 9711 9712 // Exception: filter out member pointer formation 9713 ExprResult TransformUnaryOperator(UnaryOperator *E) { 9714 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 9715 return E; 9716 9717 return BaseTransform::TransformUnaryOperator(E); 9718 } 9719 9720 ExprResult TransformLambdaExpr(LambdaExpr *E) { 9721 // Lambdas never need to be transformed. 9722 return E; 9723 } 9724 }; 9725} 9726 9727ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) { 9728 assert(ExprEvalContexts.back().Context == Unevaluated && 9729 "Should only transform unevaluated expressions"); 9730 ExprEvalContexts.back().Context = 9731 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 9732 if (ExprEvalContexts.back().Context == Unevaluated) 9733 return E; 9734 return TransformToPE(*this).TransformExpr(E); 9735} 9736 9737void 9738Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 9739 Decl *LambdaContextDecl, 9740 bool IsDecltype) { 9741 ExprEvalContexts.push_back( 9742 ExpressionEvaluationContextRecord(NewContext, 9743 ExprCleanupObjects.size(), 9744 ExprNeedsCleanups, 9745 LambdaContextDecl, 9746 IsDecltype)); 9747 ExprNeedsCleanups = false; 9748 if (!MaybeODRUseExprs.empty()) 9749 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 9750} 9751 9752void Sema::PopExpressionEvaluationContext() { 9753 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 9754 9755 if (!Rec.Lambdas.empty()) { 9756 if (Rec.Context == Unevaluated) { 9757 // C++11 [expr.prim.lambda]p2: 9758 // A lambda-expression shall not appear in an unevaluated operand 9759 // (Clause 5). 9760 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 9761 Diag(Rec.Lambdas[I]->getLocStart(), 9762 diag::err_lambda_unevaluated_operand); 9763 } else { 9764 // Mark the capture expressions odr-used. This was deferred 9765 // during lambda expression creation. 9766 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 9767 LambdaExpr *Lambda = Rec.Lambdas[I]; 9768 for (LambdaExpr::capture_init_iterator 9769 C = Lambda->capture_init_begin(), 9770 CEnd = Lambda->capture_init_end(); 9771 C != CEnd; ++C) { 9772 MarkDeclarationsReferencedInExpr(*C); 9773 } 9774 } 9775 } 9776 } 9777 9778 // When are coming out of an unevaluated context, clear out any 9779 // temporaries that we may have created as part of the evaluation of 9780 // the expression in that context: they aren't relevant because they 9781 // will never be constructed. 9782 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) { 9783 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 9784 ExprCleanupObjects.end()); 9785 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 9786 CleanupVarDeclMarking(); 9787 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 9788 // Otherwise, merge the contexts together. 9789 } else { 9790 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 9791 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 9792 Rec.SavedMaybeODRUseExprs.end()); 9793 } 9794 9795 // Pop the current expression evaluation context off the stack. 9796 ExprEvalContexts.pop_back(); 9797} 9798 9799void Sema::DiscardCleanupsInEvaluationContext() { 9800 ExprCleanupObjects.erase( 9801 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 9802 ExprCleanupObjects.end()); 9803 ExprNeedsCleanups = false; 9804 MaybeODRUseExprs.clear(); 9805} 9806 9807ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 9808 if (!E->getType()->isVariablyModifiedType()) 9809 return E; 9810 return TranformToPotentiallyEvaluated(E); 9811} 9812 9813static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 9814 // Do not mark anything as "used" within a dependent context; wait for 9815 // an instantiation. 9816 if (SemaRef.CurContext->isDependentContext()) 9817 return false; 9818 9819 switch (SemaRef.ExprEvalContexts.back().Context) { 9820 case Sema::Unevaluated: 9821 // We are in an expression that is not potentially evaluated; do nothing. 9822 // (Depending on how you read the standard, we actually do need to do 9823 // something here for null pointer constants, but the standard's 9824 // definition of a null pointer constant is completely crazy.) 9825 return false; 9826 9827 case Sema::ConstantEvaluated: 9828 case Sema::PotentiallyEvaluated: 9829 // We are in a potentially evaluated expression (or a constant-expression 9830 // in C++03); we need to do implicit template instantiation, implicitly 9831 // define class members, and mark most declarations as used. 9832 return true; 9833 9834 case Sema::PotentiallyEvaluatedIfUsed: 9835 // Referenced declarations will only be used if the construct in the 9836 // containing expression is used. 9837 return false; 9838 } 9839 llvm_unreachable("Invalid context"); 9840} 9841 9842/// \brief Mark a function referenced, and check whether it is odr-used 9843/// (C++ [basic.def.odr]p2, C99 6.9p3) 9844void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 9845 assert(Func && "No function?"); 9846 9847 Func->setReferenced(); 9848 9849 // Don't mark this function as used multiple times, unless it's a constexpr 9850 // function which we need to instantiate. 9851 if (Func->isUsed(false) && 9852 !(Func->isConstexpr() && !Func->getBody() && 9853 Func->isImplicitlyInstantiable())) 9854 return; 9855 9856 if (!IsPotentiallyEvaluatedContext(*this)) 9857 return; 9858 9859 // Note that this declaration has been used. 9860 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 9861 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 9862 if (Constructor->isDefaultConstructor()) { 9863 if (Constructor->isTrivial()) 9864 return; 9865 if (!Constructor->isUsed(false)) 9866 DefineImplicitDefaultConstructor(Loc, Constructor); 9867 } else if (Constructor->isCopyConstructor()) { 9868 if (!Constructor->isUsed(false)) 9869 DefineImplicitCopyConstructor(Loc, Constructor); 9870 } else if (Constructor->isMoveConstructor()) { 9871 if (!Constructor->isUsed(false)) 9872 DefineImplicitMoveConstructor(Loc, Constructor); 9873 } 9874 } 9875 9876 MarkVTableUsed(Loc, Constructor->getParent()); 9877 } else if (CXXDestructorDecl *Destructor = 9878 dyn_cast<CXXDestructorDecl>(Func)) { 9879 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 9880 !Destructor->isUsed(false)) 9881 DefineImplicitDestructor(Loc, Destructor); 9882 if (Destructor->isVirtual()) 9883 MarkVTableUsed(Loc, Destructor->getParent()); 9884 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 9885 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 9886 MethodDecl->isOverloadedOperator() && 9887 MethodDecl->getOverloadedOperator() == OO_Equal) { 9888 if (!MethodDecl->isUsed(false)) { 9889 if (MethodDecl->isCopyAssignmentOperator()) 9890 DefineImplicitCopyAssignment(Loc, MethodDecl); 9891 else 9892 DefineImplicitMoveAssignment(Loc, MethodDecl); 9893 } 9894 } else if (isa<CXXConversionDecl>(MethodDecl) && 9895 MethodDecl->getParent()->isLambda()) { 9896 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 9897 if (Conversion->isLambdaToBlockPointerConversion()) 9898 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 9899 else 9900 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 9901 } else if (MethodDecl->isVirtual()) 9902 MarkVTableUsed(Loc, MethodDecl->getParent()); 9903 } 9904 9905 // Recursive functions should be marked when used from another function. 9906 // FIXME: Is this really right? 9907 if (CurContext == Func) return; 9908 9909 // Instantiate the exception specification for any function which is 9910 // used: CodeGen will need it. 9911 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 9912 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated) 9913 InstantiateExceptionSpec(Loc, Func); 9914 9915 // Implicit instantiation of function templates and member functions of 9916 // class templates. 9917 if (Func->isImplicitlyInstantiable()) { 9918 bool AlreadyInstantiated = false; 9919 SourceLocation PointOfInstantiation = Loc; 9920 if (FunctionTemplateSpecializationInfo *SpecInfo 9921 = Func->getTemplateSpecializationInfo()) { 9922 if (SpecInfo->getPointOfInstantiation().isInvalid()) 9923 SpecInfo->setPointOfInstantiation(Loc); 9924 else if (SpecInfo->getTemplateSpecializationKind() 9925 == TSK_ImplicitInstantiation) { 9926 AlreadyInstantiated = true; 9927 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 9928 } 9929 } else if (MemberSpecializationInfo *MSInfo 9930 = Func->getMemberSpecializationInfo()) { 9931 if (MSInfo->getPointOfInstantiation().isInvalid()) 9932 MSInfo->setPointOfInstantiation(Loc); 9933 else if (MSInfo->getTemplateSpecializationKind() 9934 == TSK_ImplicitInstantiation) { 9935 AlreadyInstantiated = true; 9936 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 9937 } 9938 } 9939 9940 if (!AlreadyInstantiated || Func->isConstexpr()) { 9941 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 9942 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass()) 9943 PendingLocalImplicitInstantiations.push_back( 9944 std::make_pair(Func, PointOfInstantiation)); 9945 else if (Func->isConstexpr()) 9946 // Do not defer instantiations of constexpr functions, to avoid the 9947 // expression evaluator needing to call back into Sema if it sees a 9948 // call to such a function. 9949 InstantiateFunctionDefinition(PointOfInstantiation, Func); 9950 else { 9951 PendingInstantiations.push_back(std::make_pair(Func, 9952 PointOfInstantiation)); 9953 // Notify the consumer that a function was implicitly instantiated. 9954 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 9955 } 9956 } 9957 } else { 9958 // Walk redefinitions, as some of them may be instantiable. 9959 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 9960 e(Func->redecls_end()); i != e; ++i) { 9961 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 9962 MarkFunctionReferenced(Loc, *i); 9963 } 9964 } 9965 9966 // Keep track of used but undefined functions. 9967 if (!Func->isPure() && !Func->hasBody() && 9968 Func->getLinkage() != ExternalLinkage) { 9969 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()]; 9970 if (old.isInvalid()) old = Loc; 9971 } 9972 9973 Func->setUsed(true); 9974} 9975 9976static void 9977diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 9978 VarDecl *var, DeclContext *DC) { 9979 DeclContext *VarDC = var->getDeclContext(); 9980 9981 // If the parameter still belongs to the translation unit, then 9982 // we're actually just using one parameter in the declaration of 9983 // the next. 9984 if (isa<ParmVarDecl>(var) && 9985 isa<TranslationUnitDecl>(VarDC)) 9986 return; 9987 9988 // For C code, don't diagnose about capture if we're not actually in code 9989 // right now; it's impossible to write a non-constant expression outside of 9990 // function context, so we'll get other (more useful) diagnostics later. 9991 // 9992 // For C++, things get a bit more nasty... it would be nice to suppress this 9993 // diagnostic for certain cases like using a local variable in an array bound 9994 // for a member of a local class, but the correct predicate is not obvious. 9995 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 9996 return; 9997 9998 if (isa<CXXMethodDecl>(VarDC) && 9999 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 10000 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 10001 << var->getIdentifier(); 10002 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 10003 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 10004 << var->getIdentifier() << fn->getDeclName(); 10005 } else if (isa<BlockDecl>(VarDC)) { 10006 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 10007 << var->getIdentifier(); 10008 } else { 10009 // FIXME: Is there any other context where a local variable can be 10010 // declared? 10011 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 10012 << var->getIdentifier(); 10013 } 10014 10015 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 10016 << var->getIdentifier(); 10017 10018 // FIXME: Add additional diagnostic info about class etc. which prevents 10019 // capture. 10020} 10021 10022/// \brief Capture the given variable in the given lambda expression. 10023static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 10024 VarDecl *Var, QualType FieldType, 10025 QualType DeclRefType, 10026 SourceLocation Loc) { 10027 CXXRecordDecl *Lambda = LSI->Lambda; 10028 10029 // Build the non-static data member. 10030 FieldDecl *Field 10031 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 10032 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10033 0, false, false); 10034 Field->setImplicit(true); 10035 Field->setAccess(AS_private); 10036 Lambda->addDecl(Field); 10037 10038 // C++11 [expr.prim.lambda]p21: 10039 // When the lambda-expression is evaluated, the entities that 10040 // are captured by copy are used to direct-initialize each 10041 // corresponding non-static data member of the resulting closure 10042 // object. (For array members, the array elements are 10043 // direct-initialized in increasing subscript order.) These 10044 // initializations are performed in the (unspecified) order in 10045 // which the non-static data members are declared. 10046 10047 // Introduce a new evaluation context for the initialization, so 10048 // that temporaries introduced as part of the capture are retained 10049 // to be re-"exported" from the lambda expression itself. 10050 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 10051 10052 // C++ [expr.prim.labda]p12: 10053 // An entity captured by a lambda-expression is odr-used (3.2) in 10054 // the scope containing the lambda-expression. 10055 Expr *Ref = new (S.Context) DeclRefExpr(Var, false, DeclRefType, 10056 VK_LValue, Loc); 10057 Var->setReferenced(true); 10058 Var->setUsed(true); 10059 10060 // When the field has array type, create index variables for each 10061 // dimension of the array. We use these index variables to subscript 10062 // the source array, and other clients (e.g., CodeGen) will perform 10063 // the necessary iteration with these index variables. 10064 SmallVector<VarDecl *, 4> IndexVariables; 10065 QualType BaseType = FieldType; 10066 QualType SizeType = S.Context.getSizeType(); 10067 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 10068 while (const ConstantArrayType *Array 10069 = S.Context.getAsConstantArrayType(BaseType)) { 10070 // Create the iteration variable for this array index. 10071 IdentifierInfo *IterationVarName = 0; 10072 { 10073 SmallString<8> Str; 10074 llvm::raw_svector_ostream OS(Str); 10075 OS << "__i" << IndexVariables.size(); 10076 IterationVarName = &S.Context.Idents.get(OS.str()); 10077 } 10078 VarDecl *IterationVar 10079 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 10080 IterationVarName, SizeType, 10081 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 10082 SC_None, SC_None); 10083 IndexVariables.push_back(IterationVar); 10084 LSI->ArrayIndexVars.push_back(IterationVar); 10085 10086 // Create a reference to the iteration variable. 10087 ExprResult IterationVarRef 10088 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 10089 assert(!IterationVarRef.isInvalid() && 10090 "Reference to invented variable cannot fail!"); 10091 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 10092 assert(!IterationVarRef.isInvalid() && 10093 "Conversion of invented variable cannot fail!"); 10094 10095 // Subscript the array with this iteration variable. 10096 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 10097 Ref, Loc, IterationVarRef.take(), Loc); 10098 if (Subscript.isInvalid()) { 10099 S.CleanupVarDeclMarking(); 10100 S.DiscardCleanupsInEvaluationContext(); 10101 S.PopExpressionEvaluationContext(); 10102 return ExprError(); 10103 } 10104 10105 Ref = Subscript.take(); 10106 BaseType = Array->getElementType(); 10107 } 10108 10109 // Construct the entity that we will be initializing. For an array, this 10110 // will be first element in the array, which may require several levels 10111 // of array-subscript entities. 10112 SmallVector<InitializedEntity, 4> Entities; 10113 Entities.reserve(1 + IndexVariables.size()); 10114 Entities.push_back( 10115 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 10116 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 10117 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 10118 0, 10119 Entities.back())); 10120 10121 InitializationKind InitKind 10122 = InitializationKind::CreateDirect(Loc, Loc, Loc); 10123 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1); 10124 ExprResult Result(true); 10125 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1)) 10126 Result = Init.Perform(S, Entities.back(), InitKind, 10127 MultiExprArg(S, &Ref, 1)); 10128 10129 // If this initialization requires any cleanups (e.g., due to a 10130 // default argument to a copy constructor), note that for the 10131 // lambda. 10132 if (S.ExprNeedsCleanups) 10133 LSI->ExprNeedsCleanups = true; 10134 10135 // Exit the expression evaluation context used for the capture. 10136 S.CleanupVarDeclMarking(); 10137 S.DiscardCleanupsInEvaluationContext(); 10138 S.PopExpressionEvaluationContext(); 10139 return Result; 10140} 10141 10142bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 10143 TryCaptureKind Kind, SourceLocation EllipsisLoc, 10144 bool BuildAndDiagnose, 10145 QualType &CaptureType, 10146 QualType &DeclRefType) { 10147 bool Nested = false; 10148 10149 DeclContext *DC = CurContext; 10150 if (Var->getDeclContext() == DC) return true; 10151 if (!Var->hasLocalStorage()) return true; 10152 10153 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 10154 10155 // Walk up the stack to determine whether we can capture the variable, 10156 // performing the "simple" checks that don't depend on type. We stop when 10157 // we've either hit the declared scope of the variable or find an existing 10158 // capture of that variable. 10159 CaptureType = Var->getType(); 10160 DeclRefType = CaptureType.getNonReferenceType(); 10161 bool Explicit = (Kind != TryCapture_Implicit); 10162 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 10163 do { 10164 // Only block literals and lambda expressions can capture; other 10165 // scopes don't work. 10166 DeclContext *ParentDC; 10167 if (isa<BlockDecl>(DC)) 10168 ParentDC = DC->getParent(); 10169 else if (isa<CXXMethodDecl>(DC) && 10170 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 10171 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 10172 ParentDC = DC->getParent()->getParent(); 10173 else { 10174 if (BuildAndDiagnose) 10175 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 10176 return true; 10177 } 10178 10179 CapturingScopeInfo *CSI = 10180 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 10181 10182 // Check whether we've already captured it. 10183 if (CSI->CaptureMap.count(Var)) { 10184 // If we found a capture, any subcaptures are nested. 10185 Nested = true; 10186 10187 // Retrieve the capture type for this variable. 10188 CaptureType = CSI->getCapture(Var).getCaptureType(); 10189 10190 // Compute the type of an expression that refers to this variable. 10191 DeclRefType = CaptureType.getNonReferenceType(); 10192 10193 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 10194 if (Cap.isCopyCapture() && 10195 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 10196 DeclRefType.addConst(); 10197 break; 10198 } 10199 10200 bool IsBlock = isa<BlockScopeInfo>(CSI); 10201 bool IsLambda = !IsBlock; 10202 10203 // Lambdas are not allowed to capture unnamed variables 10204 // (e.g. anonymous unions). 10205 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 10206 // assuming that's the intent. 10207 if (IsLambda && !Var->getDeclName()) { 10208 if (BuildAndDiagnose) { 10209 Diag(Loc, diag::err_lambda_capture_anonymous_var); 10210 Diag(Var->getLocation(), diag::note_declared_at); 10211 } 10212 return true; 10213 } 10214 10215 // Prohibit variably-modified types; they're difficult to deal with. 10216 if (Var->getType()->isVariablyModifiedType()) { 10217 if (BuildAndDiagnose) { 10218 if (IsBlock) 10219 Diag(Loc, diag::err_ref_vm_type); 10220 else 10221 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 10222 Diag(Var->getLocation(), diag::note_previous_decl) 10223 << Var->getDeclName(); 10224 } 10225 return true; 10226 } 10227 10228 // Lambdas are not allowed to capture __block variables; they don't 10229 // support the expected semantics. 10230 if (IsLambda && HasBlocksAttr) { 10231 if (BuildAndDiagnose) { 10232 Diag(Loc, diag::err_lambda_capture_block) 10233 << Var->getDeclName(); 10234 Diag(Var->getLocation(), diag::note_previous_decl) 10235 << Var->getDeclName(); 10236 } 10237 return true; 10238 } 10239 10240 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 10241 // No capture-default 10242 if (BuildAndDiagnose) { 10243 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 10244 Diag(Var->getLocation(), diag::note_previous_decl) 10245 << Var->getDeclName(); 10246 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 10247 diag::note_lambda_decl); 10248 } 10249 return true; 10250 } 10251 10252 FunctionScopesIndex--; 10253 DC = ParentDC; 10254 Explicit = false; 10255 } while (!Var->getDeclContext()->Equals(DC)); 10256 10257 // Walk back down the scope stack, computing the type of the capture at 10258 // each step, checking type-specific requirements, and adding captures if 10259 // requested. 10260 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 10261 ++I) { 10262 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 10263 10264 // Compute the type of the capture and of a reference to the capture within 10265 // this scope. 10266 if (isa<BlockScopeInfo>(CSI)) { 10267 Expr *CopyExpr = 0; 10268 bool ByRef = false; 10269 10270 // Blocks are not allowed to capture arrays. 10271 if (CaptureType->isArrayType()) { 10272 if (BuildAndDiagnose) { 10273 Diag(Loc, diag::err_ref_array_type); 10274 Diag(Var->getLocation(), diag::note_previous_decl) 10275 << Var->getDeclName(); 10276 } 10277 return true; 10278 } 10279 10280 // Forbid the block-capture of autoreleasing variables. 10281 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 10282 if (BuildAndDiagnose) { 10283 Diag(Loc, diag::err_arc_autoreleasing_capture) 10284 << /*block*/ 0; 10285 Diag(Var->getLocation(), diag::note_previous_decl) 10286 << Var->getDeclName(); 10287 } 10288 return true; 10289 } 10290 10291 if (HasBlocksAttr || CaptureType->isReferenceType()) { 10292 // Block capture by reference does not change the capture or 10293 // declaration reference types. 10294 ByRef = true; 10295 } else { 10296 // Block capture by copy introduces 'const'. 10297 CaptureType = CaptureType.getNonReferenceType().withConst(); 10298 DeclRefType = CaptureType; 10299 10300 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 10301 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 10302 // The capture logic needs the destructor, so make sure we mark it. 10303 // Usually this is unnecessary because most local variables have 10304 // their destructors marked at declaration time, but parameters are 10305 // an exception because it's technically only the call site that 10306 // actually requires the destructor. 10307 if (isa<ParmVarDecl>(Var)) 10308 FinalizeVarWithDestructor(Var, Record); 10309 10310 // According to the blocks spec, the capture of a variable from 10311 // the stack requires a const copy constructor. This is not true 10312 // of the copy/move done to move a __block variable to the heap. 10313 Expr *DeclRef = new (Context) DeclRefExpr(Var, false, 10314 DeclRefType.withConst(), 10315 VK_LValue, Loc); 10316 ExprResult Result 10317 = PerformCopyInitialization( 10318 InitializedEntity::InitializeBlock(Var->getLocation(), 10319 CaptureType, false), 10320 Loc, Owned(DeclRef)); 10321 10322 // Build a full-expression copy expression if initialization 10323 // succeeded and used a non-trivial constructor. Recover from 10324 // errors by pretending that the copy isn't necessary. 10325 if (!Result.isInvalid() && 10326 !cast<CXXConstructExpr>(Result.get())->getConstructor() 10327 ->isTrivial()) { 10328 Result = MaybeCreateExprWithCleanups(Result); 10329 CopyExpr = Result.take(); 10330 } 10331 } 10332 } 10333 } 10334 10335 // Actually capture the variable. 10336 if (BuildAndDiagnose) 10337 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 10338 SourceLocation(), CaptureType, CopyExpr); 10339 Nested = true; 10340 continue; 10341 } 10342 10343 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 10344 10345 // Determine whether we are capturing by reference or by value. 10346 bool ByRef = false; 10347 if (I == N - 1 && Kind != TryCapture_Implicit) { 10348 ByRef = (Kind == TryCapture_ExplicitByRef); 10349 } else { 10350 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 10351 } 10352 10353 // Compute the type of the field that will capture this variable. 10354 if (ByRef) { 10355 // C++11 [expr.prim.lambda]p15: 10356 // An entity is captured by reference if it is implicitly or 10357 // explicitly captured but not captured by copy. It is 10358 // unspecified whether additional unnamed non-static data 10359 // members are declared in the closure type for entities 10360 // captured by reference. 10361 // 10362 // FIXME: It is not clear whether we want to build an lvalue reference 10363 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 10364 // to do the former, while EDG does the latter. Core issue 1249 will 10365 // clarify, but for now we follow GCC because it's a more permissive and 10366 // easily defensible position. 10367 CaptureType = Context.getLValueReferenceType(DeclRefType); 10368 } else { 10369 // C++11 [expr.prim.lambda]p14: 10370 // For each entity captured by copy, an unnamed non-static 10371 // data member is declared in the closure type. The 10372 // declaration order of these members is unspecified. The type 10373 // of such a data member is the type of the corresponding 10374 // captured entity if the entity is not a reference to an 10375 // object, or the referenced type otherwise. [Note: If the 10376 // captured entity is a reference to a function, the 10377 // corresponding data member is also a reference to a 10378 // function. - end note ] 10379 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 10380 if (!RefType->getPointeeType()->isFunctionType()) 10381 CaptureType = RefType->getPointeeType(); 10382 } 10383 10384 // Forbid the lambda copy-capture of autoreleasing variables. 10385 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 10386 if (BuildAndDiagnose) { 10387 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 10388 Diag(Var->getLocation(), diag::note_previous_decl) 10389 << Var->getDeclName(); 10390 } 10391 return true; 10392 } 10393 } 10394 10395 // Capture this variable in the lambda. 10396 Expr *CopyExpr = 0; 10397 if (BuildAndDiagnose) { 10398 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 10399 DeclRefType, Loc); 10400 if (!Result.isInvalid()) 10401 CopyExpr = Result.take(); 10402 } 10403 10404 // Compute the type of a reference to this captured variable. 10405 if (ByRef) 10406 DeclRefType = CaptureType.getNonReferenceType(); 10407 else { 10408 // C++ [expr.prim.lambda]p5: 10409 // The closure type for a lambda-expression has a public inline 10410 // function call operator [...]. This function call operator is 10411 // declared const (9.3.1) if and only if the lambda-expression’s 10412 // parameter-declaration-clause is not followed by mutable. 10413 DeclRefType = CaptureType.getNonReferenceType(); 10414 if (!LSI->Mutable && !CaptureType->isReferenceType()) 10415 DeclRefType.addConst(); 10416 } 10417 10418 // Add the capture. 10419 if (BuildAndDiagnose) 10420 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 10421 EllipsisLoc, CaptureType, CopyExpr); 10422 Nested = true; 10423 } 10424 10425 return false; 10426} 10427 10428bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 10429 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 10430 QualType CaptureType; 10431 QualType DeclRefType; 10432 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 10433 /*BuildAndDiagnose=*/true, CaptureType, 10434 DeclRefType); 10435} 10436 10437QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 10438 QualType CaptureType; 10439 QualType DeclRefType; 10440 10441 // Determine whether we can capture this variable. 10442 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 10443 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 10444 return QualType(); 10445 10446 return DeclRefType; 10447} 10448 10449static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 10450 SourceLocation Loc) { 10451 // Keep track of used but undefined variables. 10452 // FIXME: We shouldn't suppress this warning for static data members. 10453 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 10454 Var->getLinkage() != ExternalLinkage && 10455 !(Var->isStaticDataMember() && Var->hasInit())) { 10456 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()]; 10457 if (old.isInvalid()) old = Loc; 10458 } 10459 10460 SemaRef.tryCaptureVariable(Var, Loc); 10461 10462 Var->setUsed(true); 10463} 10464 10465void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 10466 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 10467 // an object that satisfies the requirements for appearing in a 10468 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 10469 // is immediately applied." This function handles the lvalue-to-rvalue 10470 // conversion part. 10471 MaybeODRUseExprs.erase(E->IgnoreParens()); 10472} 10473 10474ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 10475 if (!Res.isUsable()) 10476 return Res; 10477 10478 // If a constant-expression is a reference to a variable where we delay 10479 // deciding whether it is an odr-use, just assume we will apply the 10480 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 10481 // (a non-type template argument), we have special handling anyway. 10482 UpdateMarkingForLValueToRValue(Res.get()); 10483 return Res; 10484} 10485 10486void Sema::CleanupVarDeclMarking() { 10487 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 10488 e = MaybeODRUseExprs.end(); 10489 i != e; ++i) { 10490 VarDecl *Var; 10491 SourceLocation Loc; 10492 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 10493 Var = cast<VarDecl>(DRE->getDecl()); 10494 Loc = DRE->getLocation(); 10495 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 10496 Var = cast<VarDecl>(ME->getMemberDecl()); 10497 Loc = ME->getMemberLoc(); 10498 } else { 10499 llvm_unreachable("Unexpcted expression"); 10500 } 10501 10502 MarkVarDeclODRUsed(*this, Var, Loc); 10503 } 10504 10505 MaybeODRUseExprs.clear(); 10506} 10507 10508// Mark a VarDecl referenced, and perform the necessary handling to compute 10509// odr-uses. 10510static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 10511 VarDecl *Var, Expr *E) { 10512 Var->setReferenced(); 10513 10514 if (!IsPotentiallyEvaluatedContext(SemaRef)) 10515 return; 10516 10517 // Implicit instantiation of static data members of class templates. 10518 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 10519 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 10520 assert(MSInfo && "Missing member specialization information?"); 10521 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 10522 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 10523 (!AlreadyInstantiated || 10524 Var->isUsableInConstantExpressions(SemaRef.Context))) { 10525 if (!AlreadyInstantiated) { 10526 // This is a modification of an existing AST node. Notify listeners. 10527 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 10528 L->StaticDataMemberInstantiated(Var); 10529 MSInfo->setPointOfInstantiation(Loc); 10530 } 10531 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10532 if (Var->isUsableInConstantExpressions(SemaRef.Context)) 10533 // Do not defer instantiations of variables which could be used in a 10534 // constant expression. 10535 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 10536 else 10537 SemaRef.PendingInstantiations.push_back( 10538 std::make_pair(Var, PointOfInstantiation)); 10539 } 10540 } 10541 10542 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 10543 // an object that satisfies the requirements for appearing in a 10544 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 10545 // is immediately applied." We check the first part here, and 10546 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 10547 // Note that we use the C++11 definition everywhere because nothing in 10548 // C++03 depends on whether we get the C++03 version correct. This does not 10549 // apply to references, since they are not objects. 10550 const VarDecl *DefVD; 10551 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() && 10552 Var->isUsableInConstantExpressions(SemaRef.Context) && 10553 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) 10554 SemaRef.MaybeODRUseExprs.insert(E); 10555 else 10556 MarkVarDeclODRUsed(SemaRef, Var, Loc); 10557} 10558 10559/// \brief Mark a variable referenced, and check whether it is odr-used 10560/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 10561/// used directly for normal expressions referring to VarDecl. 10562void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 10563 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 10564} 10565 10566static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 10567 Decl *D, Expr *E) { 10568 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 10569 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 10570 return; 10571 } 10572 10573 SemaRef.MarkAnyDeclReferenced(Loc, D); 10574} 10575 10576/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 10577void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 10578 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E); 10579} 10580 10581/// \brief Perform reference-marking and odr-use handling for a MemberExpr. 10582void Sema::MarkMemberReferenced(MemberExpr *E) { 10583 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E); 10584} 10585 10586/// \brief Perform marking for a reference to an arbitrary declaration. It 10587/// marks the declaration referenced, and performs odr-use checking for functions 10588/// and variables. This method should not be used when building an normal 10589/// expression which refers to a variable. 10590void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) { 10591 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 10592 MarkVariableReferenced(Loc, VD); 10593 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 10594 MarkFunctionReferenced(Loc, FD); 10595 else 10596 D->setReferenced(); 10597} 10598 10599namespace { 10600 // Mark all of the declarations referenced 10601 // FIXME: Not fully implemented yet! We need to have a better understanding 10602 // of when we're entering 10603 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 10604 Sema &S; 10605 SourceLocation Loc; 10606 10607 public: 10608 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 10609 10610 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 10611 10612 bool TraverseTemplateArgument(const TemplateArgument &Arg); 10613 bool TraverseRecordType(RecordType *T); 10614 }; 10615} 10616 10617bool MarkReferencedDecls::TraverseTemplateArgument( 10618 const TemplateArgument &Arg) { 10619 if (Arg.getKind() == TemplateArgument::Declaration) { 10620 if (Decl *D = Arg.getAsDecl()) 10621 S.MarkAnyDeclReferenced(Loc, D); 10622 } 10623 10624 return Inherited::TraverseTemplateArgument(Arg); 10625} 10626 10627bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 10628 if (ClassTemplateSpecializationDecl *Spec 10629 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 10630 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 10631 return TraverseTemplateArguments(Args.data(), Args.size()); 10632 } 10633 10634 return true; 10635} 10636 10637void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 10638 MarkReferencedDecls Marker(*this, Loc); 10639 Marker.TraverseType(Context.getCanonicalType(T)); 10640} 10641 10642namespace { 10643 /// \brief Helper class that marks all of the declarations referenced by 10644 /// potentially-evaluated subexpressions as "referenced". 10645 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 10646 Sema &S; 10647 bool SkipLocalVariables; 10648 10649 public: 10650 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 10651 10652 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 10653 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 10654 10655 void VisitDeclRefExpr(DeclRefExpr *E) { 10656 // If we were asked not to visit local variables, don't. 10657 if (SkipLocalVariables) { 10658 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 10659 if (VD->hasLocalStorage()) 10660 return; 10661 } 10662 10663 S.MarkDeclRefReferenced(E); 10664 } 10665 10666 void VisitMemberExpr(MemberExpr *E) { 10667 S.MarkMemberReferenced(E); 10668 Inherited::VisitMemberExpr(E); 10669 } 10670 10671 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 10672 S.MarkFunctionReferenced(E->getLocStart(), 10673 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 10674 Visit(E->getSubExpr()); 10675 } 10676 10677 void VisitCXXNewExpr(CXXNewExpr *E) { 10678 if (E->getOperatorNew()) 10679 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 10680 if (E->getOperatorDelete()) 10681 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 10682 Inherited::VisitCXXNewExpr(E); 10683 } 10684 10685 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 10686 if (E->getOperatorDelete()) 10687 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 10688 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 10689 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 10690 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 10691 S.MarkFunctionReferenced(E->getLocStart(), 10692 S.LookupDestructor(Record)); 10693 } 10694 10695 Inherited::VisitCXXDeleteExpr(E); 10696 } 10697 10698 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10699 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 10700 Inherited::VisitCXXConstructExpr(E); 10701 } 10702 10703 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 10704 Visit(E->getExpr()); 10705 } 10706 10707 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10708 Inherited::VisitImplicitCastExpr(E); 10709 10710 if (E->getCastKind() == CK_LValueToRValue) 10711 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 10712 } 10713 }; 10714} 10715 10716/// \brief Mark any declarations that appear within this expression or any 10717/// potentially-evaluated subexpressions as "referenced". 10718/// 10719/// \param SkipLocalVariables If true, don't mark local variables as 10720/// 'referenced'. 10721void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 10722 bool SkipLocalVariables) { 10723 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 10724} 10725 10726/// \brief Emit a diagnostic that describes an effect on the run-time behavior 10727/// of the program being compiled. 10728/// 10729/// This routine emits the given diagnostic when the code currently being 10730/// type-checked is "potentially evaluated", meaning that there is a 10731/// possibility that the code will actually be executable. Code in sizeof() 10732/// expressions, code used only during overload resolution, etc., are not 10733/// potentially evaluated. This routine will suppress such diagnostics or, 10734/// in the absolutely nutty case of potentially potentially evaluated 10735/// expressions (C++ typeid), queue the diagnostic to potentially emit it 10736/// later. 10737/// 10738/// This routine should be used for all diagnostics that describe the run-time 10739/// behavior of a program, such as passing a non-POD value through an ellipsis. 10740/// Failure to do so will likely result in spurious diagnostics or failures 10741/// during overload resolution or within sizeof/alignof/typeof/typeid. 10742bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 10743 const PartialDiagnostic &PD) { 10744 switch (ExprEvalContexts.back().Context) { 10745 case Unevaluated: 10746 // The argument will never be evaluated, so don't complain. 10747 break; 10748 10749 case ConstantEvaluated: 10750 // Relevant diagnostics should be produced by constant evaluation. 10751 break; 10752 10753 case PotentiallyEvaluated: 10754 case PotentiallyEvaluatedIfUsed: 10755 if (Statement && getCurFunctionOrMethodDecl()) { 10756 FunctionScopes.back()->PossiblyUnreachableDiags. 10757 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 10758 } 10759 else 10760 Diag(Loc, PD); 10761 10762 return true; 10763 } 10764 10765 return false; 10766} 10767 10768bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 10769 CallExpr *CE, FunctionDecl *FD) { 10770 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 10771 return false; 10772 10773 // If we're inside a decltype's expression, don't check for a valid return 10774 // type or construct temporaries until we know whether this is the last call. 10775 if (ExprEvalContexts.back().IsDecltype) { 10776 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 10777 return false; 10778 } 10779 10780 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 10781 FunctionDecl *FD; 10782 CallExpr *CE; 10783 10784 public: 10785 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 10786 : FD(FD), CE(CE) { } 10787 10788 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 10789 if (!FD) { 10790 S.Diag(Loc, diag::err_call_incomplete_return) 10791 << T << CE->getSourceRange(); 10792 return; 10793 } 10794 10795 S.Diag(Loc, diag::err_call_function_incomplete_return) 10796 << CE->getSourceRange() << FD->getDeclName() << T; 10797 S.Diag(FD->getLocation(), 10798 diag::note_function_with_incomplete_return_type_declared_here) 10799 << FD->getDeclName(); 10800 } 10801 } Diagnoser(FD, CE); 10802 10803 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 10804 return true; 10805 10806 return false; 10807} 10808 10809// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 10810// will prevent this condition from triggering, which is what we want. 10811void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 10812 SourceLocation Loc; 10813 10814 unsigned diagnostic = diag::warn_condition_is_assignment; 10815 bool IsOrAssign = false; 10816 10817 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 10818 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 10819 return; 10820 10821 IsOrAssign = Op->getOpcode() == BO_OrAssign; 10822 10823 // Greylist some idioms by putting them into a warning subcategory. 10824 if (ObjCMessageExpr *ME 10825 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 10826 Selector Sel = ME->getSelector(); 10827 10828 // self = [<foo> init...] 10829 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 10830 diagnostic = diag::warn_condition_is_idiomatic_assignment; 10831 10832 // <foo> = [<bar> nextObject] 10833 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 10834 diagnostic = diag::warn_condition_is_idiomatic_assignment; 10835 } 10836 10837 Loc = Op->getOperatorLoc(); 10838 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 10839 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 10840 return; 10841 10842 IsOrAssign = Op->getOperator() == OO_PipeEqual; 10843 Loc = Op->getOperatorLoc(); 10844 } else { 10845 // Not an assignment. 10846 return; 10847 } 10848 10849 Diag(Loc, diagnostic) << E->getSourceRange(); 10850 10851 SourceLocation Open = E->getLocStart(); 10852 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 10853 Diag(Loc, diag::note_condition_assign_silence) 10854 << FixItHint::CreateInsertion(Open, "(") 10855 << FixItHint::CreateInsertion(Close, ")"); 10856 10857 if (IsOrAssign) 10858 Diag(Loc, diag::note_condition_or_assign_to_comparison) 10859 << FixItHint::CreateReplacement(Loc, "!="); 10860 else 10861 Diag(Loc, diag::note_condition_assign_to_comparison) 10862 << FixItHint::CreateReplacement(Loc, "=="); 10863} 10864 10865/// \brief Redundant parentheses over an equality comparison can indicate 10866/// that the user intended an assignment used as condition. 10867void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 10868 // Don't warn if the parens came from a macro. 10869 SourceLocation parenLoc = ParenE->getLocStart(); 10870 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 10871 return; 10872 // Don't warn for dependent expressions. 10873 if (ParenE->isTypeDependent()) 10874 return; 10875 10876 Expr *E = ParenE->IgnoreParens(); 10877 10878 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 10879 if (opE->getOpcode() == BO_EQ && 10880 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 10881 == Expr::MLV_Valid) { 10882 SourceLocation Loc = opE->getOperatorLoc(); 10883 10884 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 10885 SourceRange ParenERange = ParenE->getSourceRange(); 10886 Diag(Loc, diag::note_equality_comparison_silence) 10887 << FixItHint::CreateRemoval(ParenERange.getBegin()) 10888 << FixItHint::CreateRemoval(ParenERange.getEnd()); 10889 Diag(Loc, diag::note_equality_comparison_to_assign) 10890 << FixItHint::CreateReplacement(Loc, "="); 10891 } 10892} 10893 10894ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 10895 DiagnoseAssignmentAsCondition(E); 10896 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 10897 DiagnoseEqualityWithExtraParens(parenE); 10898 10899 ExprResult result = CheckPlaceholderExpr(E); 10900 if (result.isInvalid()) return ExprError(); 10901 E = result.take(); 10902 10903 if (!E->isTypeDependent()) { 10904 if (getLangOpts().CPlusPlus) 10905 return CheckCXXBooleanCondition(E); // C++ 6.4p4 10906 10907 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 10908 if (ERes.isInvalid()) 10909 return ExprError(); 10910 E = ERes.take(); 10911 10912 QualType T = E->getType(); 10913 if (!T->isScalarType()) { // C99 6.8.4.1p1 10914 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 10915 << T << E->getSourceRange(); 10916 return ExprError(); 10917 } 10918 } 10919 10920 return Owned(E); 10921} 10922 10923ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 10924 Expr *SubExpr) { 10925 if (!SubExpr) 10926 return ExprError(); 10927 10928 return CheckBooleanCondition(SubExpr, Loc); 10929} 10930 10931namespace { 10932 /// A visitor for rebuilding a call to an __unknown_any expression 10933 /// to have an appropriate type. 10934 struct RebuildUnknownAnyFunction 10935 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 10936 10937 Sema &S; 10938 10939 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 10940 10941 ExprResult VisitStmt(Stmt *S) { 10942 llvm_unreachable("unexpected statement!"); 10943 } 10944 10945 ExprResult VisitExpr(Expr *E) { 10946 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 10947 << E->getSourceRange(); 10948 return ExprError(); 10949 } 10950 10951 /// Rebuild an expression which simply semantically wraps another 10952 /// expression which it shares the type and value kind of. 10953 template <class T> ExprResult rebuildSugarExpr(T *E) { 10954 ExprResult SubResult = Visit(E->getSubExpr()); 10955 if (SubResult.isInvalid()) return ExprError(); 10956 10957 Expr *SubExpr = SubResult.take(); 10958 E->setSubExpr(SubExpr); 10959 E->setType(SubExpr->getType()); 10960 E->setValueKind(SubExpr->getValueKind()); 10961 assert(E->getObjectKind() == OK_Ordinary); 10962 return E; 10963 } 10964 10965 ExprResult VisitParenExpr(ParenExpr *E) { 10966 return rebuildSugarExpr(E); 10967 } 10968 10969 ExprResult VisitUnaryExtension(UnaryOperator *E) { 10970 return rebuildSugarExpr(E); 10971 } 10972 10973 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 10974 ExprResult SubResult = Visit(E->getSubExpr()); 10975 if (SubResult.isInvalid()) return ExprError(); 10976 10977 Expr *SubExpr = SubResult.take(); 10978 E->setSubExpr(SubExpr); 10979 E->setType(S.Context.getPointerType(SubExpr->getType())); 10980 assert(E->getValueKind() == VK_RValue); 10981 assert(E->getObjectKind() == OK_Ordinary); 10982 return E; 10983 } 10984 10985 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 10986 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 10987 10988 E->setType(VD->getType()); 10989 10990 assert(E->getValueKind() == VK_RValue); 10991 if (S.getLangOpts().CPlusPlus && 10992 !(isa<CXXMethodDecl>(VD) && 10993 cast<CXXMethodDecl>(VD)->isInstance())) 10994 E->setValueKind(VK_LValue); 10995 10996 return E; 10997 } 10998 10999 ExprResult VisitMemberExpr(MemberExpr *E) { 11000 return resolveDecl(E, E->getMemberDecl()); 11001 } 11002 11003 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11004 return resolveDecl(E, E->getDecl()); 11005 } 11006 }; 11007} 11008 11009/// Given a function expression of unknown-any type, try to rebuild it 11010/// to have a function type. 11011static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 11012 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 11013 if (Result.isInvalid()) return ExprError(); 11014 return S.DefaultFunctionArrayConversion(Result.take()); 11015} 11016 11017namespace { 11018 /// A visitor for rebuilding an expression of type __unknown_anytype 11019 /// into one which resolves the type directly on the referring 11020 /// expression. Strict preservation of the original source 11021 /// structure is not a goal. 11022 struct RebuildUnknownAnyExpr 11023 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 11024 11025 Sema &S; 11026 11027 /// The current destination type. 11028 QualType DestType; 11029 11030 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 11031 : S(S), DestType(CastType) {} 11032 11033 ExprResult VisitStmt(Stmt *S) { 11034 llvm_unreachable("unexpected statement!"); 11035 } 11036 11037 ExprResult VisitExpr(Expr *E) { 11038 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 11039 << E->getSourceRange(); 11040 return ExprError(); 11041 } 11042 11043 ExprResult VisitCallExpr(CallExpr *E); 11044 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 11045 11046 /// Rebuild an expression which simply semantically wraps another 11047 /// expression which it shares the type and value kind of. 11048 template <class T> ExprResult rebuildSugarExpr(T *E) { 11049 ExprResult SubResult = Visit(E->getSubExpr()); 11050 if (SubResult.isInvalid()) return ExprError(); 11051 Expr *SubExpr = SubResult.take(); 11052 E->setSubExpr(SubExpr); 11053 E->setType(SubExpr->getType()); 11054 E->setValueKind(SubExpr->getValueKind()); 11055 assert(E->getObjectKind() == OK_Ordinary); 11056 return E; 11057 } 11058 11059 ExprResult VisitParenExpr(ParenExpr *E) { 11060 return rebuildSugarExpr(E); 11061 } 11062 11063 ExprResult VisitUnaryExtension(UnaryOperator *E) { 11064 return rebuildSugarExpr(E); 11065 } 11066 11067 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 11068 const PointerType *Ptr = DestType->getAs<PointerType>(); 11069 if (!Ptr) { 11070 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 11071 << E->getSourceRange(); 11072 return ExprError(); 11073 } 11074 assert(E->getValueKind() == VK_RValue); 11075 assert(E->getObjectKind() == OK_Ordinary); 11076 E->setType(DestType); 11077 11078 // Build the sub-expression as if it were an object of the pointee type. 11079 DestType = Ptr->getPointeeType(); 11080 ExprResult SubResult = Visit(E->getSubExpr()); 11081 if (SubResult.isInvalid()) return ExprError(); 11082 E->setSubExpr(SubResult.take()); 11083 return E; 11084 } 11085 11086 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 11087 11088 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 11089 11090 ExprResult VisitMemberExpr(MemberExpr *E) { 11091 return resolveDecl(E, E->getMemberDecl()); 11092 } 11093 11094 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11095 return resolveDecl(E, E->getDecl()); 11096 } 11097 }; 11098} 11099 11100/// Rebuilds a call expression which yielded __unknown_anytype. 11101ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 11102 Expr *CalleeExpr = E->getCallee(); 11103 11104 enum FnKind { 11105 FK_MemberFunction, 11106 FK_FunctionPointer, 11107 FK_BlockPointer 11108 }; 11109 11110 FnKind Kind; 11111 QualType CalleeType = CalleeExpr->getType(); 11112 if (CalleeType == S.Context.BoundMemberTy) { 11113 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 11114 Kind = FK_MemberFunction; 11115 CalleeType = Expr::findBoundMemberType(CalleeExpr); 11116 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 11117 CalleeType = Ptr->getPointeeType(); 11118 Kind = FK_FunctionPointer; 11119 } else { 11120 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 11121 Kind = FK_BlockPointer; 11122 } 11123 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 11124 11125 // Verify that this is a legal result type of a function. 11126 if (DestType->isArrayType() || DestType->isFunctionType()) { 11127 unsigned diagID = diag::err_func_returning_array_function; 11128 if (Kind == FK_BlockPointer) 11129 diagID = diag::err_block_returning_array_function; 11130 11131 S.Diag(E->getExprLoc(), diagID) 11132 << DestType->isFunctionType() << DestType; 11133 return ExprError(); 11134 } 11135 11136 // Otherwise, go ahead and set DestType as the call's result. 11137 E->setType(DestType.getNonLValueExprType(S.Context)); 11138 E->setValueKind(Expr::getValueKindForType(DestType)); 11139 assert(E->getObjectKind() == OK_Ordinary); 11140 11141 // Rebuild the function type, replacing the result type with DestType. 11142 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 11143 DestType = S.Context.getFunctionType(DestType, 11144 Proto->arg_type_begin(), 11145 Proto->getNumArgs(), 11146 Proto->getExtProtoInfo()); 11147 else 11148 DestType = S.Context.getFunctionNoProtoType(DestType, 11149 FnType->getExtInfo()); 11150 11151 // Rebuild the appropriate pointer-to-function type. 11152 switch (Kind) { 11153 case FK_MemberFunction: 11154 // Nothing to do. 11155 break; 11156 11157 case FK_FunctionPointer: 11158 DestType = S.Context.getPointerType(DestType); 11159 break; 11160 11161 case FK_BlockPointer: 11162 DestType = S.Context.getBlockPointerType(DestType); 11163 break; 11164 } 11165 11166 // Finally, we can recurse. 11167 ExprResult CalleeResult = Visit(CalleeExpr); 11168 if (!CalleeResult.isUsable()) return ExprError(); 11169 E->setCallee(CalleeResult.take()); 11170 11171 // Bind a temporary if necessary. 11172 return S.MaybeBindToTemporary(E); 11173} 11174 11175ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 11176 // Verify that this is a legal result type of a call. 11177 if (DestType->isArrayType() || DestType->isFunctionType()) { 11178 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 11179 << DestType->isFunctionType() << DestType; 11180 return ExprError(); 11181 } 11182 11183 // Rewrite the method result type if available. 11184 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 11185 assert(Method->getResultType() == S.Context.UnknownAnyTy); 11186 Method->setResultType(DestType); 11187 } 11188 11189 // Change the type of the message. 11190 E->setType(DestType.getNonReferenceType()); 11191 E->setValueKind(Expr::getValueKindForType(DestType)); 11192 11193 return S.MaybeBindToTemporary(E); 11194} 11195 11196ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 11197 // The only case we should ever see here is a function-to-pointer decay. 11198 if (E->getCastKind() == CK_FunctionToPointerDecay) { 11199 assert(E->getValueKind() == VK_RValue); 11200 assert(E->getObjectKind() == OK_Ordinary); 11201 11202 E->setType(DestType); 11203 11204 // Rebuild the sub-expression as the pointee (function) type. 11205 DestType = DestType->castAs<PointerType>()->getPointeeType(); 11206 11207 ExprResult Result = Visit(E->getSubExpr()); 11208 if (!Result.isUsable()) return ExprError(); 11209 11210 E->setSubExpr(Result.take()); 11211 return S.Owned(E); 11212 } else if (E->getCastKind() == CK_LValueToRValue) { 11213 assert(E->getValueKind() == VK_RValue); 11214 assert(E->getObjectKind() == OK_Ordinary); 11215 11216 assert(isa<BlockPointerType>(E->getType())); 11217 11218 E->setType(DestType); 11219 11220 // The sub-expression has to be a lvalue reference, so rebuild it as such. 11221 DestType = S.Context.getLValueReferenceType(DestType); 11222 11223 ExprResult Result = Visit(E->getSubExpr()); 11224 if (!Result.isUsable()) return ExprError(); 11225 11226 E->setSubExpr(Result.take()); 11227 return S.Owned(E); 11228 } else { 11229 llvm_unreachable("Unhandled cast type!"); 11230 } 11231} 11232 11233ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 11234 ExprValueKind ValueKind = VK_LValue; 11235 QualType Type = DestType; 11236 11237 // We know how to make this work for certain kinds of decls: 11238 11239 // - functions 11240 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 11241 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 11242 DestType = Ptr->getPointeeType(); 11243 ExprResult Result = resolveDecl(E, VD); 11244 if (Result.isInvalid()) return ExprError(); 11245 return S.ImpCastExprToType(Result.take(), Type, 11246 CK_FunctionToPointerDecay, VK_RValue); 11247 } 11248 11249 if (!Type->isFunctionType()) { 11250 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 11251 << VD << E->getSourceRange(); 11252 return ExprError(); 11253 } 11254 11255 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 11256 if (MD->isInstance()) { 11257 ValueKind = VK_RValue; 11258 Type = S.Context.BoundMemberTy; 11259 } 11260 11261 // Function references aren't l-values in C. 11262 if (!S.getLangOpts().CPlusPlus) 11263 ValueKind = VK_RValue; 11264 11265 // - variables 11266 } else if (isa<VarDecl>(VD)) { 11267 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 11268 Type = RefTy->getPointeeType(); 11269 } else if (Type->isFunctionType()) { 11270 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 11271 << VD << E->getSourceRange(); 11272 return ExprError(); 11273 } 11274 11275 // - nothing else 11276 } else { 11277 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 11278 << VD << E->getSourceRange(); 11279 return ExprError(); 11280 } 11281 11282 VD->setType(DestType); 11283 E->setType(Type); 11284 E->setValueKind(ValueKind); 11285 return S.Owned(E); 11286} 11287 11288/// Check a cast of an unknown-any type. We intentionally only 11289/// trigger this for C-style casts. 11290ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 11291 Expr *CastExpr, CastKind &CastKind, 11292 ExprValueKind &VK, CXXCastPath &Path) { 11293 // Rewrite the casted expression from scratch. 11294 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 11295 if (!result.isUsable()) return ExprError(); 11296 11297 CastExpr = result.take(); 11298 VK = CastExpr->getValueKind(); 11299 CastKind = CK_NoOp; 11300 11301 return CastExpr; 11302} 11303 11304ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 11305 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 11306} 11307 11308static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 11309 Expr *orig = E; 11310 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 11311 while (true) { 11312 E = E->IgnoreParenImpCasts(); 11313 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 11314 E = call->getCallee(); 11315 diagID = diag::err_uncasted_call_of_unknown_any; 11316 } else { 11317 break; 11318 } 11319 } 11320 11321 SourceLocation loc; 11322 NamedDecl *d; 11323 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 11324 loc = ref->getLocation(); 11325 d = ref->getDecl(); 11326 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 11327 loc = mem->getMemberLoc(); 11328 d = mem->getMemberDecl(); 11329 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 11330 diagID = diag::err_uncasted_call_of_unknown_any; 11331 loc = msg->getSelectorStartLoc(); 11332 d = msg->getMethodDecl(); 11333 if (!d) { 11334 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 11335 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 11336 << orig->getSourceRange(); 11337 return ExprError(); 11338 } 11339 } else { 11340 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 11341 << E->getSourceRange(); 11342 return ExprError(); 11343 } 11344 11345 S.Diag(loc, diagID) << d << orig->getSourceRange(); 11346 11347 // Never recoverable. 11348 return ExprError(); 11349} 11350 11351/// Check for operands with placeholder types and complain if found. 11352/// Returns true if there was an error and no recovery was possible. 11353ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 11354 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 11355 if (!placeholderType) return Owned(E); 11356 11357 switch (placeholderType->getKind()) { 11358 11359 // Overloaded expressions. 11360 case BuiltinType::Overload: { 11361 // Try to resolve a single function template specialization. 11362 // This is obligatory. 11363 ExprResult result = Owned(E); 11364 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 11365 return result; 11366 11367 // If that failed, try to recover with a call. 11368 } else { 11369 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 11370 /*complain*/ true); 11371 return result; 11372 } 11373 } 11374 11375 // Bound member functions. 11376 case BuiltinType::BoundMember: { 11377 ExprResult result = Owned(E); 11378 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 11379 /*complain*/ true); 11380 return result; 11381 } 11382 11383 // ARC unbridged casts. 11384 case BuiltinType::ARCUnbridgedCast: { 11385 Expr *realCast = stripARCUnbridgedCast(E); 11386 diagnoseARCUnbridgedCast(realCast); 11387 return Owned(realCast); 11388 } 11389 11390 // Expressions of unknown type. 11391 case BuiltinType::UnknownAny: 11392 return diagnoseUnknownAnyExpr(*this, E); 11393 11394 // Pseudo-objects. 11395 case BuiltinType::PseudoObject: 11396 return checkPseudoObjectRValue(E); 11397 11398 // Everything else should be impossible. 11399#define BUILTIN_TYPE(Id, SingletonId) \ 11400 case BuiltinType::Id: 11401#define PLACEHOLDER_TYPE(Id, SingletonId) 11402#include "clang/AST/BuiltinTypes.def" 11403 break; 11404 } 11405 11406 llvm_unreachable("invalid placeholder type!"); 11407} 11408 11409bool Sema::CheckCaseExpression(Expr *E) { 11410 if (E->isTypeDependent()) 11411 return true; 11412 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 11413 return E->getType()->isIntegralOrEnumerationType(); 11414 return false; 11415} 11416 11417/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 11418ExprResult 11419Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 11420 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 11421 "Unknown Objective-C Boolean value!"); 11422 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 11423 Context.ObjCBuiltinBoolTy, OpLoc)); 11424} 11425