SemaExpr.cpp revision 16581335fc32abcbc6ab14eda7af38cf759664b7
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 Determine whether the use of this declaration is valid, and 112/// emit any corresponding diagnostics. 113/// 114/// This routine diagnoses various problems with referencing 115/// declarations that can occur when using a declaration. For example, 116/// it might warn if a deprecated or unavailable declaration is being 117/// used, or produce an error (and return true) if a C++0x deleted 118/// function is being used. 119/// 120/// \returns true if there was an error (this declaration cannot be 121/// referenced), false otherwise. 122/// 123bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 124 const ObjCInterfaceDecl *UnknownObjCClass) { 125 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) { 126 // If there were any diagnostics suppressed by template argument deduction, 127 // emit them now. 128 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 129 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 130 if (Pos != SuppressedDiagnostics.end()) { 131 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 132 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 133 Diag(Suppressed[I].first, Suppressed[I].second); 134 135 // Clear out the list of suppressed diagnostics, so that we don't emit 136 // them again for this specialization. However, we don't obsolete this 137 // entry from the table, because we want to avoid ever emitting these 138 // diagnostics again. 139 Suppressed.clear(); 140 } 141 } 142 143 // See if this is an auto-typed variable whose initializer we are parsing. 144 if (ParsingInitForAutoVars.count(D)) { 145 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 146 << D->getDeclName(); 147 return true; 148 } 149 150 // See if this is a deleted function. 151 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 152 if (FD->isDeleted()) { 153 Diag(Loc, diag::err_deleted_function_use); 154 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true; 155 return true; 156 } 157 } 158 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 159 160 // Warn if this is used but marked unused. 161 if (D->hasAttr<UnusedAttr>()) 162 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 163 return false; 164} 165 166/// \brief Retrieve the message suffix that should be added to a 167/// diagnostic complaining about the given function being deleted or 168/// unavailable. 169std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 170 // FIXME: C++0x implicitly-deleted special member functions could be 171 // detected here so that we could improve diagnostics to say, e.g., 172 // "base class 'A' had a deleted copy constructor". 173 if (FD->isDeleted()) 174 return std::string(); 175 176 std::string Message; 177 if (FD->getAvailability(&Message)) 178 return ": " + Message; 179 180 return std::string(); 181} 182 183/// DiagnoseSentinelCalls - This routine checks whether a call or 184/// message-send is to a declaration with the sentinel attribute, and 185/// if so, it checks that the requirements of the sentinel are 186/// satisfied. 187void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 188 Expr **args, unsigned numArgs) { 189 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 190 if (!attr) 191 return; 192 193 // The number of formal parameters of the declaration. 194 unsigned numFormalParams; 195 196 // The kind of declaration. This is also an index into a %select in 197 // the diagnostic. 198 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 199 200 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 201 numFormalParams = MD->param_size(); 202 calleeType = CT_Method; 203 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 204 numFormalParams = FD->param_size(); 205 calleeType = CT_Function; 206 } else if (isa<VarDecl>(D)) { 207 QualType type = cast<ValueDecl>(D)->getType(); 208 const FunctionType *fn = 0; 209 if (const PointerType *ptr = type->getAs<PointerType>()) { 210 fn = ptr->getPointeeType()->getAs<FunctionType>(); 211 if (!fn) return; 212 calleeType = CT_Function; 213 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 214 fn = ptr->getPointeeType()->castAs<FunctionType>(); 215 calleeType = CT_Block; 216 } else { 217 return; 218 } 219 220 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 221 numFormalParams = proto->getNumArgs(); 222 } else { 223 numFormalParams = 0; 224 } 225 } else { 226 return; 227 } 228 229 // "nullPos" is the number of formal parameters at the end which 230 // effectively count as part of the variadic arguments. This is 231 // useful if you would prefer to not have *any* formal parameters, 232 // but the language forces you to have at least one. 233 unsigned nullPos = attr->getNullPos(); 234 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 235 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 236 237 // The number of arguments which should follow the sentinel. 238 unsigned numArgsAfterSentinel = attr->getSentinel(); 239 240 // If there aren't enough arguments for all the formal parameters, 241 // the sentinel, and the args after the sentinel, complain. 242 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) { 243 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 244 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 245 return; 246 } 247 248 // Otherwise, find the sentinel expression. 249 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1]; 250 if (!sentinelExpr) return; 251 if (sentinelExpr->isValueDependent()) return; 252 if (Context.isSentinelNullExpr(sentinelExpr)) return; 253 254 // Pick a reasonable string to insert. Optimistically use 'nil' or 255 // 'NULL' if those are actually defined in the context. Only use 256 // 'nil' for ObjC methods, where it's much more likely that the 257 // variadic arguments form a list of object pointers. 258 SourceLocation MissingNilLoc 259 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 260 std::string NullValue; 261 if (calleeType == CT_Method && 262 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 263 NullValue = "nil"; 264 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 265 NullValue = "NULL"; 266 else 267 NullValue = "(void*) 0"; 268 269 if (MissingNilLoc.isInvalid()) 270 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 271 else 272 Diag(MissingNilLoc, diag::warn_missing_sentinel) 273 << calleeType 274 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 275 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 276} 277 278SourceRange Sema::getExprRange(Expr *E) const { 279 return E ? E->getSourceRange() : SourceRange(); 280} 281 282//===----------------------------------------------------------------------===// 283// Standard Promotions and Conversions 284//===----------------------------------------------------------------------===// 285 286/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 287ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 288 // Handle any placeholder expressions which made it here. 289 if (E->getType()->isPlaceholderType()) { 290 ExprResult result = CheckPlaceholderExpr(E); 291 if (result.isInvalid()) return ExprError(); 292 E = result.take(); 293 } 294 295 QualType Ty = E->getType(); 296 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 297 298 if (Ty->isFunctionType()) 299 E = ImpCastExprToType(E, Context.getPointerType(Ty), 300 CK_FunctionToPointerDecay).take(); 301 else if (Ty->isArrayType()) { 302 // In C90 mode, arrays only promote to pointers if the array expression is 303 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 304 // type 'array of type' is converted to an expression that has type 'pointer 305 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 306 // that has type 'array of type' ...". The relevant change is "an lvalue" 307 // (C90) to "an expression" (C99). 308 // 309 // C++ 4.2p1: 310 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 311 // T" can be converted to an rvalue of type "pointer to T". 312 // 313 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue()) 314 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 315 CK_ArrayToPointerDecay).take(); 316 } 317 return Owned(E); 318} 319 320static void CheckForNullPointerDereference(Sema &S, Expr *E) { 321 // Check to see if we are dereferencing a null pointer. If so, 322 // and if not volatile-qualified, this is undefined behavior that the 323 // optimizer will delete, so warn about it. People sometimes try to use this 324 // to get a deterministic trap and are surprised by clang's behavior. This 325 // only handles the pattern "*null", which is a very syntactic check. 326 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 327 if (UO->getOpcode() == UO_Deref && 328 UO->getSubExpr()->IgnoreParenCasts()-> 329 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 330 !UO->getType().isVolatileQualified()) { 331 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 332 S.PDiag(diag::warn_indirection_through_null) 333 << UO->getSubExpr()->getSourceRange()); 334 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 335 S.PDiag(diag::note_indirection_through_null)); 336 } 337} 338 339ExprResult Sema::DefaultLvalueConversion(Expr *E) { 340 // Handle any placeholder expressions which made it here. 341 if (E->getType()->isPlaceholderType()) { 342 ExprResult result = CheckPlaceholderExpr(E); 343 if (result.isInvalid()) return ExprError(); 344 E = result.take(); 345 } 346 347 // C++ [conv.lval]p1: 348 // A glvalue of a non-function, non-array type T can be 349 // converted to a prvalue. 350 if (!E->isGLValue()) return Owned(E); 351 352 QualType T = E->getType(); 353 assert(!T.isNull() && "r-value conversion on typeless expression?"); 354 355 // We can't do lvalue-to-rvalue on atomics yet. 356 if (T->isAtomicType()) 357 return Owned(E); 358 359 // We don't want to throw lvalue-to-rvalue casts on top of 360 // expressions of certain types in C++. 361 if (getLangOptions().CPlusPlus && 362 (E->getType() == Context.OverloadTy || 363 T->isDependentType() || 364 T->isRecordType())) 365 return Owned(E); 366 367 // The C standard is actually really unclear on this point, and 368 // DR106 tells us what the result should be but not why. It's 369 // generally best to say that void types just doesn't undergo 370 // lvalue-to-rvalue at all. Note that expressions of unqualified 371 // 'void' type are never l-values, but qualified void can be. 372 if (T->isVoidType()) 373 return Owned(E); 374 375 CheckForNullPointerDereference(*this, E); 376 377 // C++ [conv.lval]p1: 378 // [...] If T is a non-class type, the type of the prvalue is the 379 // cv-unqualified version of T. Otherwise, the type of the 380 // rvalue is T. 381 // 382 // C99 6.3.2.1p2: 383 // If the lvalue has qualified type, the value has the unqualified 384 // version of the type of the lvalue; otherwise, the value has the 385 // type of the lvalue. 386 if (T.hasQualifiers()) 387 T = T.getUnqualifiedType(); 388 389 UpdateMarkingForLValueToRValue(E); 390 391 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 392 E, 0, VK_RValue)); 393 394 return Res; 395} 396 397ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 398 ExprResult Res = DefaultFunctionArrayConversion(E); 399 if (Res.isInvalid()) 400 return ExprError(); 401 Res = DefaultLvalueConversion(Res.take()); 402 if (Res.isInvalid()) 403 return ExprError(); 404 return move(Res); 405} 406 407 408/// UsualUnaryConversions - Performs various conversions that are common to most 409/// operators (C99 6.3). The conversions of array and function types are 410/// sometimes suppressed. For example, the array->pointer conversion doesn't 411/// apply if the array is an argument to the sizeof or address (&) operators. 412/// In these instances, this routine should *not* be called. 413ExprResult Sema::UsualUnaryConversions(Expr *E) { 414 // First, convert to an r-value. 415 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 416 if (Res.isInvalid()) 417 return Owned(E); 418 E = Res.take(); 419 420 QualType Ty = E->getType(); 421 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 422 423 // Half FP is a bit different: it's a storage-only type, meaning that any 424 // "use" of it should be promoted to float. 425 if (Ty->isHalfType()) 426 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 427 428 // Try to perform integral promotions if the object has a theoretically 429 // promotable type. 430 if (Ty->isIntegralOrUnscopedEnumerationType()) { 431 // C99 6.3.1.1p2: 432 // 433 // The following may be used in an expression wherever an int or 434 // unsigned int may be used: 435 // - an object or expression with an integer type whose integer 436 // conversion rank is less than or equal to the rank of int 437 // and unsigned int. 438 // - A bit-field of type _Bool, int, signed int, or unsigned int. 439 // 440 // If an int can represent all values of the original type, the 441 // value is converted to an int; otherwise, it is converted to an 442 // unsigned int. These are called the integer promotions. All 443 // other types are unchanged by the integer promotions. 444 445 QualType PTy = Context.isPromotableBitField(E); 446 if (!PTy.isNull()) { 447 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 448 return Owned(E); 449 } 450 if (Ty->isPromotableIntegerType()) { 451 QualType PT = Context.getPromotedIntegerType(Ty); 452 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 453 return Owned(E); 454 } 455 } 456 return Owned(E); 457} 458 459/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 460/// do not have a prototype. Arguments that have type float are promoted to 461/// double. All other argument types are converted by UsualUnaryConversions(). 462ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 463 QualType Ty = E->getType(); 464 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 465 466 ExprResult Res = UsualUnaryConversions(E); 467 if (Res.isInvalid()) 468 return Owned(E); 469 E = Res.take(); 470 471 // If this is a 'float' (CVR qualified or typedef) promote to double. 472 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 473 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 474 475 // C++ performs lvalue-to-rvalue conversion as a default argument 476 // promotion, even on class types, but note: 477 // C++11 [conv.lval]p2: 478 // When an lvalue-to-rvalue conversion occurs in an unevaluated 479 // operand or a subexpression thereof the value contained in the 480 // referenced object is not accessed. Otherwise, if the glvalue 481 // has a class type, the conversion copy-initializes a temporary 482 // of type T from the glvalue and the result of the conversion 483 // is a prvalue for the temporary. 484 // FIXME: add some way to gate this entire thing for correctness in 485 // potentially potentially evaluated contexts. 486 if (getLangOptions().CPlusPlus && E->isGLValue() && 487 ExprEvalContexts.back().Context != Unevaluated) { 488 ExprResult Temp = PerformCopyInitialization( 489 InitializedEntity::InitializeTemporary(E->getType()), 490 E->getExprLoc(), 491 Owned(E)); 492 if (Temp.isInvalid()) 493 return ExprError(); 494 E = Temp.get(); 495 } 496 497 return Owned(E); 498} 499 500/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 501/// will warn if the resulting type is not a POD type, and rejects ObjC 502/// interfaces passed by value. 503ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 504 FunctionDecl *FDecl) { 505 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 506 // Strip the unbridged-cast placeholder expression off, if applicable. 507 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 508 (CT == VariadicMethod || 509 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 510 E = stripARCUnbridgedCast(E); 511 512 // Otherwise, do normal placeholder checking. 513 } else { 514 ExprResult ExprRes = CheckPlaceholderExpr(E); 515 if (ExprRes.isInvalid()) 516 return ExprError(); 517 E = ExprRes.take(); 518 } 519 } 520 521 ExprResult ExprRes = DefaultArgumentPromotion(E); 522 if (ExprRes.isInvalid()) 523 return ExprError(); 524 E = ExprRes.take(); 525 526 // Don't allow one to pass an Objective-C interface to a vararg. 527 if (E->getType()->isObjCObjectType() && 528 DiagRuntimeBehavior(E->getLocStart(), 0, 529 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 530 << E->getType() << CT)) 531 return ExprError(); 532 533 // Complain about passing non-POD types through varargs. However, don't 534 // perform this check for incomplete types, which we can get here when we're 535 // in an unevaluated context. 536 if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) { 537 // C++0x [expr.call]p7: 538 // Passing a potentially-evaluated argument of class type (Clause 9) 539 // having a non-trivial copy constructor, a non-trivial move constructor, 540 // or a non-trivial destructor, with no corresponding parameter, 541 // is conditionally-supported with implementation-defined semantics. 542 bool TrivialEnough = false; 543 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) { 544 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) { 545 if (Record->hasTrivialCopyConstructor() && 546 Record->hasTrivialMoveConstructor() && 547 Record->hasTrivialDestructor()) { 548 DiagRuntimeBehavior(E->getLocStart(), 0, 549 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 550 << E->getType() << CT); 551 TrivialEnough = true; 552 } 553 } 554 } 555 556 if (!TrivialEnough && 557 getLangOptions().ObjCAutoRefCount && 558 E->getType()->isObjCLifetimeType()) 559 TrivialEnough = true; 560 561 if (TrivialEnough) { 562 // Nothing to diagnose. This is okay. 563 } else if (DiagRuntimeBehavior(E->getLocStart(), 0, 564 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 565 << getLangOptions().CPlusPlus0x << E->getType() 566 << CT)) { 567 // Turn this into a trap. 568 CXXScopeSpec SS; 569 SourceLocation TemplateKWLoc; 570 UnqualifiedId Name; 571 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 572 E->getLocStart()); 573 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 574 true, false); 575 if (TrapFn.isInvalid()) 576 return ExprError(); 577 578 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(), 579 MultiExprArg(), E->getLocEnd()); 580 if (Call.isInvalid()) 581 return ExprError(); 582 583 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 584 Call.get(), E); 585 if (Comma.isInvalid()) 586 return ExprError(); 587 E = Comma.get(); 588 } 589 } 590 // c++ rules are enfroced elsewhere. 591 if (!getLangOptions().CPlusPlus && 592 !E->getType()->isVoidType() && 593 RequireCompleteType(E->getExprLoc(), E->getType(), 594 diag::err_incomplete_type)) 595 return ExprError(); 596 597 return Owned(E); 598} 599 600/// \brief Converts an integer to complex float type. Helper function of 601/// UsualArithmeticConversions() 602/// 603/// \return false if the integer expression is an integer type and is 604/// successfully converted to the complex type. 605static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 606 ExprResult &ComplexExpr, 607 QualType IntTy, 608 QualType ComplexTy, 609 bool SkipCast) { 610 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 611 if (SkipCast) return false; 612 if (IntTy->isIntegerType()) { 613 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 614 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 615 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 616 CK_FloatingRealToComplex); 617 } else { 618 assert(IntTy->isComplexIntegerType()); 619 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 620 CK_IntegralComplexToFloatingComplex); 621 } 622 return false; 623} 624 625/// \brief Takes two complex float types and converts them to the same type. 626/// Helper function of UsualArithmeticConversions() 627static QualType 628handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 629 ExprResult &RHS, QualType LHSType, 630 QualType RHSType, 631 bool IsCompAssign) { 632 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 633 634 if (order < 0) { 635 // _Complex float -> _Complex double 636 if (!IsCompAssign) 637 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 638 return RHSType; 639 } 640 if (order > 0) 641 // _Complex float -> _Complex double 642 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 643 return LHSType; 644} 645 646/// \brief Converts otherExpr to complex float and promotes complexExpr if 647/// necessary. Helper function of UsualArithmeticConversions() 648static QualType handleOtherComplexFloatConversion(Sema &S, 649 ExprResult &ComplexExpr, 650 ExprResult &OtherExpr, 651 QualType ComplexTy, 652 QualType OtherTy, 653 bool ConvertComplexExpr, 654 bool ConvertOtherExpr) { 655 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 656 657 // If just the complexExpr is complex, the otherExpr needs to be converted, 658 // and the complexExpr might need to be promoted. 659 if (order > 0) { // complexExpr is wider 660 // float -> _Complex double 661 if (ConvertOtherExpr) { 662 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 663 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 664 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 665 CK_FloatingRealToComplex); 666 } 667 return ComplexTy; 668 } 669 670 // otherTy is at least as wide. Find its corresponding complex type. 671 QualType result = (order == 0 ? ComplexTy : 672 S.Context.getComplexType(OtherTy)); 673 674 // double -> _Complex double 675 if (ConvertOtherExpr) 676 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 677 CK_FloatingRealToComplex); 678 679 // _Complex float -> _Complex double 680 if (ConvertComplexExpr && order < 0) 681 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 682 CK_FloatingComplexCast); 683 684 return result; 685} 686 687/// \brief Handle arithmetic conversion with complex types. Helper function of 688/// UsualArithmeticConversions() 689static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 690 ExprResult &RHS, QualType LHSType, 691 QualType RHSType, 692 bool IsCompAssign) { 693 // if we have an integer operand, the result is the complex type. 694 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 695 /*skipCast*/false)) 696 return LHSType; 697 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 698 /*skipCast*/IsCompAssign)) 699 return RHSType; 700 701 // This handles complex/complex, complex/float, or float/complex. 702 // When both operands are complex, the shorter operand is converted to the 703 // type of the longer, and that is the type of the result. This corresponds 704 // to what is done when combining two real floating-point operands. 705 // The fun begins when size promotion occur across type domains. 706 // From H&S 6.3.4: When one operand is complex and the other is a real 707 // floating-point type, the less precise type is converted, within it's 708 // real or complex domain, to the precision of the other type. For example, 709 // when combining a "long double" with a "double _Complex", the 710 // "double _Complex" is promoted to "long double _Complex". 711 712 bool LHSComplexFloat = LHSType->isComplexType(); 713 bool RHSComplexFloat = RHSType->isComplexType(); 714 715 // If both are complex, just cast to the more precise type. 716 if (LHSComplexFloat && RHSComplexFloat) 717 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 718 LHSType, RHSType, 719 IsCompAssign); 720 721 // If only one operand is complex, promote it if necessary and convert the 722 // other operand to complex. 723 if (LHSComplexFloat) 724 return handleOtherComplexFloatConversion( 725 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 726 /*convertOtherExpr*/ true); 727 728 assert(RHSComplexFloat); 729 return handleOtherComplexFloatConversion( 730 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 731 /*convertOtherExpr*/ !IsCompAssign); 732} 733 734/// \brief Hande arithmetic conversion from integer to float. Helper function 735/// of UsualArithmeticConversions() 736static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 737 ExprResult &IntExpr, 738 QualType FloatTy, QualType IntTy, 739 bool ConvertFloat, bool ConvertInt) { 740 if (IntTy->isIntegerType()) { 741 if (ConvertInt) 742 // Convert intExpr to the lhs floating point type. 743 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 744 CK_IntegralToFloating); 745 return FloatTy; 746 } 747 748 // Convert both sides to the appropriate complex float. 749 assert(IntTy->isComplexIntegerType()); 750 QualType result = S.Context.getComplexType(FloatTy); 751 752 // _Complex int -> _Complex float 753 if (ConvertInt) 754 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 755 CK_IntegralComplexToFloatingComplex); 756 757 // float -> _Complex float 758 if (ConvertFloat) 759 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 760 CK_FloatingRealToComplex); 761 762 return result; 763} 764 765/// \brief Handle arithmethic conversion with floating point types. Helper 766/// function of UsualArithmeticConversions() 767static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 768 ExprResult &RHS, QualType LHSType, 769 QualType RHSType, bool IsCompAssign) { 770 bool LHSFloat = LHSType->isRealFloatingType(); 771 bool RHSFloat = RHSType->isRealFloatingType(); 772 773 // If we have two real floating types, convert the smaller operand 774 // to the bigger result. 775 if (LHSFloat && RHSFloat) { 776 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 777 if (order > 0) { 778 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 779 return LHSType; 780 } 781 782 assert(order < 0 && "illegal float comparison"); 783 if (!IsCompAssign) 784 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 785 return RHSType; 786 } 787 788 if (LHSFloat) 789 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 790 /*convertFloat=*/!IsCompAssign, 791 /*convertInt=*/ true); 792 assert(RHSFloat); 793 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 794 /*convertInt=*/ true, 795 /*convertFloat=*/!IsCompAssign); 796} 797 798/// \brief Handle conversions with GCC complex int extension. Helper function 799/// of UsualArithmeticConversions() 800// FIXME: if the operands are (int, _Complex long), we currently 801// don't promote the complex. Also, signedness? 802static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 803 ExprResult &RHS, QualType LHSType, 804 QualType RHSType, 805 bool IsCompAssign) { 806 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 807 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 808 809 if (LHSComplexInt && RHSComplexInt) { 810 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(), 811 RHSComplexInt->getElementType()); 812 assert(order && "inequal types with equal element ordering"); 813 if (order > 0) { 814 // _Complex int -> _Complex long 815 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast); 816 return LHSType; 817 } 818 819 if (!IsCompAssign) 820 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast); 821 return RHSType; 822 } 823 824 if (LHSComplexInt) { 825 // int -> _Complex int 826 // FIXME: This needs to take integer ranks into account 827 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(), 828 CK_IntegralCast); 829 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex); 830 return LHSType; 831 } 832 833 assert(RHSComplexInt); 834 // int -> _Complex int 835 // FIXME: This needs to take integer ranks into account 836 if (!IsCompAssign) { 837 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(), 838 CK_IntegralCast); 839 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex); 840 } 841 return RHSType; 842} 843 844/// \brief Handle integer arithmetic conversions. Helper function of 845/// UsualArithmeticConversions() 846static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 847 ExprResult &RHS, QualType LHSType, 848 QualType RHSType, bool IsCompAssign) { 849 // The rules for this case are in C99 6.3.1.8 850 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 851 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 852 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 853 if (LHSSigned == RHSSigned) { 854 // Same signedness; use the higher-ranked type 855 if (order >= 0) { 856 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 857 return LHSType; 858 } else if (!IsCompAssign) 859 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 860 return RHSType; 861 } else if (order != (LHSSigned ? 1 : -1)) { 862 // The unsigned type has greater than or equal rank to the 863 // signed type, so use the unsigned type 864 if (RHSSigned) { 865 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 866 return LHSType; 867 } else if (!IsCompAssign) 868 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 869 return RHSType; 870 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 871 // The two types are different widths; if we are here, that 872 // means the signed type is larger than the unsigned type, so 873 // use the signed type. 874 if (LHSSigned) { 875 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 876 return LHSType; 877 } else if (!IsCompAssign) 878 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 879 return RHSType; 880 } else { 881 // The signed type is higher-ranked than the unsigned type, 882 // but isn't actually any bigger (like unsigned int and long 883 // on most 32-bit systems). Use the unsigned type corresponding 884 // to the signed type. 885 QualType result = 886 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 887 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast); 888 if (!IsCompAssign) 889 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast); 890 return result; 891 } 892} 893 894/// UsualArithmeticConversions - Performs various conversions that are common to 895/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 896/// routine returns the first non-arithmetic type found. The client is 897/// responsible for emitting appropriate error diagnostics. 898/// FIXME: verify the conversion rules for "complex int" are consistent with 899/// GCC. 900QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 901 bool IsCompAssign) { 902 if (!IsCompAssign) { 903 LHS = UsualUnaryConversions(LHS.take()); 904 if (LHS.isInvalid()) 905 return QualType(); 906 } 907 908 RHS = UsualUnaryConversions(RHS.take()); 909 if (RHS.isInvalid()) 910 return QualType(); 911 912 // For conversion purposes, we ignore any qualifiers. 913 // For example, "const float" and "float" are equivalent. 914 QualType LHSType = 915 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 916 QualType RHSType = 917 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 918 919 // If both types are identical, no conversion is needed. 920 if (LHSType == RHSType) 921 return LHSType; 922 923 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 924 // The caller can deal with this (e.g. pointer + int). 925 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 926 return LHSType; 927 928 // Apply unary and bitfield promotions to the LHS's type. 929 QualType LHSUnpromotedType = LHSType; 930 if (LHSType->isPromotableIntegerType()) 931 LHSType = Context.getPromotedIntegerType(LHSType); 932 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 933 if (!LHSBitfieldPromoteTy.isNull()) 934 LHSType = LHSBitfieldPromoteTy; 935 if (LHSType != LHSUnpromotedType && !IsCompAssign) 936 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 937 938 // If both types are identical, no conversion is needed. 939 if (LHSType == RHSType) 940 return LHSType; 941 942 // At this point, we have two different arithmetic types. 943 944 // Handle complex types first (C99 6.3.1.8p1). 945 if (LHSType->isComplexType() || RHSType->isComplexType()) 946 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 947 IsCompAssign); 948 949 // Now handle "real" floating types (i.e. float, double, long double). 950 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 951 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 952 IsCompAssign); 953 954 // Handle GCC complex int extension. 955 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 956 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 957 IsCompAssign); 958 959 // Finally, we have two differing integer types. 960 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType, 961 IsCompAssign); 962} 963 964//===----------------------------------------------------------------------===// 965// Semantic Analysis for various Expression Types 966//===----------------------------------------------------------------------===// 967 968 969ExprResult 970Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 971 SourceLocation DefaultLoc, 972 SourceLocation RParenLoc, 973 Expr *ControllingExpr, 974 MultiTypeArg ArgTypes, 975 MultiExprArg ArgExprs) { 976 unsigned NumAssocs = ArgTypes.size(); 977 assert(NumAssocs == ArgExprs.size()); 978 979 ParsedType *ParsedTypes = ArgTypes.release(); 980 Expr **Exprs = ArgExprs.release(); 981 982 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 983 for (unsigned i = 0; i < NumAssocs; ++i) { 984 if (ParsedTypes[i]) 985 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 986 else 987 Types[i] = 0; 988 } 989 990 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 991 ControllingExpr, Types, Exprs, 992 NumAssocs); 993 delete [] Types; 994 return ER; 995} 996 997ExprResult 998Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 999 SourceLocation DefaultLoc, 1000 SourceLocation RParenLoc, 1001 Expr *ControllingExpr, 1002 TypeSourceInfo **Types, 1003 Expr **Exprs, 1004 unsigned NumAssocs) { 1005 bool TypeErrorFound = false, 1006 IsResultDependent = ControllingExpr->isTypeDependent(), 1007 ContainsUnexpandedParameterPack 1008 = ControllingExpr->containsUnexpandedParameterPack(); 1009 1010 for (unsigned i = 0; i < NumAssocs; ++i) { 1011 if (Exprs[i]->containsUnexpandedParameterPack()) 1012 ContainsUnexpandedParameterPack = true; 1013 1014 if (Types[i]) { 1015 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1016 ContainsUnexpandedParameterPack = true; 1017 1018 if (Types[i]->getType()->isDependentType()) { 1019 IsResultDependent = true; 1020 } else { 1021 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1022 // complete object type other than a variably modified type." 1023 unsigned D = 0; 1024 if (Types[i]->getType()->isIncompleteType()) 1025 D = diag::err_assoc_type_incomplete; 1026 else if (!Types[i]->getType()->isObjectType()) 1027 D = diag::err_assoc_type_nonobject; 1028 else if (Types[i]->getType()->isVariablyModifiedType()) 1029 D = diag::err_assoc_type_variably_modified; 1030 1031 if (D != 0) { 1032 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1033 << Types[i]->getTypeLoc().getSourceRange() 1034 << Types[i]->getType(); 1035 TypeErrorFound = true; 1036 } 1037 1038 // C11 6.5.1.1p2 "No two generic associations in the same generic 1039 // selection shall specify compatible types." 1040 for (unsigned j = i+1; j < NumAssocs; ++j) 1041 if (Types[j] && !Types[j]->getType()->isDependentType() && 1042 Context.typesAreCompatible(Types[i]->getType(), 1043 Types[j]->getType())) { 1044 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1045 diag::err_assoc_compatible_types) 1046 << Types[j]->getTypeLoc().getSourceRange() 1047 << Types[j]->getType() 1048 << Types[i]->getType(); 1049 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1050 diag::note_compat_assoc) 1051 << Types[i]->getTypeLoc().getSourceRange() 1052 << Types[i]->getType(); 1053 TypeErrorFound = true; 1054 } 1055 } 1056 } 1057 } 1058 if (TypeErrorFound) 1059 return ExprError(); 1060 1061 // If we determined that the generic selection is result-dependent, don't 1062 // try to compute the result expression. 1063 if (IsResultDependent) 1064 return Owned(new (Context) GenericSelectionExpr( 1065 Context, KeyLoc, ControllingExpr, 1066 Types, Exprs, NumAssocs, DefaultLoc, 1067 RParenLoc, ContainsUnexpandedParameterPack)); 1068 1069 SmallVector<unsigned, 1> CompatIndices; 1070 unsigned DefaultIndex = -1U; 1071 for (unsigned i = 0; i < NumAssocs; ++i) { 1072 if (!Types[i]) 1073 DefaultIndex = i; 1074 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1075 Types[i]->getType())) 1076 CompatIndices.push_back(i); 1077 } 1078 1079 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1080 // type compatible with at most one of the types named in its generic 1081 // association list." 1082 if (CompatIndices.size() > 1) { 1083 // We strip parens here because the controlling expression is typically 1084 // parenthesized in macro definitions. 1085 ControllingExpr = ControllingExpr->IgnoreParens(); 1086 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1087 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1088 << (unsigned) CompatIndices.size(); 1089 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1090 E = CompatIndices.end(); I != E; ++I) { 1091 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1092 diag::note_compat_assoc) 1093 << Types[*I]->getTypeLoc().getSourceRange() 1094 << Types[*I]->getType(); 1095 } 1096 return ExprError(); 1097 } 1098 1099 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1100 // its controlling expression shall have type compatible with exactly one of 1101 // the types named in its generic association list." 1102 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1103 // We strip parens here because the controlling expression is typically 1104 // parenthesized in macro definitions. 1105 ControllingExpr = ControllingExpr->IgnoreParens(); 1106 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1107 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1108 return ExprError(); 1109 } 1110 1111 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1112 // type name that is compatible with the type of the controlling expression, 1113 // then the result expression of the generic selection is the expression 1114 // in that generic association. Otherwise, the result expression of the 1115 // generic selection is the expression in the default generic association." 1116 unsigned ResultIndex = 1117 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1118 1119 return Owned(new (Context) GenericSelectionExpr( 1120 Context, KeyLoc, ControllingExpr, 1121 Types, Exprs, NumAssocs, DefaultLoc, 1122 RParenLoc, ContainsUnexpandedParameterPack, 1123 ResultIndex)); 1124} 1125 1126/// ActOnStringLiteral - The specified tokens were lexed as pasted string 1127/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1128/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1129/// multiple tokens. However, the common case is that StringToks points to one 1130/// string. 1131/// 1132ExprResult 1133Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 1134 assert(NumStringToks && "Must have at least one string!"); 1135 1136 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1137 if (Literal.hadError) 1138 return ExprError(); 1139 1140 SmallVector<SourceLocation, 4> StringTokLocs; 1141 for (unsigned i = 0; i != NumStringToks; ++i) 1142 StringTokLocs.push_back(StringToks[i].getLocation()); 1143 1144 QualType StrTy = Context.CharTy; 1145 if (Literal.isWide()) 1146 StrTy = Context.getWCharType(); 1147 else if (Literal.isUTF16()) 1148 StrTy = Context.Char16Ty; 1149 else if (Literal.isUTF32()) 1150 StrTy = Context.Char32Ty; 1151 else if (Literal.isPascal()) 1152 StrTy = Context.UnsignedCharTy; 1153 1154 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1155 if (Literal.isWide()) 1156 Kind = StringLiteral::Wide; 1157 else if (Literal.isUTF8()) 1158 Kind = StringLiteral::UTF8; 1159 else if (Literal.isUTF16()) 1160 Kind = StringLiteral::UTF16; 1161 else if (Literal.isUTF32()) 1162 Kind = StringLiteral::UTF32; 1163 1164 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1165 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings) 1166 StrTy.addConst(); 1167 1168 // Get an array type for the string, according to C99 6.4.5. This includes 1169 // the nul terminator character as well as the string length for pascal 1170 // strings. 1171 StrTy = Context.getConstantArrayType(StrTy, 1172 llvm::APInt(32, Literal.GetNumStringChars()+1), 1173 ArrayType::Normal, 0); 1174 1175 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1176 return Owned(StringLiteral::Create(Context, Literal.GetString(), 1177 Kind, Literal.Pascal, StrTy, 1178 &StringTokLocs[0], 1179 StringTokLocs.size())); 1180} 1181 1182ExprResult 1183Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1184 SourceLocation Loc, 1185 const CXXScopeSpec *SS) { 1186 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1187 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1188} 1189 1190/// BuildDeclRefExpr - Build an expression that references a 1191/// declaration that does not require a closure capture. 1192ExprResult 1193Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1194 const DeclarationNameInfo &NameInfo, 1195 const CXXScopeSpec *SS) { 1196 if (getLangOptions().CUDA) 1197 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1198 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1199 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1200 CalleeTarget = IdentifyCUDATarget(Callee); 1201 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1202 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1203 << CalleeTarget << D->getIdentifier() << CallerTarget; 1204 Diag(D->getLocation(), diag::note_previous_decl) 1205 << D->getIdentifier(); 1206 return ExprError(); 1207 } 1208 } 1209 1210 DeclRefExpr *E = DeclRefExpr::Create(Context, 1211 SS ? SS->getWithLocInContext(Context) 1212 : NestedNameSpecifierLoc(), 1213 SourceLocation(), 1214 D, NameInfo, Ty, VK); 1215 1216 MarkDeclRefReferenced(E); 1217 1218 // Just in case we're building an illegal pointer-to-member. 1219 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1220 if (FD && FD->isBitField()) 1221 E->setObjectKind(OK_BitField); 1222 1223 return Owned(E); 1224} 1225 1226/// Decomposes the given name into a DeclarationNameInfo, its location, and 1227/// possibly a list of template arguments. 1228/// 1229/// If this produces template arguments, it is permitted to call 1230/// DecomposeTemplateName. 1231/// 1232/// This actually loses a lot of source location information for 1233/// non-standard name kinds; we should consider preserving that in 1234/// some way. 1235void 1236Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1237 TemplateArgumentListInfo &Buffer, 1238 DeclarationNameInfo &NameInfo, 1239 const TemplateArgumentListInfo *&TemplateArgs) { 1240 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1241 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1242 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1243 1244 ASTTemplateArgsPtr TemplateArgsPtr(*this, 1245 Id.TemplateId->getTemplateArgs(), 1246 Id.TemplateId->NumArgs); 1247 translateTemplateArguments(TemplateArgsPtr, Buffer); 1248 TemplateArgsPtr.release(); 1249 1250 TemplateName TName = Id.TemplateId->Template.get(); 1251 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1252 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1253 TemplateArgs = &Buffer; 1254 } else { 1255 NameInfo = GetNameFromUnqualifiedId(Id); 1256 TemplateArgs = 0; 1257 } 1258} 1259 1260/// Diagnose an empty lookup. 1261/// 1262/// \return false if new lookup candidates were found 1263bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1264 CorrectionCandidateCallback &CCC, 1265 TemplateArgumentListInfo *ExplicitTemplateArgs, 1266 llvm::ArrayRef<Expr *> Args) { 1267 DeclarationName Name = R.getLookupName(); 1268 1269 unsigned diagnostic = diag::err_undeclared_var_use; 1270 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1271 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1272 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1273 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1274 diagnostic = diag::err_undeclared_use; 1275 diagnostic_suggest = diag::err_undeclared_use_suggest; 1276 } 1277 1278 // If the original lookup was an unqualified lookup, fake an 1279 // unqualified lookup. This is useful when (for example) the 1280 // original lookup would not have found something because it was a 1281 // dependent name. 1282 DeclContext *DC = SS.isEmpty() ? CurContext : 0; 1283 while (DC) { 1284 if (isa<CXXRecordDecl>(DC)) { 1285 LookupQualifiedName(R, DC); 1286 1287 if (!R.empty()) { 1288 // Don't give errors about ambiguities in this lookup. 1289 R.suppressDiagnostics(); 1290 1291 // During a default argument instantiation the CurContext points 1292 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1293 // function parameter list, hence add an explicit check. 1294 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1295 ActiveTemplateInstantiations.back().Kind == 1296 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1297 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1298 bool isInstance = CurMethod && 1299 CurMethod->isInstance() && 1300 DC == CurMethod->getParent() && !isDefaultArgument; 1301 1302 1303 // Give a code modification hint to insert 'this->'. 1304 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1305 // Actually quite difficult! 1306 if (isInstance) { 1307 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1308 CallsUndergoingInstantiation.back()->getCallee()); 1309 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>( 1310 CurMethod->getInstantiatedFromMemberFunction()); 1311 if (DepMethod) { 1312 if (getLangOptions().MicrosoftMode) 1313 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1314 Diag(R.getNameLoc(), diagnostic) << Name 1315 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1316 QualType DepThisType = DepMethod->getThisType(Context); 1317 CheckCXXThisCapture(R.getNameLoc()); 1318 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1319 R.getNameLoc(), DepThisType, false); 1320 TemplateArgumentListInfo TList; 1321 if (ULE->hasExplicitTemplateArgs()) 1322 ULE->copyTemplateArgumentsInto(TList); 1323 1324 CXXScopeSpec SS; 1325 SS.Adopt(ULE->getQualifierLoc()); 1326 CXXDependentScopeMemberExpr *DepExpr = 1327 CXXDependentScopeMemberExpr::Create( 1328 Context, DepThis, DepThisType, true, SourceLocation(), 1329 SS.getWithLocInContext(Context), 1330 ULE->getTemplateKeywordLoc(), 0, 1331 R.getLookupNameInfo(), 1332 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1333 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1334 } else { 1335 // FIXME: we should be able to handle this case too. It is correct 1336 // to add this-> here. This is a workaround for PR7947. 1337 Diag(R.getNameLoc(), diagnostic) << Name; 1338 } 1339 } else { 1340 if (getLangOptions().MicrosoftMode) 1341 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1342 Diag(R.getNameLoc(), diagnostic) << Name; 1343 } 1344 1345 // Do we really want to note all of these? 1346 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1347 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1348 1349 // Return true if we are inside a default argument instantiation 1350 // and the found name refers to an instance member function, otherwise 1351 // the function calling DiagnoseEmptyLookup will try to create an 1352 // implicit member call and this is wrong for default argument. 1353 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1354 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1355 return true; 1356 } 1357 1358 // Tell the callee to try to recover. 1359 return false; 1360 } 1361 1362 R.clear(); 1363 } 1364 1365 // In Microsoft mode, if we are performing lookup from within a friend 1366 // function definition declared at class scope then we must set 1367 // DC to the lexical parent to be able to search into the parent 1368 // class. 1369 if (getLangOptions().MicrosoftMode && isa<FunctionDecl>(DC) && 1370 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1371 DC->getLexicalParent()->isRecord()) 1372 DC = DC->getLexicalParent(); 1373 else 1374 DC = DC->getParent(); 1375 } 1376 1377 // We didn't find anything, so try to correct for a typo. 1378 TypoCorrection Corrected; 1379 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1380 S, &SS, CCC))) { 1381 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 1382 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 1383 R.setLookupName(Corrected.getCorrection()); 1384 1385 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1386 if (Corrected.isOverloaded()) { 1387 OverloadCandidateSet OCS(R.getNameLoc()); 1388 OverloadCandidateSet::iterator Best; 1389 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1390 CDEnd = Corrected.end(); 1391 CD != CDEnd; ++CD) { 1392 if (FunctionTemplateDecl *FTD = 1393 dyn_cast<FunctionTemplateDecl>(*CD)) 1394 AddTemplateOverloadCandidate( 1395 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1396 Args, OCS); 1397 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1398 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1399 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1400 Args, OCS); 1401 } 1402 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1403 case OR_Success: 1404 ND = Best->Function; 1405 break; 1406 default: 1407 break; 1408 } 1409 } 1410 R.addDecl(ND); 1411 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1412 if (SS.isEmpty()) 1413 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1414 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1415 else 1416 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1417 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1418 << SS.getRange() 1419 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1420 if (ND) 1421 Diag(ND->getLocation(), diag::note_previous_decl) 1422 << CorrectedQuotedStr; 1423 1424 // Tell the callee to try to recover. 1425 return false; 1426 } 1427 1428 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1429 // FIXME: If we ended up with a typo for a type name or 1430 // Objective-C class name, we're in trouble because the parser 1431 // is in the wrong place to recover. Suggest the typo 1432 // correction, but don't make it a fix-it since we're not going 1433 // to recover well anyway. 1434 if (SS.isEmpty()) 1435 Diag(R.getNameLoc(), diagnostic_suggest) 1436 << Name << CorrectedQuotedStr; 1437 else 1438 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1439 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1440 << SS.getRange(); 1441 1442 // Don't try to recover; it won't work. 1443 return true; 1444 } 1445 } else { 1446 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1447 // because we aren't able to recover. 1448 if (SS.isEmpty()) 1449 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1450 else 1451 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1452 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1453 << SS.getRange(); 1454 return true; 1455 } 1456 } 1457 R.clear(); 1458 1459 // Emit a special diagnostic for failed member lookups. 1460 // FIXME: computing the declaration context might fail here (?) 1461 if (!SS.isEmpty()) { 1462 Diag(R.getNameLoc(), diag::err_no_member) 1463 << Name << computeDeclContext(SS, false) 1464 << SS.getRange(); 1465 return true; 1466 } 1467 1468 // Give up, we can't recover. 1469 Diag(R.getNameLoc(), diagnostic) << Name; 1470 return true; 1471} 1472 1473ExprResult Sema::ActOnIdExpression(Scope *S, 1474 CXXScopeSpec &SS, 1475 SourceLocation TemplateKWLoc, 1476 UnqualifiedId &Id, 1477 bool HasTrailingLParen, 1478 bool IsAddressOfOperand, 1479 CorrectionCandidateCallback *CCC) { 1480 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1481 "cannot be direct & operand and have a trailing lparen"); 1482 1483 if (SS.isInvalid()) 1484 return ExprError(); 1485 1486 TemplateArgumentListInfo TemplateArgsBuffer; 1487 1488 // Decompose the UnqualifiedId into the following data. 1489 DeclarationNameInfo NameInfo; 1490 const TemplateArgumentListInfo *TemplateArgs; 1491 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1492 1493 DeclarationName Name = NameInfo.getName(); 1494 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1495 SourceLocation NameLoc = NameInfo.getLoc(); 1496 1497 // C++ [temp.dep.expr]p3: 1498 // An id-expression is type-dependent if it contains: 1499 // -- an identifier that was declared with a dependent type, 1500 // (note: handled after lookup) 1501 // -- a template-id that is dependent, 1502 // (note: handled in BuildTemplateIdExpr) 1503 // -- a conversion-function-id that specifies a dependent type, 1504 // -- a nested-name-specifier that contains a class-name that 1505 // names a dependent type. 1506 // Determine whether this is a member of an unknown specialization; 1507 // we need to handle these differently. 1508 bool DependentID = false; 1509 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1510 Name.getCXXNameType()->isDependentType()) { 1511 DependentID = true; 1512 } else if (SS.isSet()) { 1513 if (DeclContext *DC = computeDeclContext(SS, false)) { 1514 if (RequireCompleteDeclContext(SS, DC)) 1515 return ExprError(); 1516 } else { 1517 DependentID = true; 1518 } 1519 } 1520 1521 if (DependentID) 1522 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1523 IsAddressOfOperand, TemplateArgs); 1524 1525 // Perform the required lookup. 1526 LookupResult R(*this, NameInfo, 1527 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1528 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1529 if (TemplateArgs) { 1530 // Lookup the template name again to correctly establish the context in 1531 // which it was found. This is really unfortunate as we already did the 1532 // lookup to determine that it was a template name in the first place. If 1533 // this becomes a performance hit, we can work harder to preserve those 1534 // results until we get here but it's likely not worth it. 1535 bool MemberOfUnknownSpecialization; 1536 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1537 MemberOfUnknownSpecialization); 1538 1539 if (MemberOfUnknownSpecialization || 1540 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1541 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1542 IsAddressOfOperand, TemplateArgs); 1543 } else { 1544 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1545 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1546 1547 // If the result might be in a dependent base class, this is a dependent 1548 // id-expression. 1549 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1550 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1551 IsAddressOfOperand, TemplateArgs); 1552 1553 // If this reference is in an Objective-C method, then we need to do 1554 // some special Objective-C lookup, too. 1555 if (IvarLookupFollowUp) { 1556 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1557 if (E.isInvalid()) 1558 return ExprError(); 1559 1560 if (Expr *Ex = E.takeAs<Expr>()) 1561 return Owned(Ex); 1562 } 1563 } 1564 1565 if (R.isAmbiguous()) 1566 return ExprError(); 1567 1568 // Determine whether this name might be a candidate for 1569 // argument-dependent lookup. 1570 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1571 1572 if (R.empty() && !ADL) { 1573 // Otherwise, this could be an implicitly declared function reference (legal 1574 // in C90, extension in C99, forbidden in C++). 1575 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) { 1576 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1577 if (D) R.addDecl(D); 1578 } 1579 1580 // If this name wasn't predeclared and if this is not a function 1581 // call, diagnose the problem. 1582 if (R.empty()) { 1583 1584 // In Microsoft mode, if we are inside a template class member function 1585 // and we can't resolve an identifier then assume the identifier is type 1586 // dependent. The goal is to postpone name lookup to instantiation time 1587 // to be able to search into type dependent base classes. 1588 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() && 1589 isa<CXXMethodDecl>(CurContext)) 1590 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1591 IsAddressOfOperand, TemplateArgs); 1592 1593 CorrectionCandidateCallback DefaultValidator; 1594 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1595 return ExprError(); 1596 1597 assert(!R.empty() && 1598 "DiagnoseEmptyLookup returned false but added no results"); 1599 1600 // If we found an Objective-C instance variable, let 1601 // LookupInObjCMethod build the appropriate expression to 1602 // reference the ivar. 1603 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1604 R.clear(); 1605 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1606 // In a hopelessly buggy code, Objective-C instance variable 1607 // lookup fails and no expression will be built to reference it. 1608 if (!E.isInvalid() && !E.get()) 1609 return ExprError(); 1610 return move(E); 1611 } 1612 } 1613 } 1614 1615 // This is guaranteed from this point on. 1616 assert(!R.empty() || ADL); 1617 1618 // Check whether this might be a C++ implicit instance member access. 1619 // C++ [class.mfct.non-static]p3: 1620 // When an id-expression that is not part of a class member access 1621 // syntax and not used to form a pointer to member is used in the 1622 // body of a non-static member function of class X, if name lookup 1623 // resolves the name in the id-expression to a non-static non-type 1624 // member of some class C, the id-expression is transformed into a 1625 // class member access expression using (*this) as the 1626 // postfix-expression to the left of the . operator. 1627 // 1628 // But we don't actually need to do this for '&' operands if R 1629 // resolved to a function or overloaded function set, because the 1630 // expression is ill-formed if it actually works out to be a 1631 // non-static member function: 1632 // 1633 // C++ [expr.ref]p4: 1634 // Otherwise, if E1.E2 refers to a non-static member function. . . 1635 // [t]he expression can be used only as the left-hand operand of a 1636 // member function call. 1637 // 1638 // There are other safeguards against such uses, but it's important 1639 // to get this right here so that we don't end up making a 1640 // spuriously dependent expression if we're inside a dependent 1641 // instance method. 1642 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1643 bool MightBeImplicitMember; 1644 if (!IsAddressOfOperand) 1645 MightBeImplicitMember = true; 1646 else if (!SS.isEmpty()) 1647 MightBeImplicitMember = false; 1648 else if (R.isOverloadedResult()) 1649 MightBeImplicitMember = false; 1650 else if (R.isUnresolvableResult()) 1651 MightBeImplicitMember = true; 1652 else 1653 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1654 isa<IndirectFieldDecl>(R.getFoundDecl()); 1655 1656 if (MightBeImplicitMember) 1657 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 1658 R, TemplateArgs); 1659 } 1660 1661 if (TemplateArgs || TemplateKWLoc.isValid()) 1662 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 1663 1664 return BuildDeclarationNameExpr(SS, R, ADL); 1665} 1666 1667/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1668/// declaration name, generally during template instantiation. 1669/// There's a large number of things which don't need to be done along 1670/// this path. 1671ExprResult 1672Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1673 const DeclarationNameInfo &NameInfo) { 1674 DeclContext *DC; 1675 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext()) 1676 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 1677 NameInfo, /*TemplateArgs=*/0); 1678 1679 if (RequireCompleteDeclContext(SS, DC)) 1680 return ExprError(); 1681 1682 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1683 LookupQualifiedName(R, DC); 1684 1685 if (R.isAmbiguous()) 1686 return ExprError(); 1687 1688 if (R.empty()) { 1689 Diag(NameInfo.getLoc(), diag::err_no_member) 1690 << NameInfo.getName() << DC << SS.getRange(); 1691 return ExprError(); 1692 } 1693 1694 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1695} 1696 1697/// LookupInObjCMethod - The parser has read a name in, and Sema has 1698/// detected that we're currently inside an ObjC method. Perform some 1699/// additional lookup. 1700/// 1701/// Ideally, most of this would be done by lookup, but there's 1702/// actually quite a lot of extra work involved. 1703/// 1704/// Returns a null sentinel to indicate trivial success. 1705ExprResult 1706Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1707 IdentifierInfo *II, bool AllowBuiltinCreation) { 1708 SourceLocation Loc = Lookup.getNameLoc(); 1709 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1710 1711 // There are two cases to handle here. 1) scoped lookup could have failed, 1712 // in which case we should look for an ivar. 2) scoped lookup could have 1713 // found a decl, but that decl is outside the current instance method (i.e. 1714 // a global variable). In these two cases, we do a lookup for an ivar with 1715 // this name, if the lookup sucedes, we replace it our current decl. 1716 1717 // If we're in a class method, we don't normally want to look for 1718 // ivars. But if we don't find anything else, and there's an 1719 // ivar, that's an error. 1720 bool IsClassMethod = CurMethod->isClassMethod(); 1721 1722 bool LookForIvars; 1723 if (Lookup.empty()) 1724 LookForIvars = true; 1725 else if (IsClassMethod) 1726 LookForIvars = false; 1727 else 1728 LookForIvars = (Lookup.isSingleResult() && 1729 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1730 ObjCInterfaceDecl *IFace = 0; 1731 if (LookForIvars) { 1732 IFace = CurMethod->getClassInterface(); 1733 ObjCInterfaceDecl *ClassDeclared; 1734 ObjCIvarDecl *IV = 0; 1735 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 1736 // Diagnose using an ivar in a class method. 1737 if (IsClassMethod) 1738 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1739 << IV->getDeclName()); 1740 1741 // If we're referencing an invalid decl, just return this as a silent 1742 // error node. The error diagnostic was already emitted on the decl. 1743 if (IV->isInvalidDecl()) 1744 return ExprError(); 1745 1746 // Check if referencing a field with __attribute__((deprecated)). 1747 if (DiagnoseUseOfDecl(IV, Loc)) 1748 return ExprError(); 1749 1750 // Diagnose the use of an ivar outside of the declaring class. 1751 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1752 !declaresSameEntity(ClassDeclared, IFace)) 1753 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1754 1755 // FIXME: This should use a new expr for a direct reference, don't 1756 // turn this into Self->ivar, just return a BareIVarExpr or something. 1757 IdentifierInfo &II = Context.Idents.get("self"); 1758 UnqualifiedId SelfName; 1759 SelfName.setIdentifier(&II, SourceLocation()); 1760 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 1761 CXXScopeSpec SelfScopeSpec; 1762 SourceLocation TemplateKWLoc; 1763 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 1764 SelfName, false, false); 1765 if (SelfExpr.isInvalid()) 1766 return ExprError(); 1767 1768 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 1769 if (SelfExpr.isInvalid()) 1770 return ExprError(); 1771 1772 MarkAnyDeclReferenced(Loc, IV); 1773 return Owned(new (Context) 1774 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1775 SelfExpr.take(), true, true)); 1776 } 1777 } else if (CurMethod->isInstanceMethod()) { 1778 // We should warn if a local variable hides an ivar. 1779 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 1780 ObjCInterfaceDecl *ClassDeclared; 1781 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1782 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1783 declaresSameEntity(IFace, ClassDeclared)) 1784 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1785 } 1786 } 1787 } else if (Lookup.isSingleResult() && 1788 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 1789 // If accessing a stand-alone ivar in a class method, this is an error. 1790 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 1791 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1792 << IV->getDeclName()); 1793 } 1794 1795 if (Lookup.empty() && II && AllowBuiltinCreation) { 1796 // FIXME. Consolidate this with similar code in LookupName. 1797 if (unsigned BuiltinID = II->getBuiltinID()) { 1798 if (!(getLangOptions().CPlusPlus && 1799 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1800 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1801 S, Lookup.isForRedeclaration(), 1802 Lookup.getNameLoc()); 1803 if (D) Lookup.addDecl(D); 1804 } 1805 } 1806 } 1807 // Sentinel value saying that we didn't do anything special. 1808 return Owned((Expr*) 0); 1809} 1810 1811/// \brief Cast a base object to a member's actual type. 1812/// 1813/// Logically this happens in three phases: 1814/// 1815/// * First we cast from the base type to the naming class. 1816/// The naming class is the class into which we were looking 1817/// when we found the member; it's the qualifier type if a 1818/// qualifier was provided, and otherwise it's the base type. 1819/// 1820/// * Next we cast from the naming class to the declaring class. 1821/// If the member we found was brought into a class's scope by 1822/// a using declaration, this is that class; otherwise it's 1823/// the class declaring the member. 1824/// 1825/// * Finally we cast from the declaring class to the "true" 1826/// declaring class of the member. This conversion does not 1827/// obey access control. 1828ExprResult 1829Sema::PerformObjectMemberConversion(Expr *From, 1830 NestedNameSpecifier *Qualifier, 1831 NamedDecl *FoundDecl, 1832 NamedDecl *Member) { 1833 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 1834 if (!RD) 1835 return Owned(From); 1836 1837 QualType DestRecordType; 1838 QualType DestType; 1839 QualType FromRecordType; 1840 QualType FromType = From->getType(); 1841 bool PointerConversions = false; 1842 if (isa<FieldDecl>(Member)) { 1843 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 1844 1845 if (FromType->getAs<PointerType>()) { 1846 DestType = Context.getPointerType(DestRecordType); 1847 FromRecordType = FromType->getPointeeType(); 1848 PointerConversions = true; 1849 } else { 1850 DestType = DestRecordType; 1851 FromRecordType = FromType; 1852 } 1853 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 1854 if (Method->isStatic()) 1855 return Owned(From); 1856 1857 DestType = Method->getThisType(Context); 1858 DestRecordType = DestType->getPointeeType(); 1859 1860 if (FromType->getAs<PointerType>()) { 1861 FromRecordType = FromType->getPointeeType(); 1862 PointerConversions = true; 1863 } else { 1864 FromRecordType = FromType; 1865 DestType = DestRecordType; 1866 } 1867 } else { 1868 // No conversion necessary. 1869 return Owned(From); 1870 } 1871 1872 if (DestType->isDependentType() || FromType->isDependentType()) 1873 return Owned(From); 1874 1875 // If the unqualified types are the same, no conversion is necessary. 1876 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1877 return Owned(From); 1878 1879 SourceRange FromRange = From->getSourceRange(); 1880 SourceLocation FromLoc = FromRange.getBegin(); 1881 1882 ExprValueKind VK = From->getValueKind(); 1883 1884 // C++ [class.member.lookup]p8: 1885 // [...] Ambiguities can often be resolved by qualifying a name with its 1886 // class name. 1887 // 1888 // If the member was a qualified name and the qualified referred to a 1889 // specific base subobject type, we'll cast to that intermediate type 1890 // first and then to the object in which the member is declared. That allows 1891 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 1892 // 1893 // class Base { public: int x; }; 1894 // class Derived1 : public Base { }; 1895 // class Derived2 : public Base { }; 1896 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 1897 // 1898 // void VeryDerived::f() { 1899 // x = 17; // error: ambiguous base subobjects 1900 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 1901 // } 1902 if (Qualifier) { 1903 QualType QType = QualType(Qualifier->getAsType(), 0); 1904 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 1905 assert(QType->isRecordType() && "lookup done with non-record type"); 1906 1907 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 1908 1909 // In C++98, the qualifier type doesn't actually have to be a base 1910 // type of the object type, in which case we just ignore it. 1911 // Otherwise build the appropriate casts. 1912 if (IsDerivedFrom(FromRecordType, QRecordType)) { 1913 CXXCastPath BasePath; 1914 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 1915 FromLoc, FromRange, &BasePath)) 1916 return ExprError(); 1917 1918 if (PointerConversions) 1919 QType = Context.getPointerType(QType); 1920 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 1921 VK, &BasePath).take(); 1922 1923 FromType = QType; 1924 FromRecordType = QRecordType; 1925 1926 // If the qualifier type was the same as the destination type, 1927 // we're done. 1928 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1929 return Owned(From); 1930 } 1931 } 1932 1933 bool IgnoreAccess = false; 1934 1935 // If we actually found the member through a using declaration, cast 1936 // down to the using declaration's type. 1937 // 1938 // Pointer equality is fine here because only one declaration of a 1939 // class ever has member declarations. 1940 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 1941 assert(isa<UsingShadowDecl>(FoundDecl)); 1942 QualType URecordType = Context.getTypeDeclType( 1943 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 1944 1945 // We only need to do this if the naming-class to declaring-class 1946 // conversion is non-trivial. 1947 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 1948 assert(IsDerivedFrom(FromRecordType, URecordType)); 1949 CXXCastPath BasePath; 1950 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 1951 FromLoc, FromRange, &BasePath)) 1952 return ExprError(); 1953 1954 QualType UType = URecordType; 1955 if (PointerConversions) 1956 UType = Context.getPointerType(UType); 1957 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 1958 VK, &BasePath).take(); 1959 FromType = UType; 1960 FromRecordType = URecordType; 1961 } 1962 1963 // We don't do access control for the conversion from the 1964 // declaring class to the true declaring class. 1965 IgnoreAccess = true; 1966 } 1967 1968 CXXCastPath BasePath; 1969 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 1970 FromLoc, FromRange, &BasePath, 1971 IgnoreAccess)) 1972 return ExprError(); 1973 1974 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 1975 VK, &BasePath); 1976} 1977 1978bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 1979 const LookupResult &R, 1980 bool HasTrailingLParen) { 1981 // Only when used directly as the postfix-expression of a call. 1982 if (!HasTrailingLParen) 1983 return false; 1984 1985 // Never if a scope specifier was provided. 1986 if (SS.isSet()) 1987 return false; 1988 1989 // Only in C++ or ObjC++. 1990 if (!getLangOptions().CPlusPlus) 1991 return false; 1992 1993 // Turn off ADL when we find certain kinds of declarations during 1994 // normal lookup: 1995 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 1996 NamedDecl *D = *I; 1997 1998 // C++0x [basic.lookup.argdep]p3: 1999 // -- a declaration of a class member 2000 // Since using decls preserve this property, we check this on the 2001 // original decl. 2002 if (D->isCXXClassMember()) 2003 return false; 2004 2005 // C++0x [basic.lookup.argdep]p3: 2006 // -- a block-scope function declaration that is not a 2007 // using-declaration 2008 // NOTE: we also trigger this for function templates (in fact, we 2009 // don't check the decl type at all, since all other decl types 2010 // turn off ADL anyway). 2011 if (isa<UsingShadowDecl>(D)) 2012 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2013 else if (D->getDeclContext()->isFunctionOrMethod()) 2014 return false; 2015 2016 // C++0x [basic.lookup.argdep]p3: 2017 // -- a declaration that is neither a function or a function 2018 // template 2019 // And also for builtin functions. 2020 if (isa<FunctionDecl>(D)) { 2021 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2022 2023 // But also builtin functions. 2024 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2025 return false; 2026 } else if (!isa<FunctionTemplateDecl>(D)) 2027 return false; 2028 } 2029 2030 return true; 2031} 2032 2033 2034/// Diagnoses obvious problems with the use of the given declaration 2035/// as an expression. This is only actually called for lookups that 2036/// were not overloaded, and it doesn't promise that the declaration 2037/// will in fact be used. 2038static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2039 if (isa<TypedefNameDecl>(D)) { 2040 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2041 return true; 2042 } 2043 2044 if (isa<ObjCInterfaceDecl>(D)) { 2045 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2046 return true; 2047 } 2048 2049 if (isa<NamespaceDecl>(D)) { 2050 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2051 return true; 2052 } 2053 2054 return false; 2055} 2056 2057ExprResult 2058Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2059 LookupResult &R, 2060 bool NeedsADL) { 2061 // If this is a single, fully-resolved result and we don't need ADL, 2062 // just build an ordinary singleton decl ref. 2063 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2064 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 2065 R.getFoundDecl()); 2066 2067 // We only need to check the declaration if there's exactly one 2068 // result, because in the overloaded case the results can only be 2069 // functions and function templates. 2070 if (R.isSingleResult() && 2071 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2072 return ExprError(); 2073 2074 // Otherwise, just build an unresolved lookup expression. Suppress 2075 // any lookup-related diagnostics; we'll hash these out later, when 2076 // we've picked a target. 2077 R.suppressDiagnostics(); 2078 2079 UnresolvedLookupExpr *ULE 2080 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2081 SS.getWithLocInContext(Context), 2082 R.getLookupNameInfo(), 2083 NeedsADL, R.isOverloadedResult(), 2084 R.begin(), R.end()); 2085 2086 return Owned(ULE); 2087} 2088 2089static bool shouldBuildBlockDeclRef(ValueDecl *D, Sema &S) { 2090 // Check for a variable with local storage not from the current scope; 2091 // we need to create BlockDeclRefExprs for these. 2092 // FIXME: BlockDeclRefExpr shouldn't exist! 2093 VarDecl *var = dyn_cast<VarDecl>(D); 2094 if (!var) 2095 return false; 2096 if (var->getDeclContext() == S.CurContext) 2097 return false; 2098 if (!var->hasLocalStorage()) 2099 return false; 2100 return S.getCurBlock() != 0; 2101} 2102 2103static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD, 2104 const DeclarationNameInfo &NameInfo) { 2105 VarDecl *var = cast<VarDecl>(VD); 2106 QualType exprType = var->getType().getNonReferenceType(); 2107 2108 bool HasBlockAttr = var->hasAttr<BlocksAttr>(); 2109 bool ConstAdded = false; 2110 if (!HasBlockAttr) { 2111 ConstAdded = !exprType.isConstQualified(); 2112 exprType.addConst(); 2113 } 2114 2115 BlockDeclRefExpr *BDRE = 2116 new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue, 2117 NameInfo.getLoc(), HasBlockAttr, 2118 ConstAdded); 2119 2120 S.MarkBlockDeclRefReferenced(BDRE); 2121 2122 return S.Owned(BDRE); 2123} 2124 2125/// \brief Complete semantic analysis for a reference to the given declaration. 2126ExprResult 2127Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2128 const DeclarationNameInfo &NameInfo, 2129 NamedDecl *D) { 2130 assert(D && "Cannot refer to a NULL declaration"); 2131 assert(!isa<FunctionTemplateDecl>(D) && 2132 "Cannot refer unambiguously to a function template"); 2133 2134 SourceLocation Loc = NameInfo.getLoc(); 2135 if (CheckDeclInExpr(*this, Loc, D)) 2136 return ExprError(); 2137 2138 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2139 // Specifically diagnose references to class templates that are missing 2140 // a template argument list. 2141 Diag(Loc, diag::err_template_decl_ref) 2142 << Template << SS.getRange(); 2143 Diag(Template->getLocation(), diag::note_template_decl_here); 2144 return ExprError(); 2145 } 2146 2147 // Make sure that we're referring to a value. 2148 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2149 if (!VD) { 2150 Diag(Loc, diag::err_ref_non_value) 2151 << D << SS.getRange(); 2152 Diag(D->getLocation(), diag::note_declared_at); 2153 return ExprError(); 2154 } 2155 2156 // Check whether this declaration can be used. Note that we suppress 2157 // this check when we're going to perform argument-dependent lookup 2158 // on this function name, because this might not be the function 2159 // that overload resolution actually selects. 2160 if (DiagnoseUseOfDecl(VD, Loc)) 2161 return ExprError(); 2162 2163 // Only create DeclRefExpr's for valid Decl's. 2164 if (VD->isInvalidDecl()) 2165 return ExprError(); 2166 2167 // Handle members of anonymous structs and unions. If we got here, 2168 // and the reference is to a class member indirect field, then this 2169 // must be the subject of a pointer-to-member expression. 2170 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2171 if (!indirectField->isCXXClassMember()) 2172 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2173 indirectField); 2174 2175 { 2176 QualType type = VD->getType(); 2177 ExprValueKind valueKind = VK_RValue; 2178 2179 switch (D->getKind()) { 2180 // Ignore all the non-ValueDecl kinds. 2181#define ABSTRACT_DECL(kind) 2182#define VALUE(type, base) 2183#define DECL(type, base) \ 2184 case Decl::type: 2185#include "clang/AST/DeclNodes.inc" 2186 llvm_unreachable("invalid value decl kind"); 2187 2188 // These shouldn't make it here. 2189 case Decl::ObjCAtDefsField: 2190 case Decl::ObjCIvar: 2191 llvm_unreachable("forming non-member reference to ivar?"); 2192 2193 // Enum constants are always r-values and never references. 2194 // Unresolved using declarations are dependent. 2195 case Decl::EnumConstant: 2196 case Decl::UnresolvedUsingValue: 2197 valueKind = VK_RValue; 2198 break; 2199 2200 // Fields and indirect fields that got here must be for 2201 // pointer-to-member expressions; we just call them l-values for 2202 // internal consistency, because this subexpression doesn't really 2203 // exist in the high-level semantics. 2204 case Decl::Field: 2205 case Decl::IndirectField: 2206 assert(getLangOptions().CPlusPlus && 2207 "building reference to field in C?"); 2208 2209 // These can't have reference type in well-formed programs, but 2210 // for internal consistency we do this anyway. 2211 type = type.getNonReferenceType(); 2212 valueKind = VK_LValue; 2213 break; 2214 2215 // Non-type template parameters are either l-values or r-values 2216 // depending on the type. 2217 case Decl::NonTypeTemplateParm: { 2218 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2219 type = reftype->getPointeeType(); 2220 valueKind = VK_LValue; // even if the parameter is an r-value reference 2221 break; 2222 } 2223 2224 // For non-references, we need to strip qualifiers just in case 2225 // the template parameter was declared as 'const int' or whatever. 2226 valueKind = VK_RValue; 2227 type = type.getUnqualifiedType(); 2228 break; 2229 } 2230 2231 case Decl::Var: 2232 // In C, "extern void blah;" is valid and is an r-value. 2233 if (!getLangOptions().CPlusPlus && 2234 !type.hasQualifiers() && 2235 type->isVoidType()) { 2236 valueKind = VK_RValue; 2237 break; 2238 } 2239 // fallthrough 2240 2241 case Decl::ImplicitParam: 2242 case Decl::ParmVar: { 2243 // These are always l-values. 2244 valueKind = VK_LValue; 2245 type = type.getNonReferenceType(); 2246 2247 if (shouldBuildBlockDeclRef(VD, *this)) 2248 return BuildBlockDeclRefExpr(*this, VD, NameInfo); 2249 2250 // FIXME: Does the addition of const really only apply in 2251 // potentially-evaluated contexts? Since the variable isn't actually 2252 // captured in an unevaluated context, it seems that the answer is no. 2253 if (ExprEvalContexts.back().Context != Sema::Unevaluated) { 2254 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2255 if (!CapturedType.isNull()) 2256 type = CapturedType; 2257 } 2258 2259 break; 2260 } 2261 2262 case Decl::Function: { 2263 const FunctionType *fty = type->castAs<FunctionType>(); 2264 2265 // If we're referring to a function with an __unknown_anytype 2266 // result type, make the entire expression __unknown_anytype. 2267 if (fty->getResultType() == Context.UnknownAnyTy) { 2268 type = Context.UnknownAnyTy; 2269 valueKind = VK_RValue; 2270 break; 2271 } 2272 2273 // Functions are l-values in C++. 2274 if (getLangOptions().CPlusPlus) { 2275 valueKind = VK_LValue; 2276 break; 2277 } 2278 2279 // C99 DR 316 says that, if a function type comes from a 2280 // function definition (without a prototype), that type is only 2281 // used for checking compatibility. Therefore, when referencing 2282 // the function, we pretend that we don't have the full function 2283 // type. 2284 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2285 isa<FunctionProtoType>(fty)) 2286 type = Context.getFunctionNoProtoType(fty->getResultType(), 2287 fty->getExtInfo()); 2288 2289 // Functions are r-values in C. 2290 valueKind = VK_RValue; 2291 break; 2292 } 2293 2294 case Decl::CXXMethod: 2295 // If we're referring to a method with an __unknown_anytype 2296 // result type, make the entire expression __unknown_anytype. 2297 // This should only be possible with a type written directly. 2298 if (const FunctionProtoType *proto 2299 = dyn_cast<FunctionProtoType>(VD->getType())) 2300 if (proto->getResultType() == Context.UnknownAnyTy) { 2301 type = Context.UnknownAnyTy; 2302 valueKind = VK_RValue; 2303 break; 2304 } 2305 2306 // C++ methods are l-values if static, r-values if non-static. 2307 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2308 valueKind = VK_LValue; 2309 break; 2310 } 2311 // fallthrough 2312 2313 case Decl::CXXConversion: 2314 case Decl::CXXDestructor: 2315 case Decl::CXXConstructor: 2316 valueKind = VK_RValue; 2317 break; 2318 } 2319 2320 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS); 2321 } 2322} 2323 2324ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2325 PredefinedExpr::IdentType IT; 2326 2327 switch (Kind) { 2328 default: llvm_unreachable("Unknown simple primary expr!"); 2329 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2330 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2331 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2332 } 2333 2334 // Pre-defined identifiers are of type char[x], where x is the length of the 2335 // string. 2336 2337 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2338 if (!currentDecl && getCurBlock()) 2339 currentDecl = getCurBlock()->TheDecl; 2340 if (!currentDecl) { 2341 Diag(Loc, diag::ext_predef_outside_function); 2342 currentDecl = Context.getTranslationUnitDecl(); 2343 } 2344 2345 QualType ResTy; 2346 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2347 ResTy = Context.DependentTy; 2348 } else { 2349 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2350 2351 llvm::APInt LengthI(32, Length + 1); 2352 ResTy = Context.CharTy.withConst(); 2353 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2354 } 2355 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2356} 2357 2358ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 2359 SmallString<16> CharBuffer; 2360 bool Invalid = false; 2361 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2362 if (Invalid) 2363 return ExprError(); 2364 2365 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2366 PP, Tok.getKind()); 2367 if (Literal.hadError()) 2368 return ExprError(); 2369 2370 QualType Ty; 2371 if (Literal.isWide()) 2372 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++. 2373 else if (Literal.isUTF16()) 2374 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2375 else if (Literal.isUTF32()) 2376 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2377 else if (!getLangOptions().CPlusPlus || Literal.isMultiChar()) 2378 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2379 else 2380 Ty = Context.CharTy; // 'x' -> char in C++ 2381 2382 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2383 if (Literal.isWide()) 2384 Kind = CharacterLiteral::Wide; 2385 else if (Literal.isUTF16()) 2386 Kind = CharacterLiteral::UTF16; 2387 else if (Literal.isUTF32()) 2388 Kind = CharacterLiteral::UTF32; 2389 2390 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2391 Tok.getLocation())); 2392} 2393 2394ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 2395 // Fast path for a single digit (which is quite common). A single digit 2396 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 2397 if (Tok.getLength() == 1) { 2398 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2399 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2400 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'), 2401 Context.IntTy, Tok.getLocation())); 2402 } 2403 2404 SmallString<512> IntegerBuffer; 2405 // Add padding so that NumericLiteralParser can overread by one character. 2406 IntegerBuffer.resize(Tok.getLength()+1); 2407 const char *ThisTokBegin = &IntegerBuffer[0]; 2408 2409 // Get the spelling of the token, which eliminates trigraphs, etc. 2410 bool Invalid = false; 2411 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 2412 if (Invalid) 2413 return ExprError(); 2414 2415 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 2416 Tok.getLocation(), PP); 2417 if (Literal.hadError) 2418 return ExprError(); 2419 2420 Expr *Res; 2421 2422 if (Literal.isFloatingLiteral()) { 2423 QualType Ty; 2424 if (Literal.isFloat) 2425 Ty = Context.FloatTy; 2426 else if (!Literal.isLong) 2427 Ty = Context.DoubleTy; 2428 else 2429 Ty = Context.LongDoubleTy; 2430 2431 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 2432 2433 using llvm::APFloat; 2434 APFloat Val(Format); 2435 2436 APFloat::opStatus result = Literal.GetFloatValue(Val); 2437 2438 // Overflow is always an error, but underflow is only an error if 2439 // we underflowed to zero (APFloat reports denormals as underflow). 2440 if ((result & APFloat::opOverflow) || 2441 ((result & APFloat::opUnderflow) && Val.isZero())) { 2442 unsigned diagnostic; 2443 SmallString<20> buffer; 2444 if (result & APFloat::opOverflow) { 2445 diagnostic = diag::warn_float_overflow; 2446 APFloat::getLargest(Format).toString(buffer); 2447 } else { 2448 diagnostic = diag::warn_float_underflow; 2449 APFloat::getSmallest(Format).toString(buffer); 2450 } 2451 2452 Diag(Tok.getLocation(), diagnostic) 2453 << Ty 2454 << StringRef(buffer.data(), buffer.size()); 2455 } 2456 2457 bool isExact = (result == APFloat::opOK); 2458 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation()); 2459 2460 if (Ty == Context.DoubleTy) { 2461 if (getLangOptions().SinglePrecisionConstants) { 2462 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2463 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2464 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2465 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2466 } 2467 } 2468 } else if (!Literal.isIntegerLiteral()) { 2469 return ExprError(); 2470 } else { 2471 QualType Ty; 2472 2473 // long long is a C99 feature. 2474 if (!getLangOptions().C99 && Literal.isLongLong) 2475 Diag(Tok.getLocation(), 2476 getLangOptions().CPlusPlus0x ? 2477 diag::warn_cxx98_compat_longlong : diag::ext_longlong); 2478 2479 // Get the value in the widest-possible width. 2480 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0); 2481 2482 if (Literal.GetIntegerValue(ResultVal)) { 2483 // If this value didn't fit into uintmax_t, warn and force to ull. 2484 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2485 Ty = Context.UnsignedLongLongTy; 2486 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2487 "long long is not intmax_t?"); 2488 } else { 2489 // If this value fits into a ULL, try to figure out what else it fits into 2490 // according to the rules of C99 6.4.4.1p5. 2491 2492 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2493 // be an unsigned int. 2494 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2495 2496 // Check from smallest to largest, picking the smallest type we can. 2497 unsigned Width = 0; 2498 if (!Literal.isLong && !Literal.isLongLong) { 2499 // Are int/unsigned possibilities? 2500 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2501 2502 // Does it fit in a unsigned int? 2503 if (ResultVal.isIntN(IntSize)) { 2504 // Does it fit in a signed int? 2505 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2506 Ty = Context.IntTy; 2507 else if (AllowUnsigned) 2508 Ty = Context.UnsignedIntTy; 2509 Width = IntSize; 2510 } 2511 } 2512 2513 // Are long/unsigned long possibilities? 2514 if (Ty.isNull() && !Literal.isLongLong) { 2515 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 2516 2517 // Does it fit in a unsigned long? 2518 if (ResultVal.isIntN(LongSize)) { 2519 // Does it fit in a signed long? 2520 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2521 Ty = Context.LongTy; 2522 else if (AllowUnsigned) 2523 Ty = Context.UnsignedLongTy; 2524 Width = LongSize; 2525 } 2526 } 2527 2528 // Finally, check long long if needed. 2529 if (Ty.isNull()) { 2530 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 2531 2532 // Does it fit in a unsigned long long? 2533 if (ResultVal.isIntN(LongLongSize)) { 2534 // Does it fit in a signed long long? 2535 // To be compatible with MSVC, hex integer literals ending with the 2536 // LL or i64 suffix are always signed in Microsoft mode. 2537 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 2538 (getLangOptions().MicrosoftExt && Literal.isLongLong))) 2539 Ty = Context.LongLongTy; 2540 else if (AllowUnsigned) 2541 Ty = Context.UnsignedLongLongTy; 2542 Width = LongLongSize; 2543 } 2544 } 2545 2546 // If we still couldn't decide a type, we probably have something that 2547 // does not fit in a signed long long, but has no U suffix. 2548 if (Ty.isNull()) { 2549 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2550 Ty = Context.UnsignedLongLongTy; 2551 Width = Context.getTargetInfo().getLongLongWidth(); 2552 } 2553 2554 if (ResultVal.getBitWidth() != Width) 2555 ResultVal = ResultVal.trunc(Width); 2556 } 2557 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2558 } 2559 2560 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2561 if (Literal.isImaginary) 2562 Res = new (Context) ImaginaryLiteral(Res, 2563 Context.getComplexType(Res->getType())); 2564 2565 return Owned(Res); 2566} 2567 2568ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 2569 assert((E != 0) && "ActOnParenExpr() missing expr"); 2570 return Owned(new (Context) ParenExpr(L, R, E)); 2571} 2572 2573static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 2574 SourceLocation Loc, 2575 SourceRange ArgRange) { 2576 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 2577 // scalar or vector data type argument..." 2578 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 2579 // type (C99 6.2.5p18) or void. 2580 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 2581 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 2582 << T << ArgRange; 2583 return true; 2584 } 2585 2586 assert((T->isVoidType() || !T->isIncompleteType()) && 2587 "Scalar types should always be complete"); 2588 return false; 2589} 2590 2591static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 2592 SourceLocation Loc, 2593 SourceRange ArgRange, 2594 UnaryExprOrTypeTrait TraitKind) { 2595 // C99 6.5.3.4p1: 2596 if (T->isFunctionType()) { 2597 // alignof(function) is allowed as an extension. 2598 if (TraitKind == UETT_SizeOf) 2599 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange; 2600 return false; 2601 } 2602 2603 // Allow sizeof(void)/alignof(void) as an extension. 2604 if (T->isVoidType()) { 2605 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange; 2606 return false; 2607 } 2608 2609 return true; 2610} 2611 2612static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 2613 SourceLocation Loc, 2614 SourceRange ArgRange, 2615 UnaryExprOrTypeTrait TraitKind) { 2616 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 2617 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) { 2618 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 2619 << T << (TraitKind == UETT_SizeOf) 2620 << ArgRange; 2621 return true; 2622 } 2623 2624 return false; 2625} 2626 2627/// \brief Check the constrains on expression operands to unary type expression 2628/// and type traits. 2629/// 2630/// Completes any types necessary and validates the constraints on the operand 2631/// expression. The logic mostly mirrors the type-based overload, but may modify 2632/// the expression as it completes the type for that expression through template 2633/// instantiation, etc. 2634bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 2635 UnaryExprOrTypeTrait ExprKind) { 2636 QualType ExprTy = E->getType(); 2637 2638 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2639 // the result is the size of the referenced type." 2640 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2641 // result shall be the alignment of the referenced type." 2642 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2643 ExprTy = Ref->getPointeeType(); 2644 2645 if (ExprKind == UETT_VecStep) 2646 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 2647 E->getSourceRange()); 2648 2649 // Whitelist some types as extensions 2650 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 2651 E->getSourceRange(), ExprKind)) 2652 return false; 2653 2654 if (RequireCompleteExprType(E, 2655 PDiag(diag::err_sizeof_alignof_incomplete_type) 2656 << ExprKind << E->getSourceRange(), 2657 std::make_pair(SourceLocation(), PDiag(0)))) 2658 return true; 2659 2660 // Completeing the expression's type may have changed it. 2661 ExprTy = E->getType(); 2662 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2663 ExprTy = Ref->getPointeeType(); 2664 2665 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 2666 E->getSourceRange(), ExprKind)) 2667 return true; 2668 2669 if (ExprKind == UETT_SizeOf) { 2670 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 2671 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 2672 QualType OType = PVD->getOriginalType(); 2673 QualType Type = PVD->getType(); 2674 if (Type->isPointerType() && OType->isArrayType()) { 2675 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 2676 << Type << OType; 2677 Diag(PVD->getLocation(), diag::note_declared_at); 2678 } 2679 } 2680 } 2681 } 2682 2683 return false; 2684} 2685 2686/// \brief Check the constraints on operands to unary expression and type 2687/// traits. 2688/// 2689/// This will complete any types necessary, and validate the various constraints 2690/// on those operands. 2691/// 2692/// The UsualUnaryConversions() function is *not* called by this routine. 2693/// C99 6.3.2.1p[2-4] all state: 2694/// Except when it is the operand of the sizeof operator ... 2695/// 2696/// C++ [expr.sizeof]p4 2697/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 2698/// standard conversions are not applied to the operand of sizeof. 2699/// 2700/// This policy is followed for all of the unary trait expressions. 2701bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 2702 SourceLocation OpLoc, 2703 SourceRange ExprRange, 2704 UnaryExprOrTypeTrait ExprKind) { 2705 if (ExprType->isDependentType()) 2706 return false; 2707 2708 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2709 // the result is the size of the referenced type." 2710 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2711 // result shall be the alignment of the referenced type." 2712 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 2713 ExprType = Ref->getPointeeType(); 2714 2715 if (ExprKind == UETT_VecStep) 2716 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 2717 2718 // Whitelist some types as extensions 2719 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 2720 ExprKind)) 2721 return false; 2722 2723 if (RequireCompleteType(OpLoc, ExprType, 2724 PDiag(diag::err_sizeof_alignof_incomplete_type) 2725 << ExprKind << ExprRange)) 2726 return true; 2727 2728 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 2729 ExprKind)) 2730 return true; 2731 2732 return false; 2733} 2734 2735static bool CheckAlignOfExpr(Sema &S, Expr *E) { 2736 E = E->IgnoreParens(); 2737 2738 // alignof decl is always ok. 2739 if (isa<DeclRefExpr>(E)) 2740 return false; 2741 2742 // Cannot know anything else if the expression is dependent. 2743 if (E->isTypeDependent()) 2744 return false; 2745 2746 if (E->getBitField()) { 2747 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 2748 << 1 << E->getSourceRange(); 2749 return true; 2750 } 2751 2752 // Alignment of a field access is always okay, so long as it isn't a 2753 // bit-field. 2754 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2755 if (isa<FieldDecl>(ME->getMemberDecl())) 2756 return false; 2757 2758 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 2759} 2760 2761bool Sema::CheckVecStepExpr(Expr *E) { 2762 E = E->IgnoreParens(); 2763 2764 // Cannot know anything else if the expression is dependent. 2765 if (E->isTypeDependent()) 2766 return false; 2767 2768 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 2769} 2770 2771/// \brief Build a sizeof or alignof expression given a type operand. 2772ExprResult 2773Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2774 SourceLocation OpLoc, 2775 UnaryExprOrTypeTrait ExprKind, 2776 SourceRange R) { 2777 if (!TInfo) 2778 return ExprError(); 2779 2780 QualType T = TInfo->getType(); 2781 2782 if (!T->isDependentType() && 2783 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 2784 return ExprError(); 2785 2786 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2787 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 2788 Context.getSizeType(), 2789 OpLoc, R.getEnd())); 2790} 2791 2792/// \brief Build a sizeof or alignof expression given an expression 2793/// operand. 2794ExprResult 2795Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2796 UnaryExprOrTypeTrait ExprKind) { 2797 ExprResult PE = CheckPlaceholderExpr(E); 2798 if (PE.isInvalid()) 2799 return ExprError(); 2800 2801 E = PE.get(); 2802 2803 // Verify that the operand is valid. 2804 bool isInvalid = false; 2805 if (E->isTypeDependent()) { 2806 // Delay type-checking for type-dependent expressions. 2807 } else if (ExprKind == UETT_AlignOf) { 2808 isInvalid = CheckAlignOfExpr(*this, E); 2809 } else if (ExprKind == UETT_VecStep) { 2810 isInvalid = CheckVecStepExpr(E); 2811 } else if (E->getBitField()) { // C99 6.5.3.4p1. 2812 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 2813 isInvalid = true; 2814 } else { 2815 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 2816 } 2817 2818 if (isInvalid) 2819 return ExprError(); 2820 2821 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 2822 PE = TranformToPotentiallyEvaluated(E); 2823 if (PE.isInvalid()) return ExprError(); 2824 E = PE.take(); 2825 } 2826 2827 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2828 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 2829 ExprKind, E, Context.getSizeType(), OpLoc, 2830 E->getSourceRange().getEnd())); 2831} 2832 2833/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 2834/// expr and the same for @c alignof and @c __alignof 2835/// Note that the ArgRange is invalid if isType is false. 2836ExprResult 2837Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2838 UnaryExprOrTypeTrait ExprKind, bool IsType, 2839 void *TyOrEx, const SourceRange &ArgRange) { 2840 // If error parsing type, ignore. 2841 if (TyOrEx == 0) return ExprError(); 2842 2843 if (IsType) { 2844 TypeSourceInfo *TInfo; 2845 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 2846 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 2847 } 2848 2849 Expr *ArgEx = (Expr *)TyOrEx; 2850 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 2851 return move(Result); 2852} 2853 2854static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 2855 bool IsReal) { 2856 if (V.get()->isTypeDependent()) 2857 return S.Context.DependentTy; 2858 2859 // _Real and _Imag are only l-values for normal l-values. 2860 if (V.get()->getObjectKind() != OK_Ordinary) { 2861 V = S.DefaultLvalueConversion(V.take()); 2862 if (V.isInvalid()) 2863 return QualType(); 2864 } 2865 2866 // These operators return the element type of a complex type. 2867 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 2868 return CT->getElementType(); 2869 2870 // Otherwise they pass through real integer and floating point types here. 2871 if (V.get()->getType()->isArithmeticType()) 2872 return V.get()->getType(); 2873 2874 // Test for placeholders. 2875 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 2876 if (PR.isInvalid()) return QualType(); 2877 if (PR.get() != V.get()) { 2878 V = move(PR); 2879 return CheckRealImagOperand(S, V, Loc, IsReal); 2880 } 2881 2882 // Reject anything else. 2883 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 2884 << (IsReal ? "__real" : "__imag"); 2885 return QualType(); 2886} 2887 2888 2889 2890ExprResult 2891Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2892 tok::TokenKind Kind, Expr *Input) { 2893 UnaryOperatorKind Opc; 2894 switch (Kind) { 2895 default: llvm_unreachable("Unknown unary op!"); 2896 case tok::plusplus: Opc = UO_PostInc; break; 2897 case tok::minusminus: Opc = UO_PostDec; break; 2898 } 2899 2900 // Since this might is a postfix expression, get rid of ParenListExprs. 2901 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 2902 if (Result.isInvalid()) return ExprError(); 2903 Input = Result.take(); 2904 2905 return BuildUnaryOp(S, OpLoc, Opc, Input); 2906} 2907 2908ExprResult 2909Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2910 Expr *Idx, SourceLocation RLoc) { 2911 // Since this might be a postfix expression, get rid of ParenListExprs. 2912 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 2913 if (Result.isInvalid()) return ExprError(); 2914 Base = Result.take(); 2915 2916 Expr *LHSExp = Base, *RHSExp = Idx; 2917 2918 if (getLangOptions().CPlusPlus && 2919 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 2920 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2921 Context.DependentTy, 2922 VK_LValue, OK_Ordinary, 2923 RLoc)); 2924 } 2925 2926 if (getLangOptions().CPlusPlus && 2927 (LHSExp->getType()->isRecordType() || 2928 LHSExp->getType()->isEnumeralType() || 2929 RHSExp->getType()->isRecordType() || 2930 RHSExp->getType()->isEnumeralType())) { 2931 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 2932 } 2933 2934 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 2935} 2936 2937 2938ExprResult 2939Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2940 Expr *Idx, SourceLocation RLoc) { 2941 Expr *LHSExp = Base; 2942 Expr *RHSExp = Idx; 2943 2944 // Perform default conversions. 2945 if (!LHSExp->getType()->getAs<VectorType>()) { 2946 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 2947 if (Result.isInvalid()) 2948 return ExprError(); 2949 LHSExp = Result.take(); 2950 } 2951 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 2952 if (Result.isInvalid()) 2953 return ExprError(); 2954 RHSExp = Result.take(); 2955 2956 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 2957 ExprValueKind VK = VK_LValue; 2958 ExprObjectKind OK = OK_Ordinary; 2959 2960 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 2961 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 2962 // in the subscript position. As a result, we need to derive the array base 2963 // and index from the expression types. 2964 Expr *BaseExpr, *IndexExpr; 2965 QualType ResultType; 2966 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 2967 BaseExpr = LHSExp; 2968 IndexExpr = RHSExp; 2969 ResultType = Context.DependentTy; 2970 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 2971 BaseExpr = LHSExp; 2972 IndexExpr = RHSExp; 2973 ResultType = PTy->getPointeeType(); 2974 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 2975 // Handle the uncommon case of "123[Ptr]". 2976 BaseExpr = RHSExp; 2977 IndexExpr = LHSExp; 2978 ResultType = PTy->getPointeeType(); 2979 } else if (const ObjCObjectPointerType *PTy = 2980 LHSTy->getAs<ObjCObjectPointerType>()) { 2981 BaseExpr = LHSExp; 2982 IndexExpr = RHSExp; 2983 ResultType = PTy->getPointeeType(); 2984 } else if (const ObjCObjectPointerType *PTy = 2985 RHSTy->getAs<ObjCObjectPointerType>()) { 2986 // Handle the uncommon case of "123[Ptr]". 2987 BaseExpr = RHSExp; 2988 IndexExpr = LHSExp; 2989 ResultType = PTy->getPointeeType(); 2990 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 2991 BaseExpr = LHSExp; // vectors: V[123] 2992 IndexExpr = RHSExp; 2993 VK = LHSExp->getValueKind(); 2994 if (VK != VK_RValue) 2995 OK = OK_VectorComponent; 2996 2997 // FIXME: need to deal with const... 2998 ResultType = VTy->getElementType(); 2999 } else if (LHSTy->isArrayType()) { 3000 // If we see an array that wasn't promoted by 3001 // DefaultFunctionArrayLvalueConversion, it must be an array that 3002 // wasn't promoted because of the C90 rule that doesn't 3003 // allow promoting non-lvalue arrays. Warn, then 3004 // force the promotion here. 3005 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3006 LHSExp->getSourceRange(); 3007 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3008 CK_ArrayToPointerDecay).take(); 3009 LHSTy = LHSExp->getType(); 3010 3011 BaseExpr = LHSExp; 3012 IndexExpr = RHSExp; 3013 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3014 } else if (RHSTy->isArrayType()) { 3015 // Same as previous, except for 123[f().a] case 3016 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3017 RHSExp->getSourceRange(); 3018 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3019 CK_ArrayToPointerDecay).take(); 3020 RHSTy = RHSExp->getType(); 3021 3022 BaseExpr = RHSExp; 3023 IndexExpr = LHSExp; 3024 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3025 } else { 3026 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3027 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3028 } 3029 // C99 6.5.2.1p1 3030 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3031 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3032 << IndexExpr->getSourceRange()); 3033 3034 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3035 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3036 && !IndexExpr->isTypeDependent()) 3037 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3038 3039 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3040 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3041 // type. Note that Functions are not objects, and that (in C99 parlance) 3042 // incomplete types are not object types. 3043 if (ResultType->isFunctionType()) { 3044 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3045 << ResultType << BaseExpr->getSourceRange(); 3046 return ExprError(); 3047 } 3048 3049 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) { 3050 // GNU extension: subscripting on pointer to void 3051 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3052 << BaseExpr->getSourceRange(); 3053 3054 // C forbids expressions of unqualified void type from being l-values. 3055 // See IsCForbiddenLValueType. 3056 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3057 } else if (!ResultType->isDependentType() && 3058 RequireCompleteType(LLoc, ResultType, 3059 PDiag(diag::err_subscript_incomplete_type) 3060 << BaseExpr->getSourceRange())) 3061 return ExprError(); 3062 3063 // Diagnose bad cases where we step over interface counts. 3064 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 3065 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3066 << ResultType << BaseExpr->getSourceRange(); 3067 return ExprError(); 3068 } 3069 3070 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3071 !ResultType.isCForbiddenLValueType()); 3072 3073 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3074 ResultType, VK, OK, RLoc)); 3075} 3076 3077ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3078 FunctionDecl *FD, 3079 ParmVarDecl *Param) { 3080 if (Param->hasUnparsedDefaultArg()) { 3081 Diag(CallLoc, 3082 diag::err_use_of_default_argument_to_function_declared_later) << 3083 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3084 Diag(UnparsedDefaultArgLocs[Param], 3085 diag::note_default_argument_declared_here); 3086 return ExprError(); 3087 } 3088 3089 if (Param->hasUninstantiatedDefaultArg()) { 3090 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3091 3092 // Instantiate the expression. 3093 MultiLevelTemplateArgumentList ArgList 3094 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3095 3096 std::pair<const TemplateArgument *, unsigned> Innermost 3097 = ArgList.getInnermost(); 3098 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first, 3099 Innermost.second); 3100 3101 ExprResult Result; 3102 { 3103 // C++ [dcl.fct.default]p5: 3104 // The names in the [default argument] expression are bound, and 3105 // the semantic constraints are checked, at the point where the 3106 // default argument expression appears. 3107 ContextRAII SavedContext(*this, FD); 3108 LocalInstantiationScope Local(*this); 3109 Result = SubstExpr(UninstExpr, ArgList); 3110 } 3111 if (Result.isInvalid()) 3112 return ExprError(); 3113 3114 // Check the expression as an initializer for the parameter. 3115 InitializedEntity Entity 3116 = InitializedEntity::InitializeParameter(Context, Param); 3117 InitializationKind Kind 3118 = InitializationKind::CreateCopy(Param->getLocation(), 3119 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin()); 3120 Expr *ResultE = Result.takeAs<Expr>(); 3121 3122 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3123 Result = InitSeq.Perform(*this, Entity, Kind, 3124 MultiExprArg(*this, &ResultE, 1)); 3125 if (Result.isInvalid()) 3126 return ExprError(); 3127 3128 // Build the default argument expression. 3129 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, 3130 Result.takeAs<Expr>())); 3131 } 3132 3133 // If the default expression creates temporaries, we need to 3134 // push them to the current stack of expression temporaries so they'll 3135 // be properly destroyed. 3136 // FIXME: We should really be rebuilding the default argument with new 3137 // bound temporaries; see the comment in PR5810. 3138 // We don't need to do that with block decls, though, because 3139 // blocks in default argument expression can never capture anything. 3140 if (isa<ExprWithCleanups>(Param->getInit())) { 3141 // Set the "needs cleanups" bit regardless of whether there are 3142 // any explicit objects. 3143 ExprNeedsCleanups = true; 3144 3145 // Append all the objects to the cleanup list. Right now, this 3146 // should always be a no-op, because blocks in default argument 3147 // expressions should never be able to capture anything. 3148 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3149 "default argument expression has capturing blocks?"); 3150 } 3151 3152 // We already type-checked the argument, so we know it works. 3153 // Just mark all of the declarations in this potentially-evaluated expression 3154 // as being "referenced". 3155 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3156 /*SkipLocalVariables=*/true); 3157 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3158} 3159 3160/// ConvertArgumentsForCall - Converts the arguments specified in 3161/// Args/NumArgs to the parameter types of the function FDecl with 3162/// function prototype Proto. Call is the call expression itself, and 3163/// Fn is the function expression. For a C++ member function, this 3164/// routine does not attempt to convert the object argument. Returns 3165/// true if the call is ill-formed. 3166bool 3167Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3168 FunctionDecl *FDecl, 3169 const FunctionProtoType *Proto, 3170 Expr **Args, unsigned NumArgs, 3171 SourceLocation RParenLoc, 3172 bool IsExecConfig) { 3173 // Bail out early if calling a builtin with custom typechecking. 3174 // We don't need to do this in the 3175 if (FDecl) 3176 if (unsigned ID = FDecl->getBuiltinID()) 3177 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3178 return false; 3179 3180 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3181 // assignment, to the types of the corresponding parameter, ... 3182 unsigned NumArgsInProto = Proto->getNumArgs(); 3183 bool Invalid = false; 3184 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3185 unsigned FnKind = Fn->getType()->isBlockPointerType() 3186 ? 1 /* block */ 3187 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3188 : 0 /* function */); 3189 3190 // If too few arguments are available (and we don't have default 3191 // arguments for the remaining parameters), don't make the call. 3192 if (NumArgs < NumArgsInProto) { 3193 if (NumArgs < MinArgs) { 3194 Diag(RParenLoc, MinArgs == NumArgsInProto 3195 ? diag::err_typecheck_call_too_few_args 3196 : diag::err_typecheck_call_too_few_args_at_least) 3197 << FnKind 3198 << MinArgs << NumArgs << Fn->getSourceRange(); 3199 3200 // Emit the location of the prototype. 3201 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3202 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3203 << FDecl; 3204 3205 return true; 3206 } 3207 Call->setNumArgs(Context, NumArgsInProto); 3208 } 3209 3210 // If too many are passed and not variadic, error on the extras and drop 3211 // them. 3212 if (NumArgs > NumArgsInProto) { 3213 if (!Proto->isVariadic()) { 3214 Diag(Args[NumArgsInProto]->getLocStart(), 3215 MinArgs == NumArgsInProto 3216 ? diag::err_typecheck_call_too_many_args 3217 : diag::err_typecheck_call_too_many_args_at_most) 3218 << FnKind 3219 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3220 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3221 Args[NumArgs-1]->getLocEnd()); 3222 3223 // Emit the location of the prototype. 3224 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3225 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3226 << FDecl; 3227 3228 // This deletes the extra arguments. 3229 Call->setNumArgs(Context, NumArgsInProto); 3230 return true; 3231 } 3232 } 3233 SmallVector<Expr *, 8> AllArgs; 3234 VariadicCallType CallType = 3235 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 3236 if (Fn->getType()->isBlockPointerType()) 3237 CallType = VariadicBlock; // Block 3238 else if (isa<MemberExpr>(Fn)) 3239 CallType = VariadicMethod; 3240 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl, 3241 Proto, 0, Args, NumArgs, AllArgs, CallType); 3242 if (Invalid) 3243 return true; 3244 unsigned TotalNumArgs = AllArgs.size(); 3245 for (unsigned i = 0; i < TotalNumArgs; ++i) 3246 Call->setArg(i, AllArgs[i]); 3247 3248 return false; 3249} 3250 3251bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3252 FunctionDecl *FDecl, 3253 const FunctionProtoType *Proto, 3254 unsigned FirstProtoArg, 3255 Expr **Args, unsigned NumArgs, 3256 SmallVector<Expr *, 8> &AllArgs, 3257 VariadicCallType CallType, 3258 bool AllowExplicit) { 3259 unsigned NumArgsInProto = Proto->getNumArgs(); 3260 unsigned NumArgsToCheck = NumArgs; 3261 bool Invalid = false; 3262 if (NumArgs != NumArgsInProto) 3263 // Use default arguments for missing arguments 3264 NumArgsToCheck = NumArgsInProto; 3265 unsigned ArgIx = 0; 3266 // Continue to check argument types (even if we have too few/many args). 3267 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3268 QualType ProtoArgType = Proto->getArgType(i); 3269 3270 Expr *Arg; 3271 ParmVarDecl *Param; 3272 if (ArgIx < NumArgs) { 3273 Arg = Args[ArgIx++]; 3274 3275 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3276 ProtoArgType, 3277 PDiag(diag::err_call_incomplete_argument) 3278 << Arg->getSourceRange())) 3279 return true; 3280 3281 // Pass the argument 3282 Param = 0; 3283 if (FDecl && i < FDecl->getNumParams()) 3284 Param = FDecl->getParamDecl(i); 3285 3286 // Strip the unbridged-cast placeholder expression off, if applicable. 3287 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3288 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3289 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3290 Arg = stripARCUnbridgedCast(Arg); 3291 3292 InitializedEntity Entity = 3293 Param? InitializedEntity::InitializeParameter(Context, Param) 3294 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3295 Proto->isArgConsumed(i)); 3296 ExprResult ArgE = PerformCopyInitialization(Entity, 3297 SourceLocation(), 3298 Owned(Arg), 3299 /*TopLevelOfInitList=*/false, 3300 AllowExplicit); 3301 if (ArgE.isInvalid()) 3302 return true; 3303 3304 Arg = ArgE.takeAs<Expr>(); 3305 } else { 3306 Param = FDecl->getParamDecl(i); 3307 3308 ExprResult ArgExpr = 3309 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3310 if (ArgExpr.isInvalid()) 3311 return true; 3312 3313 Arg = ArgExpr.takeAs<Expr>(); 3314 } 3315 3316 // Check for array bounds violations for each argument to the call. This 3317 // check only triggers warnings when the argument isn't a more complex Expr 3318 // with its own checking, such as a BinaryOperator. 3319 CheckArrayAccess(Arg); 3320 3321 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3322 CheckStaticArrayArgument(CallLoc, Param, Arg); 3323 3324 AllArgs.push_back(Arg); 3325 } 3326 3327 // If this is a variadic call, handle args passed through "...". 3328 if (CallType != VariadicDoesNotApply) { 3329 3330 // Assume that extern "C" functions with variadic arguments that 3331 // return __unknown_anytype aren't *really* variadic. 3332 if (Proto->getResultType() == Context.UnknownAnyTy && 3333 FDecl && FDecl->isExternC()) { 3334 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3335 ExprResult arg; 3336 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens())) 3337 arg = DefaultFunctionArrayLvalueConversion(Args[i]); 3338 else 3339 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl); 3340 Invalid |= arg.isInvalid(); 3341 AllArgs.push_back(arg.take()); 3342 } 3343 3344 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3345 } else { 3346 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3347 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 3348 FDecl); 3349 Invalid |= Arg.isInvalid(); 3350 AllArgs.push_back(Arg.take()); 3351 } 3352 } 3353 3354 // Check for array bounds violations. 3355 for (unsigned i = ArgIx; i != NumArgs; ++i) 3356 CheckArrayAccess(Args[i]); 3357 } 3358 return Invalid; 3359} 3360 3361static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 3362 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 3363 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL)) 3364 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 3365 << ATL->getLocalSourceRange(); 3366} 3367 3368/// CheckStaticArrayArgument - If the given argument corresponds to a static 3369/// array parameter, check that it is non-null, and that if it is formed by 3370/// array-to-pointer decay, the underlying array is sufficiently large. 3371/// 3372/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 3373/// array type derivation, then for each call to the function, the value of the 3374/// corresponding actual argument shall provide access to the first element of 3375/// an array with at least as many elements as specified by the size expression. 3376void 3377Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 3378 ParmVarDecl *Param, 3379 const Expr *ArgExpr) { 3380 // Static array parameters are not supported in C++. 3381 if (!Param || getLangOptions().CPlusPlus) 3382 return; 3383 3384 QualType OrigTy = Param->getOriginalType(); 3385 3386 const ArrayType *AT = Context.getAsArrayType(OrigTy); 3387 if (!AT || AT->getSizeModifier() != ArrayType::Static) 3388 return; 3389 3390 if (ArgExpr->isNullPointerConstant(Context, 3391 Expr::NPC_NeverValueDependent)) { 3392 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 3393 DiagnoseCalleeStaticArrayParam(*this, Param); 3394 return; 3395 } 3396 3397 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 3398 if (!CAT) 3399 return; 3400 3401 const ConstantArrayType *ArgCAT = 3402 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 3403 if (!ArgCAT) 3404 return; 3405 3406 if (ArgCAT->getSize().ult(CAT->getSize())) { 3407 Diag(CallLoc, diag::warn_static_array_too_small) 3408 << ArgExpr->getSourceRange() 3409 << (unsigned) ArgCAT->getSize().getZExtValue() 3410 << (unsigned) CAT->getSize().getZExtValue(); 3411 DiagnoseCalleeStaticArrayParam(*this, Param); 3412 } 3413} 3414 3415/// Given a function expression of unknown-any type, try to rebuild it 3416/// to have a function type. 3417static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 3418 3419/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3420/// This provides the location of the left/right parens and a list of comma 3421/// locations. 3422ExprResult 3423Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3424 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3425 Expr *ExecConfig, bool IsExecConfig) { 3426 unsigned NumArgs = ArgExprs.size(); 3427 3428 // Since this might be a postfix expression, get rid of ParenListExprs. 3429 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3430 if (Result.isInvalid()) return ExprError(); 3431 Fn = Result.take(); 3432 3433 Expr **Args = ArgExprs.release(); 3434 3435 if (getLangOptions().CPlusPlus) { 3436 // If this is a pseudo-destructor expression, build the call immediately. 3437 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3438 if (NumArgs > 0) { 3439 // Pseudo-destructor calls should not have any arguments. 3440 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3441 << FixItHint::CreateRemoval( 3442 SourceRange(Args[0]->getLocStart(), 3443 Args[NumArgs-1]->getLocEnd())); 3444 3445 NumArgs = 0; 3446 } 3447 3448 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 3449 VK_RValue, RParenLoc)); 3450 } 3451 3452 // Determine whether this is a dependent call inside a C++ template, 3453 // in which case we won't do any semantic analysis now. 3454 // FIXME: Will need to cache the results of name lookup (including ADL) in 3455 // Fn. 3456 bool Dependent = false; 3457 if (Fn->isTypeDependent()) 3458 Dependent = true; 3459 else if (Expr::hasAnyTypeDependentArguments( 3460 llvm::makeArrayRef(Args, NumArgs))) 3461 Dependent = true; 3462 3463 if (Dependent) { 3464 if (ExecConfig) { 3465 return Owned(new (Context) CUDAKernelCallExpr( 3466 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs, 3467 Context.DependentTy, VK_RValue, RParenLoc)); 3468 } else { 3469 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 3470 Context.DependentTy, VK_RValue, 3471 RParenLoc)); 3472 } 3473 } 3474 3475 // Determine whether this is a call to an object (C++ [over.call.object]). 3476 if (Fn->getType()->isRecordType()) 3477 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 3478 RParenLoc)); 3479 3480 if (Fn->getType() == Context.UnknownAnyTy) { 3481 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3482 if (result.isInvalid()) return ExprError(); 3483 Fn = result.take(); 3484 } 3485 3486 if (Fn->getType() == Context.BoundMemberTy) { 3487 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3488 RParenLoc); 3489 } 3490 } 3491 3492 // Check for overloaded calls. This can happen even in C due to extensions. 3493 if (Fn->getType() == Context.OverloadTy) { 3494 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 3495 3496 // We aren't supposed to apply this logic for if there's an '&' involved. 3497 if (!find.HasFormOfMemberPointer) { 3498 OverloadExpr *ovl = find.Expression; 3499 if (isa<UnresolvedLookupExpr>(ovl)) { 3500 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 3501 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs, 3502 RParenLoc, ExecConfig); 3503 } else { 3504 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3505 RParenLoc); 3506 } 3507 } 3508 } 3509 3510 // If we're directly calling a function, get the appropriate declaration. 3511 if (Fn->getType() == Context.UnknownAnyTy) { 3512 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3513 if (result.isInvalid()) return ExprError(); 3514 Fn = result.take(); 3515 } 3516 3517 Expr *NakedFn = Fn->IgnoreParens(); 3518 3519 NamedDecl *NDecl = 0; 3520 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 3521 if (UnOp->getOpcode() == UO_AddrOf) 3522 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 3523 3524 if (isa<DeclRefExpr>(NakedFn)) 3525 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3526 else if (isa<MemberExpr>(NakedFn)) 3527 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 3528 3529 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc, 3530 ExecConfig, IsExecConfig); 3531} 3532 3533ExprResult 3534Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3535 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 3536 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 3537 if (!ConfigDecl) 3538 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 3539 << "cudaConfigureCall"); 3540 QualType ConfigQTy = ConfigDecl->getType(); 3541 3542 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 3543 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc); 3544 MarkFunctionReferenced(LLLLoc, ConfigDecl); 3545 3546 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 3547 /*IsExecConfig=*/true); 3548} 3549 3550/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 3551/// 3552/// __builtin_astype( value, dst type ) 3553/// 3554ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3555 SourceLocation BuiltinLoc, 3556 SourceLocation RParenLoc) { 3557 ExprValueKind VK = VK_RValue; 3558 ExprObjectKind OK = OK_Ordinary; 3559 QualType DstTy = GetTypeFromParser(ParsedDestTy); 3560 QualType SrcTy = E->getType(); 3561 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 3562 return ExprError(Diag(BuiltinLoc, 3563 diag::err_invalid_astype_of_different_size) 3564 << DstTy 3565 << SrcTy 3566 << E->getSourceRange()); 3567 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 3568 RParenLoc)); 3569} 3570 3571/// BuildResolvedCallExpr - Build a call to a resolved expression, 3572/// i.e. an expression not of \p OverloadTy. The expression should 3573/// unary-convert to an expression of function-pointer or 3574/// block-pointer type. 3575/// 3576/// \param NDecl the declaration being called, if available 3577ExprResult 3578Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3579 SourceLocation LParenLoc, 3580 Expr **Args, unsigned NumArgs, 3581 SourceLocation RParenLoc, 3582 Expr *Config, bool IsExecConfig) { 3583 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 3584 3585 // Promote the function operand. 3586 ExprResult Result = UsualUnaryConversions(Fn); 3587 if (Result.isInvalid()) 3588 return ExprError(); 3589 Fn = Result.take(); 3590 3591 // Make the call expr early, before semantic checks. This guarantees cleanup 3592 // of arguments and function on error. 3593 CallExpr *TheCall; 3594 if (Config) { 3595 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 3596 cast<CallExpr>(Config), 3597 Args, NumArgs, 3598 Context.BoolTy, 3599 VK_RValue, 3600 RParenLoc); 3601 } else { 3602 TheCall = new (Context) CallExpr(Context, Fn, 3603 Args, NumArgs, 3604 Context.BoolTy, 3605 VK_RValue, 3606 RParenLoc); 3607 } 3608 3609 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 3610 3611 // Bail out early if calling a builtin with custom typechecking. 3612 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 3613 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3614 3615 retry: 3616 const FunctionType *FuncT; 3617 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 3618 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 3619 // have type pointer to function". 3620 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 3621 if (FuncT == 0) 3622 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3623 << Fn->getType() << Fn->getSourceRange()); 3624 } else if (const BlockPointerType *BPT = 3625 Fn->getType()->getAs<BlockPointerType>()) { 3626 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 3627 } else { 3628 // Handle calls to expressions of unknown-any type. 3629 if (Fn->getType() == Context.UnknownAnyTy) { 3630 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 3631 if (rewrite.isInvalid()) return ExprError(); 3632 Fn = rewrite.take(); 3633 TheCall->setCallee(Fn); 3634 goto retry; 3635 } 3636 3637 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3638 << Fn->getType() << Fn->getSourceRange()); 3639 } 3640 3641 if (getLangOptions().CUDA) { 3642 if (Config) { 3643 // CUDA: Kernel calls must be to global functions 3644 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 3645 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 3646 << FDecl->getName() << Fn->getSourceRange()); 3647 3648 // CUDA: Kernel function must have 'void' return type 3649 if (!FuncT->getResultType()->isVoidType()) 3650 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 3651 << Fn->getType() << Fn->getSourceRange()); 3652 } else { 3653 // CUDA: Calls to global functions must be configured 3654 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 3655 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 3656 << FDecl->getName() << Fn->getSourceRange()); 3657 } 3658 } 3659 3660 // Check for a valid return type 3661 if (CheckCallReturnType(FuncT->getResultType(), 3662 Fn->getSourceRange().getBegin(), TheCall, 3663 FDecl)) 3664 return ExprError(); 3665 3666 // We know the result type of the call, set it. 3667 TheCall->setType(FuncT->getCallResultType(Context)); 3668 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 3669 3670 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 3671 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 3672 RParenLoc, IsExecConfig)) 3673 return ExprError(); 3674 } else { 3675 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 3676 3677 if (FDecl) { 3678 // Check if we have too few/too many template arguments, based 3679 // on our knowledge of the function definition. 3680 const FunctionDecl *Def = 0; 3681 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 3682 const FunctionProtoType *Proto 3683 = Def->getType()->getAs<FunctionProtoType>(); 3684 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 3685 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 3686 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 3687 } 3688 3689 // If the function we're calling isn't a function prototype, but we have 3690 // a function prototype from a prior declaratiom, use that prototype. 3691 if (!FDecl->hasPrototype()) 3692 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 3693 } 3694 3695 // Promote the arguments (C99 6.5.2.2p6). 3696 for (unsigned i = 0; i != NumArgs; i++) { 3697 Expr *Arg = Args[i]; 3698 3699 if (Proto && i < Proto->getNumArgs()) { 3700 InitializedEntity Entity 3701 = InitializedEntity::InitializeParameter(Context, 3702 Proto->getArgType(i), 3703 Proto->isArgConsumed(i)); 3704 ExprResult ArgE = PerformCopyInitialization(Entity, 3705 SourceLocation(), 3706 Owned(Arg)); 3707 if (ArgE.isInvalid()) 3708 return true; 3709 3710 Arg = ArgE.takeAs<Expr>(); 3711 3712 } else { 3713 ExprResult ArgE = DefaultArgumentPromotion(Arg); 3714 3715 if (ArgE.isInvalid()) 3716 return true; 3717 3718 Arg = ArgE.takeAs<Expr>(); 3719 } 3720 3721 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3722 Arg->getType(), 3723 PDiag(diag::err_call_incomplete_argument) 3724 << Arg->getSourceRange())) 3725 return ExprError(); 3726 3727 TheCall->setArg(i, Arg); 3728 } 3729 } 3730 3731 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3732 if (!Method->isStatic()) 3733 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 3734 << Fn->getSourceRange()); 3735 3736 // Check for sentinels 3737 if (NDecl) 3738 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 3739 3740 // Do special checking on direct calls to functions. 3741 if (FDecl) { 3742 if (CheckFunctionCall(FDecl, TheCall)) 3743 return ExprError(); 3744 3745 if (BuiltinID) 3746 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3747 } else if (NDecl) { 3748 if (CheckBlockCall(NDecl, TheCall)) 3749 return ExprError(); 3750 } 3751 3752 return MaybeBindToTemporary(TheCall); 3753} 3754 3755ExprResult 3756Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 3757 SourceLocation RParenLoc, Expr *InitExpr) { 3758 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 3759 // FIXME: put back this assert when initializers are worked out. 3760 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 3761 3762 TypeSourceInfo *TInfo; 3763 QualType literalType = GetTypeFromParser(Ty, &TInfo); 3764 if (!TInfo) 3765 TInfo = Context.getTrivialTypeSourceInfo(literalType); 3766 3767 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 3768} 3769 3770ExprResult 3771Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 3772 SourceLocation RParenLoc, Expr *LiteralExpr) { 3773 QualType literalType = TInfo->getType(); 3774 3775 if (literalType->isArrayType()) { 3776 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 3777 PDiag(diag::err_illegal_decl_array_incomplete_type) 3778 << SourceRange(LParenLoc, 3779 LiteralExpr->getSourceRange().getEnd()))) 3780 return ExprError(); 3781 if (literalType->isVariableArrayType()) 3782 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3783 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 3784 } else if (!literalType->isDependentType() && 3785 RequireCompleteType(LParenLoc, literalType, 3786 PDiag(diag::err_typecheck_decl_incomplete_type) 3787 << SourceRange(LParenLoc, 3788 LiteralExpr->getSourceRange().getEnd()))) 3789 return ExprError(); 3790 3791 InitializedEntity Entity 3792 = InitializedEntity::InitializeTemporary(literalType); 3793 InitializationKind Kind 3794 = InitializationKind::CreateCStyleCast(LParenLoc, 3795 SourceRange(LParenLoc, RParenLoc), 3796 /*InitList=*/true); 3797 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1); 3798 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3799 MultiExprArg(*this, &LiteralExpr, 1), 3800 &literalType); 3801 if (Result.isInvalid()) 3802 return ExprError(); 3803 LiteralExpr = Result.get(); 3804 3805 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3806 if (isFileScope) { // 6.5.2.5p3 3807 if (CheckForConstantInitializer(LiteralExpr, literalType)) 3808 return ExprError(); 3809 } 3810 3811 // In C, compound literals are l-values for some reason. 3812 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue; 3813 3814 return MaybeBindToTemporary( 3815 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 3816 VK, LiteralExpr, isFileScope)); 3817} 3818 3819ExprResult 3820Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 3821 SourceLocation RBraceLoc) { 3822 unsigned NumInit = InitArgList.size(); 3823 Expr **InitList = InitArgList.release(); 3824 3825 // Immediately handle non-overload placeholders. Overloads can be 3826 // resolved contextually, but everything else here can't. 3827 for (unsigned I = 0; I != NumInit; ++I) { 3828 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) { 3829 ExprResult result = CheckPlaceholderExpr(InitList[I]); 3830 3831 // Ignore failures; dropping the entire initializer list because 3832 // of one failure would be terrible for indexing/etc. 3833 if (result.isInvalid()) continue; 3834 3835 InitList[I] = result.take(); 3836 } 3837 } 3838 3839 // Semantic analysis for initializers is done by ActOnDeclarator() and 3840 // CheckInitializer() - it requires knowledge of the object being intialized. 3841 3842 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList, 3843 NumInit, RBraceLoc); 3844 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 3845 return Owned(E); 3846} 3847 3848/// Do an explicit extend of the given block pointer if we're in ARC. 3849static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 3850 assert(E.get()->getType()->isBlockPointerType()); 3851 assert(E.get()->isRValue()); 3852 3853 // Only do this in an r-value context. 3854 if (!S.getLangOptions().ObjCAutoRefCount) return; 3855 3856 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 3857 CK_ARCExtendBlockObject, E.get(), 3858 /*base path*/ 0, VK_RValue); 3859 S.ExprNeedsCleanups = true; 3860} 3861 3862/// Prepare a conversion of the given expression to an ObjC object 3863/// pointer type. 3864CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 3865 QualType type = E.get()->getType(); 3866 if (type->isObjCObjectPointerType()) { 3867 return CK_BitCast; 3868 } else if (type->isBlockPointerType()) { 3869 maybeExtendBlockObject(*this, E); 3870 return CK_BlockPointerToObjCPointerCast; 3871 } else { 3872 assert(type->isPointerType()); 3873 return CK_CPointerToObjCPointerCast; 3874 } 3875} 3876 3877/// Prepares for a scalar cast, performing all the necessary stages 3878/// except the final cast and returning the kind required. 3879CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 3880 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 3881 // Also, callers should have filtered out the invalid cases with 3882 // pointers. Everything else should be possible. 3883 3884 QualType SrcTy = Src.get()->getType(); 3885 if (const AtomicType *SrcAtomicTy = SrcTy->getAs<AtomicType>()) 3886 SrcTy = SrcAtomicTy->getValueType(); 3887 if (const AtomicType *DestAtomicTy = DestTy->getAs<AtomicType>()) 3888 DestTy = DestAtomicTy->getValueType(); 3889 3890 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 3891 return CK_NoOp; 3892 3893 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 3894 case Type::STK_MemberPointer: 3895 llvm_unreachable("member pointer type in C"); 3896 3897 case Type::STK_CPointer: 3898 case Type::STK_BlockPointer: 3899 case Type::STK_ObjCObjectPointer: 3900 switch (DestTy->getScalarTypeKind()) { 3901 case Type::STK_CPointer: 3902 return CK_BitCast; 3903 case Type::STK_BlockPointer: 3904 return (SrcKind == Type::STK_BlockPointer 3905 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 3906 case Type::STK_ObjCObjectPointer: 3907 if (SrcKind == Type::STK_ObjCObjectPointer) 3908 return CK_BitCast; 3909 if (SrcKind == Type::STK_CPointer) 3910 return CK_CPointerToObjCPointerCast; 3911 maybeExtendBlockObject(*this, Src); 3912 return CK_BlockPointerToObjCPointerCast; 3913 case Type::STK_Bool: 3914 return CK_PointerToBoolean; 3915 case Type::STK_Integral: 3916 return CK_PointerToIntegral; 3917 case Type::STK_Floating: 3918 case Type::STK_FloatingComplex: 3919 case Type::STK_IntegralComplex: 3920 case Type::STK_MemberPointer: 3921 llvm_unreachable("illegal cast from pointer"); 3922 } 3923 llvm_unreachable("Should have returned before this"); 3924 3925 case Type::STK_Bool: // casting from bool is like casting from an integer 3926 case Type::STK_Integral: 3927 switch (DestTy->getScalarTypeKind()) { 3928 case Type::STK_CPointer: 3929 case Type::STK_ObjCObjectPointer: 3930 case Type::STK_BlockPointer: 3931 if (Src.get()->isNullPointerConstant(Context, 3932 Expr::NPC_ValueDependentIsNull)) 3933 return CK_NullToPointer; 3934 return CK_IntegralToPointer; 3935 case Type::STK_Bool: 3936 return CK_IntegralToBoolean; 3937 case Type::STK_Integral: 3938 return CK_IntegralCast; 3939 case Type::STK_Floating: 3940 return CK_IntegralToFloating; 3941 case Type::STK_IntegralComplex: 3942 Src = ImpCastExprToType(Src.take(), 3943 DestTy->castAs<ComplexType>()->getElementType(), 3944 CK_IntegralCast); 3945 return CK_IntegralRealToComplex; 3946 case Type::STK_FloatingComplex: 3947 Src = ImpCastExprToType(Src.take(), 3948 DestTy->castAs<ComplexType>()->getElementType(), 3949 CK_IntegralToFloating); 3950 return CK_FloatingRealToComplex; 3951 case Type::STK_MemberPointer: 3952 llvm_unreachable("member pointer type in C"); 3953 } 3954 llvm_unreachable("Should have returned before this"); 3955 3956 case Type::STK_Floating: 3957 switch (DestTy->getScalarTypeKind()) { 3958 case Type::STK_Floating: 3959 return CK_FloatingCast; 3960 case Type::STK_Bool: 3961 return CK_FloatingToBoolean; 3962 case Type::STK_Integral: 3963 return CK_FloatingToIntegral; 3964 case Type::STK_FloatingComplex: 3965 Src = ImpCastExprToType(Src.take(), 3966 DestTy->castAs<ComplexType>()->getElementType(), 3967 CK_FloatingCast); 3968 return CK_FloatingRealToComplex; 3969 case Type::STK_IntegralComplex: 3970 Src = ImpCastExprToType(Src.take(), 3971 DestTy->castAs<ComplexType>()->getElementType(), 3972 CK_FloatingToIntegral); 3973 return CK_IntegralRealToComplex; 3974 case Type::STK_CPointer: 3975 case Type::STK_ObjCObjectPointer: 3976 case Type::STK_BlockPointer: 3977 llvm_unreachable("valid float->pointer cast?"); 3978 case Type::STK_MemberPointer: 3979 llvm_unreachable("member pointer type in C"); 3980 } 3981 llvm_unreachable("Should have returned before this"); 3982 3983 case Type::STK_FloatingComplex: 3984 switch (DestTy->getScalarTypeKind()) { 3985 case Type::STK_FloatingComplex: 3986 return CK_FloatingComplexCast; 3987 case Type::STK_IntegralComplex: 3988 return CK_FloatingComplexToIntegralComplex; 3989 case Type::STK_Floating: { 3990 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 3991 if (Context.hasSameType(ET, DestTy)) 3992 return CK_FloatingComplexToReal; 3993 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 3994 return CK_FloatingCast; 3995 } 3996 case Type::STK_Bool: 3997 return CK_FloatingComplexToBoolean; 3998 case Type::STK_Integral: 3999 Src = ImpCastExprToType(Src.take(), 4000 SrcTy->castAs<ComplexType>()->getElementType(), 4001 CK_FloatingComplexToReal); 4002 return CK_FloatingToIntegral; 4003 case Type::STK_CPointer: 4004 case Type::STK_ObjCObjectPointer: 4005 case Type::STK_BlockPointer: 4006 llvm_unreachable("valid complex float->pointer cast?"); 4007 case Type::STK_MemberPointer: 4008 llvm_unreachable("member pointer type in C"); 4009 } 4010 llvm_unreachable("Should have returned before this"); 4011 4012 case Type::STK_IntegralComplex: 4013 switch (DestTy->getScalarTypeKind()) { 4014 case Type::STK_FloatingComplex: 4015 return CK_IntegralComplexToFloatingComplex; 4016 case Type::STK_IntegralComplex: 4017 return CK_IntegralComplexCast; 4018 case Type::STK_Integral: { 4019 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4020 if (Context.hasSameType(ET, DestTy)) 4021 return CK_IntegralComplexToReal; 4022 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4023 return CK_IntegralCast; 4024 } 4025 case Type::STK_Bool: 4026 return CK_IntegralComplexToBoolean; 4027 case Type::STK_Floating: 4028 Src = ImpCastExprToType(Src.take(), 4029 SrcTy->castAs<ComplexType>()->getElementType(), 4030 CK_IntegralComplexToReal); 4031 return CK_IntegralToFloating; 4032 case Type::STK_CPointer: 4033 case Type::STK_ObjCObjectPointer: 4034 case Type::STK_BlockPointer: 4035 llvm_unreachable("valid complex int->pointer cast?"); 4036 case Type::STK_MemberPointer: 4037 llvm_unreachable("member pointer type in C"); 4038 } 4039 llvm_unreachable("Should have returned before this"); 4040 } 4041 4042 llvm_unreachable("Unhandled scalar cast"); 4043} 4044 4045bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4046 CastKind &Kind) { 4047 assert(VectorTy->isVectorType() && "Not a vector type!"); 4048 4049 if (Ty->isVectorType() || Ty->isIntegerType()) { 4050 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4051 return Diag(R.getBegin(), 4052 Ty->isVectorType() ? 4053 diag::err_invalid_conversion_between_vectors : 4054 diag::err_invalid_conversion_between_vector_and_integer) 4055 << VectorTy << Ty << R; 4056 } else 4057 return Diag(R.getBegin(), 4058 diag::err_invalid_conversion_between_vector_and_scalar) 4059 << VectorTy << Ty << R; 4060 4061 Kind = CK_BitCast; 4062 return false; 4063} 4064 4065ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4066 Expr *CastExpr, CastKind &Kind) { 4067 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4068 4069 QualType SrcTy = CastExpr->getType(); 4070 4071 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4072 // an ExtVectorType. 4073 // In OpenCL, casts between vectors of different types are not allowed. 4074 // (See OpenCL 6.2). 4075 if (SrcTy->isVectorType()) { 4076 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4077 || (getLangOptions().OpenCL && 4078 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4079 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4080 << DestTy << SrcTy << R; 4081 return ExprError(); 4082 } 4083 Kind = CK_BitCast; 4084 return Owned(CastExpr); 4085 } 4086 4087 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4088 // conversion will take place first from scalar to elt type, and then 4089 // splat from elt type to vector. 4090 if (SrcTy->isPointerType()) 4091 return Diag(R.getBegin(), 4092 diag::err_invalid_conversion_between_vector_and_scalar) 4093 << DestTy << SrcTy << R; 4094 4095 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4096 ExprResult CastExprRes = Owned(CastExpr); 4097 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4098 if (CastExprRes.isInvalid()) 4099 return ExprError(); 4100 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4101 4102 Kind = CK_VectorSplat; 4103 return Owned(CastExpr); 4104} 4105 4106ExprResult 4107Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4108 Declarator &D, ParsedType &Ty, 4109 SourceLocation RParenLoc, Expr *CastExpr) { 4110 assert(!D.isInvalidType() && (CastExpr != 0) && 4111 "ActOnCastExpr(): missing type or expr"); 4112 4113 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4114 if (D.isInvalidType()) 4115 return ExprError(); 4116 4117 if (getLangOptions().CPlusPlus) { 4118 // Check that there are no default arguments (C++ only). 4119 CheckExtraCXXDefaultArguments(D); 4120 } 4121 4122 checkUnusedDeclAttributes(D); 4123 4124 QualType castType = castTInfo->getType(); 4125 Ty = CreateParsedType(castType, castTInfo); 4126 4127 bool isVectorLiteral = false; 4128 4129 // Check for an altivec or OpenCL literal, 4130 // i.e. all the elements are integer constants. 4131 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4132 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4133 if ((getLangOptions().AltiVec || getLangOptions().OpenCL) 4134 && castType->isVectorType() && (PE || PLE)) { 4135 if (PLE && PLE->getNumExprs() == 0) { 4136 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4137 return ExprError(); 4138 } 4139 if (PE || PLE->getNumExprs() == 1) { 4140 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4141 if (!E->getType()->isVectorType()) 4142 isVectorLiteral = true; 4143 } 4144 else 4145 isVectorLiteral = true; 4146 } 4147 4148 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4149 // then handle it as such. 4150 if (isVectorLiteral) 4151 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4152 4153 // If the Expr being casted is a ParenListExpr, handle it specially. 4154 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4155 // sequence of BinOp comma operators. 4156 if (isa<ParenListExpr>(CastExpr)) { 4157 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4158 if (Result.isInvalid()) return ExprError(); 4159 CastExpr = Result.take(); 4160 } 4161 4162 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4163} 4164 4165ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4166 SourceLocation RParenLoc, Expr *E, 4167 TypeSourceInfo *TInfo) { 4168 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4169 "Expected paren or paren list expression"); 4170 4171 Expr **exprs; 4172 unsigned numExprs; 4173 Expr *subExpr; 4174 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4175 exprs = PE->getExprs(); 4176 numExprs = PE->getNumExprs(); 4177 } else { 4178 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4179 exprs = &subExpr; 4180 numExprs = 1; 4181 } 4182 4183 QualType Ty = TInfo->getType(); 4184 assert(Ty->isVectorType() && "Expected vector type"); 4185 4186 SmallVector<Expr *, 8> initExprs; 4187 const VectorType *VTy = Ty->getAs<VectorType>(); 4188 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4189 4190 // '(...)' form of vector initialization in AltiVec: the number of 4191 // initializers must be one or must match the size of the vector. 4192 // If a single value is specified in the initializer then it will be 4193 // replicated to all the components of the vector 4194 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4195 // The number of initializers must be one or must match the size of the 4196 // vector. If a single value is specified in the initializer then it will 4197 // be replicated to all the components of the vector 4198 if (numExprs == 1) { 4199 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4200 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4201 if (Literal.isInvalid()) 4202 return ExprError(); 4203 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4204 PrepareScalarCast(Literal, ElemTy)); 4205 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4206 } 4207 else if (numExprs < numElems) { 4208 Diag(E->getExprLoc(), 4209 diag::err_incorrect_number_of_vector_initializers); 4210 return ExprError(); 4211 } 4212 else 4213 initExprs.append(exprs, exprs + numExprs); 4214 } 4215 else { 4216 // For OpenCL, when the number of initializers is a single value, 4217 // it will be replicated to all components of the vector. 4218 if (getLangOptions().OpenCL && 4219 VTy->getVectorKind() == VectorType::GenericVector && 4220 numExprs == 1) { 4221 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4222 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4223 if (Literal.isInvalid()) 4224 return ExprError(); 4225 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4226 PrepareScalarCast(Literal, ElemTy)); 4227 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4228 } 4229 4230 initExprs.append(exprs, exprs + numExprs); 4231 } 4232 // FIXME: This means that pretty-printing the final AST will produce curly 4233 // braces instead of the original commas. 4234 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc, 4235 &initExprs[0], 4236 initExprs.size(), RParenLoc); 4237 initE->setType(Ty); 4238 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4239} 4240 4241/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4242/// the ParenListExpr into a sequence of comma binary operators. 4243ExprResult 4244Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4245 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4246 if (!E) 4247 return Owned(OrigExpr); 4248 4249 ExprResult Result(E->getExpr(0)); 4250 4251 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4252 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4253 E->getExpr(i)); 4254 4255 if (Result.isInvalid()) return ExprError(); 4256 4257 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4258} 4259 4260ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4261 SourceLocation R, 4262 MultiExprArg Val) { 4263 unsigned nexprs = Val.size(); 4264 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 4265 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 4266 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 4267 return Owned(expr); 4268} 4269 4270/// \brief Emit a specialized diagnostic when one expression is a null pointer 4271/// constant and the other is not a pointer. Returns true if a diagnostic is 4272/// emitted. 4273bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4274 SourceLocation QuestionLoc) { 4275 Expr *NullExpr = LHSExpr; 4276 Expr *NonPointerExpr = RHSExpr; 4277 Expr::NullPointerConstantKind NullKind = 4278 NullExpr->isNullPointerConstant(Context, 4279 Expr::NPC_ValueDependentIsNotNull); 4280 4281 if (NullKind == Expr::NPCK_NotNull) { 4282 NullExpr = RHSExpr; 4283 NonPointerExpr = LHSExpr; 4284 NullKind = 4285 NullExpr->isNullPointerConstant(Context, 4286 Expr::NPC_ValueDependentIsNotNull); 4287 } 4288 4289 if (NullKind == Expr::NPCK_NotNull) 4290 return false; 4291 4292 if (NullKind == Expr::NPCK_ZeroInteger) { 4293 // In this case, check to make sure that we got here from a "NULL" 4294 // string in the source code. 4295 NullExpr = NullExpr->IgnoreParenImpCasts(); 4296 SourceLocation loc = NullExpr->getExprLoc(); 4297 if (!findMacroSpelling(loc, "NULL")) 4298 return false; 4299 } 4300 4301 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr); 4302 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 4303 << NonPointerExpr->getType() << DiagType 4304 << NonPointerExpr->getSourceRange(); 4305 return true; 4306} 4307 4308/// \brief Return false if the condition expression is valid, true otherwise. 4309static bool checkCondition(Sema &S, Expr *Cond) { 4310 QualType CondTy = Cond->getType(); 4311 4312 // C99 6.5.15p2 4313 if (CondTy->isScalarType()) return false; 4314 4315 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 4316 if (S.getLangOptions().OpenCL && CondTy->isVectorType()) 4317 return false; 4318 4319 // Emit the proper error message. 4320 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ? 4321 diag::err_typecheck_cond_expect_scalar : 4322 diag::err_typecheck_cond_expect_scalar_or_vector) 4323 << CondTy; 4324 return true; 4325} 4326 4327/// \brief Return false if the two expressions can be converted to a vector, 4328/// true otherwise 4329static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 4330 ExprResult &RHS, 4331 QualType CondTy) { 4332 // Both operands should be of scalar type. 4333 if (!LHS.get()->getType()->isScalarType()) { 4334 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4335 << CondTy; 4336 return true; 4337 } 4338 if (!RHS.get()->getType()->isScalarType()) { 4339 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4340 << CondTy; 4341 return true; 4342 } 4343 4344 // Implicity convert these scalars to the type of the condition. 4345 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 4346 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 4347 return false; 4348} 4349 4350/// \brief Handle when one or both operands are void type. 4351static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 4352 ExprResult &RHS) { 4353 Expr *LHSExpr = LHS.get(); 4354 Expr *RHSExpr = RHS.get(); 4355 4356 if (!LHSExpr->getType()->isVoidType()) 4357 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4358 << RHSExpr->getSourceRange(); 4359 if (!RHSExpr->getType()->isVoidType()) 4360 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4361 << LHSExpr->getSourceRange(); 4362 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 4363 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 4364 return S.Context.VoidTy; 4365} 4366 4367/// \brief Return false if the NullExpr can be promoted to PointerTy, 4368/// true otherwise. 4369static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 4370 QualType PointerTy) { 4371 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 4372 !NullExpr.get()->isNullPointerConstant(S.Context, 4373 Expr::NPC_ValueDependentIsNull)) 4374 return true; 4375 4376 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 4377 return false; 4378} 4379 4380/// \brief Checks compatibility between two pointers and return the resulting 4381/// type. 4382static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 4383 ExprResult &RHS, 4384 SourceLocation Loc) { 4385 QualType LHSTy = LHS.get()->getType(); 4386 QualType RHSTy = RHS.get()->getType(); 4387 4388 if (S.Context.hasSameType(LHSTy, RHSTy)) { 4389 // Two identical pointers types are always compatible. 4390 return LHSTy; 4391 } 4392 4393 QualType lhptee, rhptee; 4394 4395 // Get the pointee types. 4396 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 4397 lhptee = LHSBTy->getPointeeType(); 4398 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 4399 } else { 4400 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 4401 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 4402 } 4403 4404 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4405 rhptee.getUnqualifiedType())) { 4406 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 4407 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4408 << RHS.get()->getSourceRange(); 4409 // In this situation, we assume void* type. No especially good 4410 // reason, but this is what gcc does, and we do have to pick 4411 // to get a consistent AST. 4412 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 4413 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4414 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4415 return incompatTy; 4416 } 4417 4418 // The pointer types are compatible. 4419 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 4420 // differently qualified versions of compatible types, the result type is 4421 // a pointer to an appropriately qualified version of the *composite* 4422 // type. 4423 // FIXME: Need to calculate the composite type. 4424 // FIXME: Need to add qualifiers 4425 4426 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast); 4427 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4428 return LHSTy; 4429} 4430 4431/// \brief Return the resulting type when the operands are both block pointers. 4432static QualType checkConditionalBlockPointerCompatibility(Sema &S, 4433 ExprResult &LHS, 4434 ExprResult &RHS, 4435 SourceLocation Loc) { 4436 QualType LHSTy = LHS.get()->getType(); 4437 QualType RHSTy = RHS.get()->getType(); 4438 4439 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4440 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4441 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 4442 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4443 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4444 return destType; 4445 } 4446 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 4447 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4448 << RHS.get()->getSourceRange(); 4449 return QualType(); 4450 } 4451 4452 // We have 2 block pointer types. 4453 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4454} 4455 4456/// \brief Return the resulting type when the operands are both pointers. 4457static QualType 4458checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 4459 ExprResult &RHS, 4460 SourceLocation Loc) { 4461 // get the pointer types 4462 QualType LHSTy = LHS.get()->getType(); 4463 QualType RHSTy = RHS.get()->getType(); 4464 4465 // get the "pointed to" types 4466 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4467 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4468 4469 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4470 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4471 // Figure out necessary qualifiers (C99 6.5.15p6) 4472 QualType destPointee 4473 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4474 QualType destType = S.Context.getPointerType(destPointee); 4475 // Add qualifiers if necessary. 4476 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4477 // Promote to void*. 4478 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4479 return destType; 4480 } 4481 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4482 QualType destPointee 4483 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4484 QualType destType = S.Context.getPointerType(destPointee); 4485 // Add qualifiers if necessary. 4486 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4487 // Promote to void*. 4488 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4489 return destType; 4490 } 4491 4492 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4493} 4494 4495/// \brief Return false if the first expression is not an integer and the second 4496/// expression is not a pointer, true otherwise. 4497static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 4498 Expr* PointerExpr, SourceLocation Loc, 4499 bool IsIntFirstExpr) { 4500 if (!PointerExpr->getType()->isPointerType() || 4501 !Int.get()->getType()->isIntegerType()) 4502 return false; 4503 4504 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 4505 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 4506 4507 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4508 << Expr1->getType() << Expr2->getType() 4509 << Expr1->getSourceRange() << Expr2->getSourceRange(); 4510 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 4511 CK_IntegralToPointer); 4512 return true; 4513} 4514 4515/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 4516/// In that case, LHS = cond. 4517/// C99 6.5.15 4518QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4519 ExprResult &RHS, ExprValueKind &VK, 4520 ExprObjectKind &OK, 4521 SourceLocation QuestionLoc) { 4522 4523 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 4524 if (!LHSResult.isUsable()) return QualType(); 4525 LHS = move(LHSResult); 4526 4527 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 4528 if (!RHSResult.isUsable()) return QualType(); 4529 RHS = move(RHSResult); 4530 4531 // C++ is sufficiently different to merit its own checker. 4532 if (getLangOptions().CPlusPlus) 4533 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 4534 4535 VK = VK_RValue; 4536 OK = OK_Ordinary; 4537 4538 Cond = UsualUnaryConversions(Cond.take()); 4539 if (Cond.isInvalid()) 4540 return QualType(); 4541 LHS = UsualUnaryConversions(LHS.take()); 4542 if (LHS.isInvalid()) 4543 return QualType(); 4544 RHS = UsualUnaryConversions(RHS.take()); 4545 if (RHS.isInvalid()) 4546 return QualType(); 4547 4548 QualType CondTy = Cond.get()->getType(); 4549 QualType LHSTy = LHS.get()->getType(); 4550 QualType RHSTy = RHS.get()->getType(); 4551 4552 // first, check the condition. 4553 if (checkCondition(*this, Cond.get())) 4554 return QualType(); 4555 4556 // Now check the two expressions. 4557 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 4558 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 4559 4560 // OpenCL: If the condition is a vector, and both operands are scalar, 4561 // attempt to implicity convert them to the vector type to act like the 4562 // built in select. 4563 if (getLangOptions().OpenCL && CondTy->isVectorType()) 4564 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 4565 return QualType(); 4566 4567 // If both operands have arithmetic type, do the usual arithmetic conversions 4568 // to find a common type: C99 6.5.15p3,5. 4569 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 4570 UsualArithmeticConversions(LHS, RHS); 4571 if (LHS.isInvalid() || RHS.isInvalid()) 4572 return QualType(); 4573 return LHS.get()->getType(); 4574 } 4575 4576 // If both operands are the same structure or union type, the result is that 4577 // type. 4578 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 4579 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 4580 if (LHSRT->getDecl() == RHSRT->getDecl()) 4581 // "If both the operands have structure or union type, the result has 4582 // that type." This implies that CV qualifiers are dropped. 4583 return LHSTy.getUnqualifiedType(); 4584 // FIXME: Type of conditional expression must be complete in C mode. 4585 } 4586 4587 // C99 6.5.15p5: "If both operands have void type, the result has void type." 4588 // The following || allows only one side to be void (a GCC-ism). 4589 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 4590 return checkConditionalVoidType(*this, LHS, RHS); 4591 } 4592 4593 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 4594 // the type of the other operand." 4595 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 4596 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 4597 4598 // All objective-c pointer type analysis is done here. 4599 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 4600 QuestionLoc); 4601 if (LHS.isInvalid() || RHS.isInvalid()) 4602 return QualType(); 4603 if (!compositeType.isNull()) 4604 return compositeType; 4605 4606 4607 // Handle block pointer types. 4608 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 4609 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 4610 QuestionLoc); 4611 4612 // Check constraints for C object pointers types (C99 6.5.15p3,6). 4613 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 4614 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 4615 QuestionLoc); 4616 4617 // GCC compatibility: soften pointer/integer mismatch. Note that 4618 // null pointers have been filtered out by this point. 4619 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 4620 /*isIntFirstExpr=*/true)) 4621 return RHSTy; 4622 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 4623 /*isIntFirstExpr=*/false)) 4624 return LHSTy; 4625 4626 // Emit a better diagnostic if one of the expressions is a null pointer 4627 // constant and the other is not a pointer type. In this case, the user most 4628 // likely forgot to take the address of the other expression. 4629 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4630 return QualType(); 4631 4632 // Otherwise, the operands are not compatible. 4633 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4634 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4635 << RHS.get()->getSourceRange(); 4636 return QualType(); 4637} 4638 4639/// FindCompositeObjCPointerType - Helper method to find composite type of 4640/// two objective-c pointer types of the two input expressions. 4641QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 4642 SourceLocation QuestionLoc) { 4643 QualType LHSTy = LHS.get()->getType(); 4644 QualType RHSTy = RHS.get()->getType(); 4645 4646 // Handle things like Class and struct objc_class*. Here we case the result 4647 // to the pseudo-builtin, because that will be implicitly cast back to the 4648 // redefinition type if an attempt is made to access its fields. 4649 if (LHSTy->isObjCClassType() && 4650 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 4651 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 4652 return LHSTy; 4653 } 4654 if (RHSTy->isObjCClassType() && 4655 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 4656 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 4657 return RHSTy; 4658 } 4659 // And the same for struct objc_object* / id 4660 if (LHSTy->isObjCIdType() && 4661 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 4662 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 4663 return LHSTy; 4664 } 4665 if (RHSTy->isObjCIdType() && 4666 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 4667 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 4668 return RHSTy; 4669 } 4670 // And the same for struct objc_selector* / SEL 4671 if (Context.isObjCSelType(LHSTy) && 4672 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 4673 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4674 return LHSTy; 4675 } 4676 if (Context.isObjCSelType(RHSTy) && 4677 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 4678 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 4679 return RHSTy; 4680 } 4681 // Check constraints for Objective-C object pointers types. 4682 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 4683 4684 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4685 // Two identical object pointer types are always compatible. 4686 return LHSTy; 4687 } 4688 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 4689 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 4690 QualType compositeType = LHSTy; 4691 4692 // If both operands are interfaces and either operand can be 4693 // assigned to the other, use that type as the composite 4694 // type. This allows 4695 // xxx ? (A*) a : (B*) b 4696 // where B is a subclass of A. 4697 // 4698 // Additionally, as for assignment, if either type is 'id' 4699 // allow silent coercion. Finally, if the types are 4700 // incompatible then make sure to use 'id' as the composite 4701 // type so the result is acceptable for sending messages to. 4702 4703 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 4704 // It could return the composite type. 4705 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 4706 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 4707 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 4708 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 4709 } else if ((LHSTy->isObjCQualifiedIdType() || 4710 RHSTy->isObjCQualifiedIdType()) && 4711 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 4712 // Need to handle "id<xx>" explicitly. 4713 // GCC allows qualified id and any Objective-C type to devolve to 4714 // id. Currently localizing to here until clear this should be 4715 // part of ObjCQualifiedIdTypesAreCompatible. 4716 compositeType = Context.getObjCIdType(); 4717 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 4718 compositeType = Context.getObjCIdType(); 4719 } else if (!(compositeType = 4720 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 4721 ; 4722 else { 4723 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 4724 << LHSTy << RHSTy 4725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4726 QualType incompatTy = Context.getObjCIdType(); 4727 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4728 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4729 return incompatTy; 4730 } 4731 // The object pointer types are compatible. 4732 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 4733 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 4734 return compositeType; 4735 } 4736 // Check Objective-C object pointer types and 'void *' 4737 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 4738 if (getLangOptions().ObjCAutoRefCount) { 4739 // ARC forbids the implicit conversion of object pointers to 'void *', 4740 // so these types are not compatible. 4741 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 4742 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4743 LHS = RHS = true; 4744 return QualType(); 4745 } 4746 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4747 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4748 QualType destPointee 4749 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4750 QualType destType = Context.getPointerType(destPointee); 4751 // Add qualifiers if necessary. 4752 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4753 // Promote to void*. 4754 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4755 return destType; 4756 } 4757 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 4758 if (getLangOptions().ObjCAutoRefCount) { 4759 // ARC forbids the implicit conversion of object pointers to 'void *', 4760 // so these types are not compatible. 4761 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 4762 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4763 LHS = RHS = true; 4764 return QualType(); 4765 } 4766 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4767 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4768 QualType destPointee 4769 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4770 QualType destType = Context.getPointerType(destPointee); 4771 // Add qualifiers if necessary. 4772 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4773 // Promote to void*. 4774 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4775 return destType; 4776 } 4777 return QualType(); 4778} 4779 4780/// SuggestParentheses - Emit a note with a fixit hint that wraps 4781/// ParenRange in parentheses. 4782static void SuggestParentheses(Sema &Self, SourceLocation Loc, 4783 const PartialDiagnostic &Note, 4784 SourceRange ParenRange) { 4785 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 4786 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 4787 EndLoc.isValid()) { 4788 Self.Diag(Loc, Note) 4789 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 4790 << FixItHint::CreateInsertion(EndLoc, ")"); 4791 } else { 4792 // We can't display the parentheses, so just show the bare note. 4793 Self.Diag(Loc, Note) << ParenRange; 4794 } 4795} 4796 4797static bool IsArithmeticOp(BinaryOperatorKind Opc) { 4798 return Opc >= BO_Mul && Opc <= BO_Shr; 4799} 4800 4801/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 4802/// expression, either using a built-in or overloaded operator, 4803/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 4804/// expression. 4805static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 4806 Expr **RHSExprs) { 4807 // Don't strip parenthesis: we should not warn if E is in parenthesis. 4808 E = E->IgnoreImpCasts(); 4809 E = E->IgnoreConversionOperator(); 4810 E = E->IgnoreImpCasts(); 4811 4812 // Built-in binary operator. 4813 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 4814 if (IsArithmeticOp(OP->getOpcode())) { 4815 *Opcode = OP->getOpcode(); 4816 *RHSExprs = OP->getRHS(); 4817 return true; 4818 } 4819 } 4820 4821 // Overloaded operator. 4822 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 4823 if (Call->getNumArgs() != 2) 4824 return false; 4825 4826 // Make sure this is really a binary operator that is safe to pass into 4827 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 4828 OverloadedOperatorKind OO = Call->getOperator(); 4829 if (OO < OO_Plus || OO > OO_Arrow) 4830 return false; 4831 4832 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 4833 if (IsArithmeticOp(OpKind)) { 4834 *Opcode = OpKind; 4835 *RHSExprs = Call->getArg(1); 4836 return true; 4837 } 4838 } 4839 4840 return false; 4841} 4842 4843static bool IsLogicOp(BinaryOperatorKind Opc) { 4844 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 4845} 4846 4847/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 4848/// or is a logical expression such as (x==y) which has int type, but is 4849/// commonly interpreted as boolean. 4850static bool ExprLooksBoolean(Expr *E) { 4851 E = E->IgnoreParenImpCasts(); 4852 4853 if (E->getType()->isBooleanType()) 4854 return true; 4855 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 4856 return IsLogicOp(OP->getOpcode()); 4857 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 4858 return OP->getOpcode() == UO_LNot; 4859 4860 return false; 4861} 4862 4863/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 4864/// and binary operator are mixed in a way that suggests the programmer assumed 4865/// the conditional operator has higher precedence, for example: 4866/// "int x = a + someBinaryCondition ? 1 : 2". 4867static void DiagnoseConditionalPrecedence(Sema &Self, 4868 SourceLocation OpLoc, 4869 Expr *Condition, 4870 Expr *LHSExpr, 4871 Expr *RHSExpr) { 4872 BinaryOperatorKind CondOpcode; 4873 Expr *CondRHS; 4874 4875 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 4876 return; 4877 if (!ExprLooksBoolean(CondRHS)) 4878 return; 4879 4880 // The condition is an arithmetic binary expression, with a right- 4881 // hand side that looks boolean, so warn. 4882 4883 Self.Diag(OpLoc, diag::warn_precedence_conditional) 4884 << Condition->getSourceRange() 4885 << BinaryOperator::getOpcodeStr(CondOpcode); 4886 4887 SuggestParentheses(Self, OpLoc, 4888 Self.PDiag(diag::note_precedence_conditional_silence) 4889 << BinaryOperator::getOpcodeStr(CondOpcode), 4890 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 4891 4892 SuggestParentheses(Self, OpLoc, 4893 Self.PDiag(diag::note_precedence_conditional_first), 4894 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 4895} 4896 4897/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 4898/// in the case of a the GNU conditional expr extension. 4899ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 4900 SourceLocation ColonLoc, 4901 Expr *CondExpr, Expr *LHSExpr, 4902 Expr *RHSExpr) { 4903 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 4904 // was the condition. 4905 OpaqueValueExpr *opaqueValue = 0; 4906 Expr *commonExpr = 0; 4907 if (LHSExpr == 0) { 4908 commonExpr = CondExpr; 4909 4910 // We usually want to apply unary conversions *before* saving, except 4911 // in the special case of a C++ l-value conditional. 4912 if (!(getLangOptions().CPlusPlus 4913 && !commonExpr->isTypeDependent() 4914 && commonExpr->getValueKind() == RHSExpr->getValueKind() 4915 && commonExpr->isGLValue() 4916 && commonExpr->isOrdinaryOrBitFieldObject() 4917 && RHSExpr->isOrdinaryOrBitFieldObject() 4918 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 4919 ExprResult commonRes = UsualUnaryConversions(commonExpr); 4920 if (commonRes.isInvalid()) 4921 return ExprError(); 4922 commonExpr = commonRes.take(); 4923 } 4924 4925 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 4926 commonExpr->getType(), 4927 commonExpr->getValueKind(), 4928 commonExpr->getObjectKind(), 4929 commonExpr); 4930 LHSExpr = CondExpr = opaqueValue; 4931 } 4932 4933 ExprValueKind VK = VK_RValue; 4934 ExprObjectKind OK = OK_Ordinary; 4935 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 4936 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 4937 VK, OK, QuestionLoc); 4938 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 4939 RHS.isInvalid()) 4940 return ExprError(); 4941 4942 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 4943 RHS.get()); 4944 4945 if (!commonExpr) 4946 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 4947 LHS.take(), ColonLoc, 4948 RHS.take(), result, VK, OK)); 4949 4950 return Owned(new (Context) 4951 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 4952 RHS.take(), QuestionLoc, ColonLoc, result, VK, 4953 OK)); 4954} 4955 4956// checkPointerTypesForAssignment - This is a very tricky routine (despite 4957// being closely modeled after the C99 spec:-). The odd characteristic of this 4958// routine is it effectively iqnores the qualifiers on the top level pointee. 4959// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 4960// FIXME: add a couple examples in this comment. 4961static Sema::AssignConvertType 4962checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 4963 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 4964 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 4965 4966 // get the "pointed to" type (ignoring qualifiers at the top level) 4967 const Type *lhptee, *rhptee; 4968 Qualifiers lhq, rhq; 4969 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 4970 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 4971 4972 Sema::AssignConvertType ConvTy = Sema::Compatible; 4973 4974 // C99 6.5.16.1p1: This following citation is common to constraints 4975 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 4976 // qualifiers of the type *pointed to* by the right; 4977 Qualifiers lq; 4978 4979 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 4980 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 4981 lhq.compatiblyIncludesObjCLifetime(rhq)) { 4982 // Ignore lifetime for further calculation. 4983 lhq.removeObjCLifetime(); 4984 rhq.removeObjCLifetime(); 4985 } 4986 4987 if (!lhq.compatiblyIncludes(rhq)) { 4988 // Treat address-space mismatches as fatal. TODO: address subspaces 4989 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 4990 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 4991 4992 // It's okay to add or remove GC or lifetime qualifiers when converting to 4993 // and from void*. 4994 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 4995 .compatiblyIncludes( 4996 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 4997 && (lhptee->isVoidType() || rhptee->isVoidType())) 4998 ; // keep old 4999 5000 // Treat lifetime mismatches as fatal. 5001 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5002 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5003 5004 // For GCC compatibility, other qualifier mismatches are treated 5005 // as still compatible in C. 5006 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5007 } 5008 5009 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5010 // incomplete type and the other is a pointer to a qualified or unqualified 5011 // version of void... 5012 if (lhptee->isVoidType()) { 5013 if (rhptee->isIncompleteOrObjectType()) 5014 return ConvTy; 5015 5016 // As an extension, we allow cast to/from void* to function pointer. 5017 assert(rhptee->isFunctionType()); 5018 return Sema::FunctionVoidPointer; 5019 } 5020 5021 if (rhptee->isVoidType()) { 5022 if (lhptee->isIncompleteOrObjectType()) 5023 return ConvTy; 5024 5025 // As an extension, we allow cast to/from void* to function pointer. 5026 assert(lhptee->isFunctionType()); 5027 return Sema::FunctionVoidPointer; 5028 } 5029 5030 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5031 // unqualified versions of compatible types, ... 5032 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5033 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5034 // Check if the pointee types are compatible ignoring the sign. 5035 // We explicitly check for char so that we catch "char" vs 5036 // "unsigned char" on systems where "char" is unsigned. 5037 if (lhptee->isCharType()) 5038 ltrans = S.Context.UnsignedCharTy; 5039 else if (lhptee->hasSignedIntegerRepresentation()) 5040 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5041 5042 if (rhptee->isCharType()) 5043 rtrans = S.Context.UnsignedCharTy; 5044 else if (rhptee->hasSignedIntegerRepresentation()) 5045 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5046 5047 if (ltrans == rtrans) { 5048 // Types are compatible ignoring the sign. Qualifier incompatibility 5049 // takes priority over sign incompatibility because the sign 5050 // warning can be disabled. 5051 if (ConvTy != Sema::Compatible) 5052 return ConvTy; 5053 5054 return Sema::IncompatiblePointerSign; 5055 } 5056 5057 // If we are a multi-level pointer, it's possible that our issue is simply 5058 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5059 // the eventual target type is the same and the pointers have the same 5060 // level of indirection, this must be the issue. 5061 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5062 do { 5063 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5064 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5065 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5066 5067 if (lhptee == rhptee) 5068 return Sema::IncompatibleNestedPointerQualifiers; 5069 } 5070 5071 // General pointer incompatibility takes priority over qualifiers. 5072 return Sema::IncompatiblePointer; 5073 } 5074 if (!S.getLangOptions().CPlusPlus && 5075 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5076 return Sema::IncompatiblePointer; 5077 return ConvTy; 5078} 5079 5080/// checkBlockPointerTypesForAssignment - This routine determines whether two 5081/// block pointer types are compatible or whether a block and normal pointer 5082/// are compatible. It is more restrict than comparing two function pointer 5083// types. 5084static Sema::AssignConvertType 5085checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5086 QualType RHSType) { 5087 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5088 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5089 5090 QualType lhptee, rhptee; 5091 5092 // get the "pointed to" type (ignoring qualifiers at the top level) 5093 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5094 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5095 5096 // In C++, the types have to match exactly. 5097 if (S.getLangOptions().CPlusPlus) 5098 return Sema::IncompatibleBlockPointer; 5099 5100 Sema::AssignConvertType ConvTy = Sema::Compatible; 5101 5102 // For blocks we enforce that qualifiers are identical. 5103 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5104 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5105 5106 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5107 return Sema::IncompatibleBlockPointer; 5108 5109 return ConvTy; 5110} 5111 5112/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5113/// for assignment compatibility. 5114static Sema::AssignConvertType 5115checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5116 QualType RHSType) { 5117 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5118 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5119 5120 if (LHSType->isObjCBuiltinType()) { 5121 // Class is not compatible with ObjC object pointers. 5122 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5123 !RHSType->isObjCQualifiedClassType()) 5124 return Sema::IncompatiblePointer; 5125 return Sema::Compatible; 5126 } 5127 if (RHSType->isObjCBuiltinType()) { 5128 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5129 !LHSType->isObjCQualifiedClassType()) 5130 return Sema::IncompatiblePointer; 5131 return Sema::Compatible; 5132 } 5133 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5134 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5135 5136 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5137 // make an exception for id<P> 5138 !LHSType->isObjCQualifiedIdType()) 5139 return Sema::CompatiblePointerDiscardsQualifiers; 5140 5141 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5142 return Sema::Compatible; 5143 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5144 return Sema::IncompatibleObjCQualifiedId; 5145 return Sema::IncompatiblePointer; 5146} 5147 5148Sema::AssignConvertType 5149Sema::CheckAssignmentConstraints(SourceLocation Loc, 5150 QualType LHSType, QualType RHSType) { 5151 // Fake up an opaque expression. We don't actually care about what 5152 // cast operations are required, so if CheckAssignmentConstraints 5153 // adds casts to this they'll be wasted, but fortunately that doesn't 5154 // usually happen on valid code. 5155 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5156 ExprResult RHSPtr = &RHSExpr; 5157 CastKind K = CK_Invalid; 5158 5159 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5160} 5161 5162/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5163/// has code to accommodate several GCC extensions when type checking 5164/// pointers. Here are some objectionable examples that GCC considers warnings: 5165/// 5166/// int a, *pint; 5167/// short *pshort; 5168/// struct foo *pfoo; 5169/// 5170/// pint = pshort; // warning: assignment from incompatible pointer type 5171/// a = pint; // warning: assignment makes integer from pointer without a cast 5172/// pint = a; // warning: assignment makes pointer from integer without a cast 5173/// pint = pfoo; // warning: assignment from incompatible pointer type 5174/// 5175/// As a result, the code for dealing with pointers is more complex than the 5176/// C99 spec dictates. 5177/// 5178/// Sets 'Kind' for any result kind except Incompatible. 5179Sema::AssignConvertType 5180Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5181 CastKind &Kind) { 5182 QualType RHSType = RHS.get()->getType(); 5183 QualType OrigLHSType = LHSType; 5184 5185 // Get canonical types. We're not formatting these types, just comparing 5186 // them. 5187 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5188 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5189 5190 5191 // Common case: no conversion required. 5192 if (LHSType == RHSType) { 5193 Kind = CK_NoOp; 5194 return Compatible; 5195 } 5196 5197 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5198 if (AtomicTy->getValueType() == RHSType) { 5199 Kind = CK_NonAtomicToAtomic; 5200 return Compatible; 5201 } 5202 } 5203 5204 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(RHSType)) { 5205 if (AtomicTy->getValueType() == LHSType) { 5206 Kind = CK_AtomicToNonAtomic; 5207 return Compatible; 5208 } 5209 } 5210 5211 5212 // If the left-hand side is a reference type, then we are in a 5213 // (rare!) case where we've allowed the use of references in C, 5214 // e.g., as a parameter type in a built-in function. In this case, 5215 // just make sure that the type referenced is compatible with the 5216 // right-hand side type. The caller is responsible for adjusting 5217 // LHSType so that the resulting expression does not have reference 5218 // type. 5219 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5220 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5221 Kind = CK_LValueBitCast; 5222 return Compatible; 5223 } 5224 return Incompatible; 5225 } 5226 5227 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5228 // to the same ExtVector type. 5229 if (LHSType->isExtVectorType()) { 5230 if (RHSType->isExtVectorType()) 5231 return Incompatible; 5232 if (RHSType->isArithmeticType()) { 5233 // CK_VectorSplat does T -> vector T, so first cast to the 5234 // element type. 5235 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5236 if (elType != RHSType) { 5237 Kind = PrepareScalarCast(RHS, elType); 5238 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5239 } 5240 Kind = CK_VectorSplat; 5241 return Compatible; 5242 } 5243 } 5244 5245 // Conversions to or from vector type. 5246 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5247 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5248 // Allow assignments of an AltiVec vector type to an equivalent GCC 5249 // vector type and vice versa 5250 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5251 Kind = CK_BitCast; 5252 return Compatible; 5253 } 5254 5255 // If we are allowing lax vector conversions, and LHS and RHS are both 5256 // vectors, the total size only needs to be the same. This is a bitcast; 5257 // no bits are changed but the result type is different. 5258 if (getLangOptions().LaxVectorConversions && 5259 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5260 Kind = CK_BitCast; 5261 return IncompatibleVectors; 5262 } 5263 } 5264 return Incompatible; 5265 } 5266 5267 // Arithmetic conversions. 5268 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5269 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) { 5270 Kind = PrepareScalarCast(RHS, LHSType); 5271 return Compatible; 5272 } 5273 5274 // Conversions to normal pointers. 5275 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5276 // U* -> T* 5277 if (isa<PointerType>(RHSType)) { 5278 Kind = CK_BitCast; 5279 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 5280 } 5281 5282 // int -> T* 5283 if (RHSType->isIntegerType()) { 5284 Kind = CK_IntegralToPointer; // FIXME: null? 5285 return IntToPointer; 5286 } 5287 5288 // C pointers are not compatible with ObjC object pointers, 5289 // with two exceptions: 5290 if (isa<ObjCObjectPointerType>(RHSType)) { 5291 // - conversions to void* 5292 if (LHSPointer->getPointeeType()->isVoidType()) { 5293 Kind = CK_BitCast; 5294 return Compatible; 5295 } 5296 5297 // - conversions from 'Class' to the redefinition type 5298 if (RHSType->isObjCClassType() && 5299 Context.hasSameType(LHSType, 5300 Context.getObjCClassRedefinitionType())) { 5301 Kind = CK_BitCast; 5302 return Compatible; 5303 } 5304 5305 Kind = CK_BitCast; 5306 return IncompatiblePointer; 5307 } 5308 5309 // U^ -> void* 5310 if (RHSType->getAs<BlockPointerType>()) { 5311 if (LHSPointer->getPointeeType()->isVoidType()) { 5312 Kind = CK_BitCast; 5313 return Compatible; 5314 } 5315 } 5316 5317 return Incompatible; 5318 } 5319 5320 // Conversions to block pointers. 5321 if (isa<BlockPointerType>(LHSType)) { 5322 // U^ -> T^ 5323 if (RHSType->isBlockPointerType()) { 5324 Kind = CK_BitCast; 5325 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 5326 } 5327 5328 // int or null -> T^ 5329 if (RHSType->isIntegerType()) { 5330 Kind = CK_IntegralToPointer; // FIXME: null 5331 return IntToBlockPointer; 5332 } 5333 5334 // id -> T^ 5335 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) { 5336 Kind = CK_AnyPointerToBlockPointerCast; 5337 return Compatible; 5338 } 5339 5340 // void* -> T^ 5341 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 5342 if (RHSPT->getPointeeType()->isVoidType()) { 5343 Kind = CK_AnyPointerToBlockPointerCast; 5344 return Compatible; 5345 } 5346 5347 return Incompatible; 5348 } 5349 5350 // Conversions to Objective-C pointers. 5351 if (isa<ObjCObjectPointerType>(LHSType)) { 5352 // A* -> B* 5353 if (RHSType->isObjCObjectPointerType()) { 5354 Kind = CK_BitCast; 5355 Sema::AssignConvertType result = 5356 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 5357 if (getLangOptions().ObjCAutoRefCount && 5358 result == Compatible && 5359 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 5360 result = IncompatibleObjCWeakRef; 5361 return result; 5362 } 5363 5364 // int or null -> A* 5365 if (RHSType->isIntegerType()) { 5366 Kind = CK_IntegralToPointer; // FIXME: null 5367 return IntToPointer; 5368 } 5369 5370 // In general, C pointers are not compatible with ObjC object pointers, 5371 // with two exceptions: 5372 if (isa<PointerType>(RHSType)) { 5373 Kind = CK_CPointerToObjCPointerCast; 5374 5375 // - conversions from 'void*' 5376 if (RHSType->isVoidPointerType()) { 5377 return Compatible; 5378 } 5379 5380 // - conversions to 'Class' from its redefinition type 5381 if (LHSType->isObjCClassType() && 5382 Context.hasSameType(RHSType, 5383 Context.getObjCClassRedefinitionType())) { 5384 return Compatible; 5385 } 5386 5387 return IncompatiblePointer; 5388 } 5389 5390 // T^ -> A* 5391 if (RHSType->isBlockPointerType()) { 5392 maybeExtendBlockObject(*this, RHS); 5393 Kind = CK_BlockPointerToObjCPointerCast; 5394 return Compatible; 5395 } 5396 5397 return Incompatible; 5398 } 5399 5400 // Conversions from pointers that are not covered by the above. 5401 if (isa<PointerType>(RHSType)) { 5402 // T* -> _Bool 5403 if (LHSType == Context.BoolTy) { 5404 Kind = CK_PointerToBoolean; 5405 return Compatible; 5406 } 5407 5408 // T* -> int 5409 if (LHSType->isIntegerType()) { 5410 Kind = CK_PointerToIntegral; 5411 return PointerToInt; 5412 } 5413 5414 return Incompatible; 5415 } 5416 5417 // Conversions from Objective-C pointers that are not covered by the above. 5418 if (isa<ObjCObjectPointerType>(RHSType)) { 5419 // T* -> _Bool 5420 if (LHSType == Context.BoolTy) { 5421 Kind = CK_PointerToBoolean; 5422 return Compatible; 5423 } 5424 5425 // T* -> int 5426 if (LHSType->isIntegerType()) { 5427 Kind = CK_PointerToIntegral; 5428 return PointerToInt; 5429 } 5430 5431 return Incompatible; 5432 } 5433 5434 // struct A -> struct B 5435 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 5436 if (Context.typesAreCompatible(LHSType, RHSType)) { 5437 Kind = CK_NoOp; 5438 return Compatible; 5439 } 5440 } 5441 5442 return Incompatible; 5443} 5444 5445/// \brief Constructs a transparent union from an expression that is 5446/// used to initialize the transparent union. 5447static void ConstructTransparentUnion(Sema &S, ASTContext &C, 5448 ExprResult &EResult, QualType UnionType, 5449 FieldDecl *Field) { 5450 // Build an initializer list that designates the appropriate member 5451 // of the transparent union. 5452 Expr *E = EResult.take(); 5453 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 5454 &E, 1, 5455 SourceLocation()); 5456 Initializer->setType(UnionType); 5457 Initializer->setInitializedFieldInUnion(Field); 5458 5459 // Build a compound literal constructing a value of the transparent 5460 // union type from this initializer list. 5461 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 5462 EResult = S.Owned( 5463 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 5464 VK_RValue, Initializer, false)); 5465} 5466 5467Sema::AssignConvertType 5468Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 5469 ExprResult &RHS) { 5470 QualType RHSType = RHS.get()->getType(); 5471 5472 // If the ArgType is a Union type, we want to handle a potential 5473 // transparent_union GCC extension. 5474 const RecordType *UT = ArgType->getAsUnionType(); 5475 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5476 return Incompatible; 5477 5478 // The field to initialize within the transparent union. 5479 RecordDecl *UD = UT->getDecl(); 5480 FieldDecl *InitField = 0; 5481 // It's compatible if the expression matches any of the fields. 5482 for (RecordDecl::field_iterator it = UD->field_begin(), 5483 itend = UD->field_end(); 5484 it != itend; ++it) { 5485 if (it->getType()->isPointerType()) { 5486 // If the transparent union contains a pointer type, we allow: 5487 // 1) void pointer 5488 // 2) null pointer constant 5489 if (RHSType->isPointerType()) 5490 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 5491 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 5492 InitField = *it; 5493 break; 5494 } 5495 5496 if (RHS.get()->isNullPointerConstant(Context, 5497 Expr::NPC_ValueDependentIsNull)) { 5498 RHS = ImpCastExprToType(RHS.take(), it->getType(), 5499 CK_NullToPointer); 5500 InitField = *it; 5501 break; 5502 } 5503 } 5504 5505 CastKind Kind = CK_Invalid; 5506 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 5507 == Compatible) { 5508 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 5509 InitField = *it; 5510 break; 5511 } 5512 } 5513 5514 if (!InitField) 5515 return Incompatible; 5516 5517 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 5518 return Compatible; 5519} 5520 5521Sema::AssignConvertType 5522Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5523 bool Diagnose) { 5524 if (getLangOptions().CPlusPlus) { 5525 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 5526 // C++ 5.17p3: If the left operand is not of class type, the 5527 // expression is implicitly converted (C++ 4) to the 5528 // cv-unqualified type of the left operand. 5529 ExprResult Res; 5530 if (Diagnose) { 5531 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5532 AA_Assigning); 5533 } else { 5534 ImplicitConversionSequence ICS = 5535 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5536 /*SuppressUserConversions=*/false, 5537 /*AllowExplicit=*/false, 5538 /*InOverloadResolution=*/false, 5539 /*CStyle=*/false, 5540 /*AllowObjCWritebackConversion=*/false); 5541 if (ICS.isFailure()) 5542 return Incompatible; 5543 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5544 ICS, AA_Assigning); 5545 } 5546 if (Res.isInvalid()) 5547 return Incompatible; 5548 Sema::AssignConvertType result = Compatible; 5549 if (getLangOptions().ObjCAutoRefCount && 5550 !CheckObjCARCUnavailableWeakConversion(LHSType, 5551 RHS.get()->getType())) 5552 result = IncompatibleObjCWeakRef; 5553 RHS = move(Res); 5554 return result; 5555 } 5556 5557 // FIXME: Currently, we fall through and treat C++ classes like C 5558 // structures. 5559 // FIXME: We also fall through for atomics; not sure what should 5560 // happen there, though. 5561 } 5562 5563 // C99 6.5.16.1p1: the left operand is a pointer and the right is 5564 // a null pointer constant. 5565 if ((LHSType->isPointerType() || 5566 LHSType->isObjCObjectPointerType() || 5567 LHSType->isBlockPointerType()) 5568 && RHS.get()->isNullPointerConstant(Context, 5569 Expr::NPC_ValueDependentIsNull)) { 5570 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 5571 return Compatible; 5572 } 5573 5574 // This check seems unnatural, however it is necessary to ensure the proper 5575 // conversion of functions/arrays. If the conversion were done for all 5576 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 5577 // expressions that suppress this implicit conversion (&, sizeof). 5578 // 5579 // Suppress this for references: C++ 8.5.3p5. 5580 if (!LHSType->isReferenceType()) { 5581 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5582 if (RHS.isInvalid()) 5583 return Incompatible; 5584 } 5585 5586 CastKind Kind = CK_Invalid; 5587 Sema::AssignConvertType result = 5588 CheckAssignmentConstraints(LHSType, RHS, Kind); 5589 5590 // C99 6.5.16.1p2: The value of the right operand is converted to the 5591 // type of the assignment expression. 5592 // CheckAssignmentConstraints allows the left-hand side to be a reference, 5593 // so that we can use references in built-in functions even in C. 5594 // The getNonReferenceType() call makes sure that the resulting expression 5595 // does not have reference type. 5596 if (result != Incompatible && RHS.get()->getType() != LHSType) 5597 RHS = ImpCastExprToType(RHS.take(), 5598 LHSType.getNonLValueExprType(Context), Kind); 5599 return result; 5600} 5601 5602QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 5603 ExprResult &RHS) { 5604 Diag(Loc, diag::err_typecheck_invalid_operands) 5605 << LHS.get()->getType() << RHS.get()->getType() 5606 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5607 return QualType(); 5608} 5609 5610QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 5611 SourceLocation Loc, bool IsCompAssign) { 5612 if (!IsCompAssign) { 5613 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 5614 if (LHS.isInvalid()) 5615 return QualType(); 5616 } 5617 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5618 if (RHS.isInvalid()) 5619 return QualType(); 5620 5621 // For conversion purposes, we ignore any qualifiers. 5622 // For example, "const float" and "float" are equivalent. 5623 QualType LHSType = 5624 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 5625 QualType RHSType = 5626 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 5627 5628 // If the vector types are identical, return. 5629 if (LHSType == RHSType) 5630 return LHSType; 5631 5632 // Handle the case of equivalent AltiVec and GCC vector types 5633 if (LHSType->isVectorType() && RHSType->isVectorType() && 5634 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5635 if (LHSType->isExtVectorType()) { 5636 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5637 return LHSType; 5638 } 5639 5640 if (!IsCompAssign) 5641 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 5642 return RHSType; 5643 } 5644 5645 if (getLangOptions().LaxVectorConversions && 5646 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 5647 // If we are allowing lax vector conversions, and LHS and RHS are both 5648 // vectors, the total size only needs to be the same. This is a 5649 // bitcast; no bits are changed but the result type is different. 5650 // FIXME: Should we really be allowing this? 5651 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5652 return LHSType; 5653 } 5654 5655 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 5656 // swap back (so that we don't reverse the inputs to a subtract, for instance. 5657 bool swapped = false; 5658 if (RHSType->isExtVectorType() && !IsCompAssign) { 5659 swapped = true; 5660 std::swap(RHS, LHS); 5661 std::swap(RHSType, LHSType); 5662 } 5663 5664 // Handle the case of an ext vector and scalar. 5665 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 5666 QualType EltTy = LV->getElementType(); 5667 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 5668 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 5669 if (order > 0) 5670 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 5671 if (order >= 0) { 5672 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5673 if (swapped) std::swap(RHS, LHS); 5674 return LHSType; 5675 } 5676 } 5677 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 5678 RHSType->isRealFloatingType()) { 5679 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 5680 if (order > 0) 5681 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 5682 if (order >= 0) { 5683 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5684 if (swapped) std::swap(RHS, LHS); 5685 return LHSType; 5686 } 5687 } 5688 } 5689 5690 // Vectors of different size or scalar and non-ext-vector are errors. 5691 if (swapped) std::swap(RHS, LHS); 5692 Diag(Loc, diag::err_typecheck_vector_not_convertable) 5693 << LHS.get()->getType() << RHS.get()->getType() 5694 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5695 return QualType(); 5696} 5697 5698// checkArithmeticNull - Detect when a NULL constant is used improperly in an 5699// expression. These are mainly cases where the null pointer is used as an 5700// integer instead of a pointer. 5701static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 5702 SourceLocation Loc, bool IsCompare) { 5703 // The canonical way to check for a GNU null is with isNullPointerConstant, 5704 // but we use a bit of a hack here for speed; this is a relatively 5705 // hot path, and isNullPointerConstant is slow. 5706 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 5707 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 5708 5709 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 5710 5711 // Avoid analyzing cases where the result will either be invalid (and 5712 // diagnosed as such) or entirely valid and not something to warn about. 5713 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 5714 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 5715 return; 5716 5717 // Comparison operations would not make sense with a null pointer no matter 5718 // what the other expression is. 5719 if (!IsCompare) { 5720 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 5721 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 5722 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 5723 return; 5724 } 5725 5726 // The rest of the operations only make sense with a null pointer 5727 // if the other expression is a pointer. 5728 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 5729 NonNullType->canDecayToPointerType()) 5730 return; 5731 5732 S.Diag(Loc, diag::warn_null_in_comparison_operation) 5733 << LHSNull /* LHS is NULL */ << NonNullType 5734 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5735} 5736 5737QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 5738 SourceLocation Loc, 5739 bool IsCompAssign, bool IsDiv) { 5740 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 5741 5742 if (LHS.get()->getType()->isVectorType() || 5743 RHS.get()->getType()->isVectorType()) 5744 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 5745 5746 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 5747 if (LHS.isInvalid() || RHS.isInvalid()) 5748 return QualType(); 5749 5750 5751 if (!LHS.get()->getType()->isArithmeticType() || 5752 !RHS.get()->getType()->isArithmeticType()) { 5753 if (IsCompAssign && 5754 LHS.get()->getType()->isAtomicType() && 5755 RHS.get()->getType()->isArithmeticType()) 5756 return compType; 5757 return InvalidOperands(Loc, LHS, RHS); 5758 } 5759 5760 // Check for division by zero. 5761 if (IsDiv && 5762 RHS.get()->isNullPointerConstant(Context, 5763 Expr::NPC_ValueDependentIsNotNull)) 5764 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 5765 << RHS.get()->getSourceRange()); 5766 5767 return compType; 5768} 5769 5770QualType Sema::CheckRemainderOperands( 5771 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 5772 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 5773 5774 if (LHS.get()->getType()->isVectorType() || 5775 RHS.get()->getType()->isVectorType()) { 5776 if (LHS.get()->getType()->hasIntegerRepresentation() && 5777 RHS.get()->getType()->hasIntegerRepresentation()) 5778 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 5779 return InvalidOperands(Loc, LHS, RHS); 5780 } 5781 5782 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 5783 if (LHS.isInvalid() || RHS.isInvalid()) 5784 return QualType(); 5785 5786 if (!LHS.get()->getType()->isIntegerType() || 5787 !RHS.get()->getType()->isIntegerType()) 5788 return InvalidOperands(Loc, LHS, RHS); 5789 5790 // Check for remainder by zero. 5791 if (RHS.get()->isNullPointerConstant(Context, 5792 Expr::NPC_ValueDependentIsNotNull)) 5793 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 5794 << RHS.get()->getSourceRange()); 5795 5796 return compType; 5797} 5798 5799/// \brief Diagnose invalid arithmetic on two void pointers. 5800static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 5801 Expr *LHSExpr, Expr *RHSExpr) { 5802 S.Diag(Loc, S.getLangOptions().CPlusPlus 5803 ? diag::err_typecheck_pointer_arith_void_type 5804 : diag::ext_gnu_void_ptr) 5805 << 1 /* two pointers */ << LHSExpr->getSourceRange() 5806 << RHSExpr->getSourceRange(); 5807} 5808 5809/// \brief Diagnose invalid arithmetic on a void pointer. 5810static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 5811 Expr *Pointer) { 5812 S.Diag(Loc, S.getLangOptions().CPlusPlus 5813 ? diag::err_typecheck_pointer_arith_void_type 5814 : diag::ext_gnu_void_ptr) 5815 << 0 /* one pointer */ << Pointer->getSourceRange(); 5816} 5817 5818/// \brief Diagnose invalid arithmetic on two function pointers. 5819static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 5820 Expr *LHS, Expr *RHS) { 5821 assert(LHS->getType()->isAnyPointerType()); 5822 assert(RHS->getType()->isAnyPointerType()); 5823 S.Diag(Loc, S.getLangOptions().CPlusPlus 5824 ? diag::err_typecheck_pointer_arith_function_type 5825 : diag::ext_gnu_ptr_func_arith) 5826 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 5827 // We only show the second type if it differs from the first. 5828 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 5829 RHS->getType()) 5830 << RHS->getType()->getPointeeType() 5831 << LHS->getSourceRange() << RHS->getSourceRange(); 5832} 5833 5834/// \brief Diagnose invalid arithmetic on a function pointer. 5835static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 5836 Expr *Pointer) { 5837 assert(Pointer->getType()->isAnyPointerType()); 5838 S.Diag(Loc, S.getLangOptions().CPlusPlus 5839 ? diag::err_typecheck_pointer_arith_function_type 5840 : diag::ext_gnu_ptr_func_arith) 5841 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 5842 << 0 /* one pointer, so only one type */ 5843 << Pointer->getSourceRange(); 5844} 5845 5846/// \brief Emit error if Operand is incomplete pointer type 5847/// 5848/// \returns True if pointer has incomplete type 5849static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 5850 Expr *Operand) { 5851 if ((Operand->getType()->isPointerType() && 5852 !Operand->getType()->isDependentType()) || 5853 Operand->getType()->isObjCObjectPointerType()) { 5854 QualType PointeeTy = Operand->getType()->getPointeeType(); 5855 if (S.RequireCompleteType( 5856 Loc, PointeeTy, 5857 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type) 5858 << PointeeTy << Operand->getSourceRange())) 5859 return true; 5860 } 5861 return false; 5862} 5863 5864/// \brief Check the validity of an arithmetic pointer operand. 5865/// 5866/// If the operand has pointer type, this code will check for pointer types 5867/// which are invalid in arithmetic operations. These will be diagnosed 5868/// appropriately, including whether or not the use is supported as an 5869/// extension. 5870/// 5871/// \returns True when the operand is valid to use (even if as an extension). 5872static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 5873 Expr *Operand) { 5874 if (!Operand->getType()->isAnyPointerType()) return true; 5875 5876 QualType PointeeTy = Operand->getType()->getPointeeType(); 5877 if (PointeeTy->isVoidType()) { 5878 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 5879 return !S.getLangOptions().CPlusPlus; 5880 } 5881 if (PointeeTy->isFunctionType()) { 5882 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 5883 return !S.getLangOptions().CPlusPlus; 5884 } 5885 5886 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 5887 5888 return true; 5889} 5890 5891/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 5892/// operands. 5893/// 5894/// This routine will diagnose any invalid arithmetic on pointer operands much 5895/// like \see checkArithmeticOpPointerOperand. However, it has special logic 5896/// for emitting a single diagnostic even for operations where both LHS and RHS 5897/// are (potentially problematic) pointers. 5898/// 5899/// \returns True when the operand is valid to use (even if as an extension). 5900static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 5901 Expr *LHSExpr, Expr *RHSExpr) { 5902 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 5903 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 5904 if (!isLHSPointer && !isRHSPointer) return true; 5905 5906 QualType LHSPointeeTy, RHSPointeeTy; 5907 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 5908 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 5909 5910 // Check for arithmetic on pointers to incomplete types. 5911 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 5912 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 5913 if (isLHSVoidPtr || isRHSVoidPtr) { 5914 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 5915 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 5916 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 5917 5918 return !S.getLangOptions().CPlusPlus; 5919 } 5920 5921 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 5922 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 5923 if (isLHSFuncPtr || isRHSFuncPtr) { 5924 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 5925 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 5926 RHSExpr); 5927 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 5928 5929 return !S.getLangOptions().CPlusPlus; 5930 } 5931 5932 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false; 5933 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false; 5934 5935 return true; 5936} 5937 5938/// \brief Check bad cases where we step over interface counts. 5939static bool checkArithmethicPointerOnNonFragileABI(Sema &S, 5940 SourceLocation OpLoc, 5941 Expr *Op) { 5942 assert(Op->getType()->isAnyPointerType()); 5943 QualType PointeeTy = Op->getType()->getPointeeType(); 5944 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI) 5945 return true; 5946 5947 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 5948 << PointeeTy << Op->getSourceRange(); 5949 return false; 5950} 5951 5952/// \brief Emit error when two pointers are incompatible. 5953static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 5954 Expr *LHSExpr, Expr *RHSExpr) { 5955 assert(LHSExpr->getType()->isAnyPointerType()); 5956 assert(RHSExpr->getType()->isAnyPointerType()); 5957 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 5958 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 5959 << RHSExpr->getSourceRange(); 5960} 5961 5962QualType Sema::CheckAdditionOperands( // C99 6.5.6 5963 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) { 5964 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 5965 5966 if (LHS.get()->getType()->isVectorType() || 5967 RHS.get()->getType()->isVectorType()) { 5968 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 5969 if (CompLHSTy) *CompLHSTy = compType; 5970 return compType; 5971 } 5972 5973 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 5974 if (LHS.isInvalid() || RHS.isInvalid()) 5975 return QualType(); 5976 5977 // handle the common case first (both operands are arithmetic). 5978 if (LHS.get()->getType()->isArithmeticType() && 5979 RHS.get()->getType()->isArithmeticType()) { 5980 if (CompLHSTy) *CompLHSTy = compType; 5981 return compType; 5982 } 5983 5984 if (LHS.get()->getType()->isAtomicType() && 5985 RHS.get()->getType()->isArithmeticType()) { 5986 *CompLHSTy = LHS.get()->getType(); 5987 return compType; 5988 } 5989 5990 // Put any potential pointer into PExp 5991 Expr* PExp = LHS.get(), *IExp = RHS.get(); 5992 if (IExp->getType()->isAnyPointerType()) 5993 std::swap(PExp, IExp); 5994 5995 if (!PExp->getType()->isAnyPointerType()) 5996 return InvalidOperands(Loc, LHS, RHS); 5997 5998 if (!IExp->getType()->isIntegerType()) 5999 return InvalidOperands(Loc, LHS, RHS); 6000 6001 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6002 return QualType(); 6003 6004 // Diagnose bad cases where we step over interface counts. 6005 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp)) 6006 return QualType(); 6007 6008 // Check array bounds for pointer arithemtic 6009 CheckArrayAccess(PExp, IExp); 6010 6011 if (CompLHSTy) { 6012 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6013 if (LHSTy.isNull()) { 6014 LHSTy = LHS.get()->getType(); 6015 if (LHSTy->isPromotableIntegerType()) 6016 LHSTy = Context.getPromotedIntegerType(LHSTy); 6017 } 6018 *CompLHSTy = LHSTy; 6019 } 6020 6021 return PExp->getType(); 6022} 6023 6024// C99 6.5.6 6025QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6026 SourceLocation Loc, 6027 QualType* CompLHSTy) { 6028 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6029 6030 if (LHS.get()->getType()->isVectorType() || 6031 RHS.get()->getType()->isVectorType()) { 6032 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6033 if (CompLHSTy) *CompLHSTy = compType; 6034 return compType; 6035 } 6036 6037 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6038 if (LHS.isInvalid() || RHS.isInvalid()) 6039 return QualType(); 6040 6041 // Enforce type constraints: C99 6.5.6p3. 6042 6043 // Handle the common case first (both operands are arithmetic). 6044 if (LHS.get()->getType()->isArithmeticType() && 6045 RHS.get()->getType()->isArithmeticType()) { 6046 if (CompLHSTy) *CompLHSTy = compType; 6047 return compType; 6048 } 6049 6050 if (LHS.get()->getType()->isAtomicType() && 6051 RHS.get()->getType()->isArithmeticType()) { 6052 *CompLHSTy = LHS.get()->getType(); 6053 return compType; 6054 } 6055 6056 // Either ptr - int or ptr - ptr. 6057 if (LHS.get()->getType()->isAnyPointerType()) { 6058 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6059 6060 // Diagnose bad cases where we step over interface counts. 6061 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get())) 6062 return QualType(); 6063 6064 // The result type of a pointer-int computation is the pointer type. 6065 if (RHS.get()->getType()->isIntegerType()) { 6066 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6067 return QualType(); 6068 6069 // Check array bounds for pointer arithemtic 6070 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6071 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6072 6073 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6074 return LHS.get()->getType(); 6075 } 6076 6077 // Handle pointer-pointer subtractions. 6078 if (const PointerType *RHSPTy 6079 = RHS.get()->getType()->getAs<PointerType>()) { 6080 QualType rpointee = RHSPTy->getPointeeType(); 6081 6082 if (getLangOptions().CPlusPlus) { 6083 // Pointee types must be the same: C++ [expr.add] 6084 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6085 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6086 } 6087 } else { 6088 // Pointee types must be compatible C99 6.5.6p3 6089 if (!Context.typesAreCompatible( 6090 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6091 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6092 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6093 return QualType(); 6094 } 6095 } 6096 6097 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6098 LHS.get(), RHS.get())) 6099 return QualType(); 6100 6101 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6102 return Context.getPointerDiffType(); 6103 } 6104 } 6105 6106 return InvalidOperands(Loc, LHS, RHS); 6107} 6108 6109static bool isScopedEnumerationType(QualType T) { 6110 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6111 return ET->getDecl()->isScoped(); 6112 return false; 6113} 6114 6115static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6116 SourceLocation Loc, unsigned Opc, 6117 QualType LHSType) { 6118 llvm::APSInt Right; 6119 // Check right/shifter operand 6120 if (RHS.get()->isValueDependent() || 6121 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6122 return; 6123 6124 if (Right.isNegative()) { 6125 S.DiagRuntimeBehavior(Loc, RHS.get(), 6126 S.PDiag(diag::warn_shift_negative) 6127 << RHS.get()->getSourceRange()); 6128 return; 6129 } 6130 llvm::APInt LeftBits(Right.getBitWidth(), 6131 S.Context.getTypeSize(LHS.get()->getType())); 6132 if (Right.uge(LeftBits)) { 6133 S.DiagRuntimeBehavior(Loc, RHS.get(), 6134 S.PDiag(diag::warn_shift_gt_typewidth) 6135 << RHS.get()->getSourceRange()); 6136 return; 6137 } 6138 if (Opc != BO_Shl) 6139 return; 6140 6141 // When left shifting an ICE which is signed, we can check for overflow which 6142 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6143 // integers have defined behavior modulo one more than the maximum value 6144 // representable in the result type, so never warn for those. 6145 llvm::APSInt Left; 6146 if (LHS.get()->isValueDependent() || 6147 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6148 LHSType->hasUnsignedIntegerRepresentation()) 6149 return; 6150 llvm::APInt ResultBits = 6151 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6152 if (LeftBits.uge(ResultBits)) 6153 return; 6154 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6155 Result = Result.shl(Right); 6156 6157 // Print the bit representation of the signed integer as an unsigned 6158 // hexadecimal number. 6159 SmallString<40> HexResult; 6160 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6161 6162 // If we are only missing a sign bit, this is less likely to result in actual 6163 // bugs -- if the result is cast back to an unsigned type, it will have the 6164 // expected value. Thus we place this behind a different warning that can be 6165 // turned off separately if needed. 6166 if (LeftBits == ResultBits - 1) { 6167 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6168 << HexResult.str() << LHSType 6169 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6170 return; 6171 } 6172 6173 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6174 << HexResult.str() << Result.getMinSignedBits() << LHSType 6175 << Left.getBitWidth() << LHS.get()->getSourceRange() 6176 << RHS.get()->getSourceRange(); 6177} 6178 6179// C99 6.5.7 6180QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6181 SourceLocation Loc, unsigned Opc, 6182 bool IsCompAssign) { 6183 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6184 6185 // C99 6.5.7p2: Each of the operands shall have integer type. 6186 if (!LHS.get()->getType()->hasIntegerRepresentation() || 6187 !RHS.get()->getType()->hasIntegerRepresentation()) 6188 return InvalidOperands(Loc, LHS, RHS); 6189 6190 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6191 // hasIntegerRepresentation() above instead of this. 6192 if (isScopedEnumerationType(LHS.get()->getType()) || 6193 isScopedEnumerationType(RHS.get()->getType())) { 6194 return InvalidOperands(Loc, LHS, RHS); 6195 } 6196 6197 // Vector shifts promote their scalar inputs to vector type. 6198 if (LHS.get()->getType()->isVectorType() || 6199 RHS.get()->getType()->isVectorType()) 6200 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6201 6202 // Shifts don't perform usual arithmetic conversions, they just do integer 6203 // promotions on each operand. C99 6.5.7p3 6204 6205 // For the LHS, do usual unary conversions, but then reset them away 6206 // if this is a compound assignment. 6207 ExprResult OldLHS = LHS; 6208 LHS = UsualUnaryConversions(LHS.take()); 6209 if (LHS.isInvalid()) 6210 return QualType(); 6211 QualType LHSType = LHS.get()->getType(); 6212 if (IsCompAssign) LHS = OldLHS; 6213 6214 // The RHS is simpler. 6215 RHS = UsualUnaryConversions(RHS.take()); 6216 if (RHS.isInvalid()) 6217 return QualType(); 6218 6219 // Sanity-check shift operands 6220 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6221 6222 // "The type of the result is that of the promoted left operand." 6223 return LHSType; 6224} 6225 6226static bool IsWithinTemplateSpecialization(Decl *D) { 6227 if (DeclContext *DC = D->getDeclContext()) { 6228 if (isa<ClassTemplateSpecializationDecl>(DC)) 6229 return true; 6230 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6231 return FD->isFunctionTemplateSpecialization(); 6232 } 6233 return false; 6234} 6235 6236/// If two different enums are compared, raise a warning. 6237static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, 6238 ExprResult &RHS) { 6239 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType(); 6240 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType(); 6241 6242 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6243 if (!LHSEnumType) 6244 return; 6245 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6246 if (!RHSEnumType) 6247 return; 6248 6249 // Ignore anonymous enums. 6250 if (!LHSEnumType->getDecl()->getIdentifier()) 6251 return; 6252 if (!RHSEnumType->getDecl()->getIdentifier()) 6253 return; 6254 6255 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 6256 return; 6257 6258 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6259 << LHSStrippedType << RHSStrippedType 6260 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6261} 6262 6263/// \brief Diagnose bad pointer comparisons. 6264static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 6265 ExprResult &LHS, ExprResult &RHS, 6266 bool IsError) { 6267 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 6268 : diag::ext_typecheck_comparison_of_distinct_pointers) 6269 << LHS.get()->getType() << RHS.get()->getType() 6270 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6271} 6272 6273/// \brief Returns false if the pointers are converted to a composite type, 6274/// true otherwise. 6275static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 6276 ExprResult &LHS, ExprResult &RHS) { 6277 // C++ [expr.rel]p2: 6278 // [...] Pointer conversions (4.10) and qualification 6279 // conversions (4.4) are performed on pointer operands (or on 6280 // a pointer operand and a null pointer constant) to bring 6281 // them to their composite pointer type. [...] 6282 // 6283 // C++ [expr.eq]p1 uses the same notion for (in)equality 6284 // comparisons of pointers. 6285 6286 // C++ [expr.eq]p2: 6287 // In addition, pointers to members can be compared, or a pointer to 6288 // member and a null pointer constant. Pointer to member conversions 6289 // (4.11) and qualification conversions (4.4) are performed to bring 6290 // them to a common type. If one operand is a null pointer constant, 6291 // the common type is the type of the other operand. Otherwise, the 6292 // common type is a pointer to member type similar (4.4) to the type 6293 // of one of the operands, with a cv-qualification signature (4.4) 6294 // that is the union of the cv-qualification signatures of the operand 6295 // types. 6296 6297 QualType LHSType = LHS.get()->getType(); 6298 QualType RHSType = RHS.get()->getType(); 6299 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 6300 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 6301 6302 bool NonStandardCompositeType = false; 6303 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 6304 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 6305 if (T.isNull()) { 6306 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 6307 return true; 6308 } 6309 6310 if (NonStandardCompositeType) 6311 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 6312 << LHSType << RHSType << T << LHS.get()->getSourceRange() 6313 << RHS.get()->getSourceRange(); 6314 6315 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 6316 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 6317 return false; 6318} 6319 6320static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 6321 ExprResult &LHS, 6322 ExprResult &RHS, 6323 bool IsError) { 6324 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 6325 : diag::ext_typecheck_comparison_of_fptr_to_void) 6326 << LHS.get()->getType() << RHS.get()->getType() 6327 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6328} 6329 6330// C99 6.5.8, C++ [expr.rel] 6331QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 6332 SourceLocation Loc, unsigned OpaqueOpc, 6333 bool IsRelational) { 6334 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 6335 6336 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 6337 6338 // Handle vector comparisons separately. 6339 if (LHS.get()->getType()->isVectorType() || 6340 RHS.get()->getType()->isVectorType()) 6341 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 6342 6343 QualType LHSType = LHS.get()->getType(); 6344 QualType RHSType = RHS.get()->getType(); 6345 6346 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 6347 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 6348 6349 checkEnumComparison(*this, Loc, LHS, RHS); 6350 6351 if (!LHSType->hasFloatingRepresentation() && 6352 !(LHSType->isBlockPointerType() && IsRelational) && 6353 !LHS.get()->getLocStart().isMacroID() && 6354 !RHS.get()->getLocStart().isMacroID()) { 6355 // For non-floating point types, check for self-comparisons of the form 6356 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6357 // often indicate logic errors in the program. 6358 // 6359 // NOTE: Don't warn about comparison expressions resulting from macro 6360 // expansion. Also don't warn about comparisons which are only self 6361 // comparisons within a template specialization. The warnings should catch 6362 // obvious cases in the definition of the template anyways. The idea is to 6363 // warn when the typed comparison operator will always evaluate to the same 6364 // result. 6365 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 6366 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 6367 if (DRL->getDecl() == DRR->getDecl() && 6368 !IsWithinTemplateSpecialization(DRL->getDecl())) { 6369 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6370 << 0 // self- 6371 << (Opc == BO_EQ 6372 || Opc == BO_LE 6373 || Opc == BO_GE)); 6374 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 6375 !DRL->getDecl()->getType()->isReferenceType() && 6376 !DRR->getDecl()->getType()->isReferenceType()) { 6377 // what is it always going to eval to? 6378 char always_evals_to; 6379 switch(Opc) { 6380 case BO_EQ: // e.g. array1 == array2 6381 always_evals_to = 0; // false 6382 break; 6383 case BO_NE: // e.g. array1 != array2 6384 always_evals_to = 1; // true 6385 break; 6386 default: 6387 // best we can say is 'a constant' 6388 always_evals_to = 2; // e.g. array1 <= array2 6389 break; 6390 } 6391 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6392 << 1 // array 6393 << always_evals_to); 6394 } 6395 } 6396 } 6397 6398 if (isa<CastExpr>(LHSStripped)) 6399 LHSStripped = LHSStripped->IgnoreParenCasts(); 6400 if (isa<CastExpr>(RHSStripped)) 6401 RHSStripped = RHSStripped->IgnoreParenCasts(); 6402 6403 // Warn about comparisons against a string constant (unless the other 6404 // operand is null), the user probably wants strcmp. 6405 Expr *literalString = 0; 6406 Expr *literalStringStripped = 0; 6407 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 6408 !RHSStripped->isNullPointerConstant(Context, 6409 Expr::NPC_ValueDependentIsNull)) { 6410 literalString = LHS.get(); 6411 literalStringStripped = LHSStripped; 6412 } else if ((isa<StringLiteral>(RHSStripped) || 6413 isa<ObjCEncodeExpr>(RHSStripped)) && 6414 !LHSStripped->isNullPointerConstant(Context, 6415 Expr::NPC_ValueDependentIsNull)) { 6416 literalString = RHS.get(); 6417 literalStringStripped = RHSStripped; 6418 } 6419 6420 if (literalString) { 6421 std::string resultComparison; 6422 switch (Opc) { 6423 case BO_LT: resultComparison = ") < 0"; break; 6424 case BO_GT: resultComparison = ") > 0"; break; 6425 case BO_LE: resultComparison = ") <= 0"; break; 6426 case BO_GE: resultComparison = ") >= 0"; break; 6427 case BO_EQ: resultComparison = ") == 0"; break; 6428 case BO_NE: resultComparison = ") != 0"; break; 6429 default: llvm_unreachable("Invalid comparison operator"); 6430 } 6431 6432 DiagRuntimeBehavior(Loc, 0, 6433 PDiag(diag::warn_stringcompare) 6434 << isa<ObjCEncodeExpr>(literalStringStripped) 6435 << literalString->getSourceRange()); 6436 } 6437 } 6438 6439 // C99 6.5.8p3 / C99 6.5.9p4 6440 if (LHS.get()->getType()->isArithmeticType() && 6441 RHS.get()->getType()->isArithmeticType()) { 6442 UsualArithmeticConversions(LHS, RHS); 6443 if (LHS.isInvalid() || RHS.isInvalid()) 6444 return QualType(); 6445 } 6446 else { 6447 LHS = UsualUnaryConversions(LHS.take()); 6448 if (LHS.isInvalid()) 6449 return QualType(); 6450 6451 RHS = UsualUnaryConversions(RHS.take()); 6452 if (RHS.isInvalid()) 6453 return QualType(); 6454 } 6455 6456 LHSType = LHS.get()->getType(); 6457 RHSType = RHS.get()->getType(); 6458 6459 // The result of comparisons is 'bool' in C++, 'int' in C. 6460 QualType ResultTy = Context.getLogicalOperationType(); 6461 6462 if (IsRelational) { 6463 if (LHSType->isRealType() && RHSType->isRealType()) 6464 return ResultTy; 6465 } else { 6466 // Check for comparisons of floating point operands using != and ==. 6467 if (LHSType->hasFloatingRepresentation()) 6468 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 6469 6470 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 6471 return ResultTy; 6472 } 6473 6474 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 6475 Expr::NPC_ValueDependentIsNull); 6476 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 6477 Expr::NPC_ValueDependentIsNull); 6478 6479 // All of the following pointer-related warnings are GCC extensions, except 6480 // when handling null pointer constants. 6481 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 6482 QualType LCanPointeeTy = 6483 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 6484 QualType RCanPointeeTy = 6485 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 6486 6487 if (getLangOptions().CPlusPlus) { 6488 if (LCanPointeeTy == RCanPointeeTy) 6489 return ResultTy; 6490 if (!IsRelational && 6491 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6492 // Valid unless comparison between non-null pointer and function pointer 6493 // This is a gcc extension compatibility comparison. 6494 // In a SFINAE context, we treat this as a hard error to maintain 6495 // conformance with the C++ standard. 6496 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6497 && !LHSIsNull && !RHSIsNull) { 6498 diagnoseFunctionPointerToVoidComparison( 6499 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext()); 6500 6501 if (isSFINAEContext()) 6502 return QualType(); 6503 6504 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6505 return ResultTy; 6506 } 6507 } 6508 6509 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 6510 return QualType(); 6511 else 6512 return ResultTy; 6513 } 6514 // C99 6.5.9p2 and C99 6.5.8p2 6515 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 6516 RCanPointeeTy.getUnqualifiedType())) { 6517 // Valid unless a relational comparison of function pointers 6518 if (IsRelational && LCanPointeeTy->isFunctionType()) { 6519 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 6520 << LHSType << RHSType << LHS.get()->getSourceRange() 6521 << RHS.get()->getSourceRange(); 6522 } 6523 } else if (!IsRelational && 6524 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6525 // Valid unless comparison between non-null pointer and function pointer 6526 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6527 && !LHSIsNull && !RHSIsNull) 6528 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 6529 /*isError*/false); 6530 } else { 6531 // Invalid 6532 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 6533 } 6534 if (LCanPointeeTy != RCanPointeeTy) { 6535 if (LHSIsNull && !RHSIsNull) 6536 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6537 else 6538 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6539 } 6540 return ResultTy; 6541 } 6542 6543 if (getLangOptions().CPlusPlus) { 6544 // Comparison of nullptr_t with itself. 6545 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 6546 return ResultTy; 6547 6548 // Comparison of pointers with null pointer constants and equality 6549 // comparisons of member pointers to null pointer constants. 6550 if (RHSIsNull && 6551 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 6552 (!IsRelational && 6553 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 6554 RHS = ImpCastExprToType(RHS.take(), LHSType, 6555 LHSType->isMemberPointerType() 6556 ? CK_NullToMemberPointer 6557 : CK_NullToPointer); 6558 return ResultTy; 6559 } 6560 if (LHSIsNull && 6561 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 6562 (!IsRelational && 6563 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 6564 LHS = ImpCastExprToType(LHS.take(), RHSType, 6565 RHSType->isMemberPointerType() 6566 ? CK_NullToMemberPointer 6567 : CK_NullToPointer); 6568 return ResultTy; 6569 } 6570 6571 // Comparison of member pointers. 6572 if (!IsRelational && 6573 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 6574 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 6575 return QualType(); 6576 else 6577 return ResultTy; 6578 } 6579 6580 // Handle scoped enumeration types specifically, since they don't promote 6581 // to integers. 6582 if (LHS.get()->getType()->isEnumeralType() && 6583 Context.hasSameUnqualifiedType(LHS.get()->getType(), 6584 RHS.get()->getType())) 6585 return ResultTy; 6586 } 6587 6588 // Handle block pointer types. 6589 if (!IsRelational && LHSType->isBlockPointerType() && 6590 RHSType->isBlockPointerType()) { 6591 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 6592 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 6593 6594 if (!LHSIsNull && !RHSIsNull && 6595 !Context.typesAreCompatible(lpointee, rpointee)) { 6596 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 6597 << LHSType << RHSType << LHS.get()->getSourceRange() 6598 << RHS.get()->getSourceRange(); 6599 } 6600 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6601 return ResultTy; 6602 } 6603 6604 // Allow block pointers to be compared with null pointer constants. 6605 if (!IsRelational 6606 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 6607 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 6608 if (!LHSIsNull && !RHSIsNull) { 6609 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 6610 ->getPointeeType()->isVoidType()) 6611 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 6612 ->getPointeeType()->isVoidType()))) 6613 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 6614 << LHSType << RHSType << LHS.get()->getSourceRange() 6615 << RHS.get()->getSourceRange(); 6616 } 6617 if (LHSIsNull && !RHSIsNull) 6618 LHS = ImpCastExprToType(LHS.take(), RHSType, 6619 RHSType->isPointerType() ? CK_BitCast 6620 : CK_AnyPointerToBlockPointerCast); 6621 else 6622 RHS = ImpCastExprToType(RHS.take(), LHSType, 6623 LHSType->isPointerType() ? CK_BitCast 6624 : CK_AnyPointerToBlockPointerCast); 6625 return ResultTy; 6626 } 6627 6628 if (LHSType->isObjCObjectPointerType() || 6629 RHSType->isObjCObjectPointerType()) { 6630 const PointerType *LPT = LHSType->getAs<PointerType>(); 6631 const PointerType *RPT = RHSType->getAs<PointerType>(); 6632 if (LPT || RPT) { 6633 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 6634 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 6635 6636 if (!LPtrToVoid && !RPtrToVoid && 6637 !Context.typesAreCompatible(LHSType, RHSType)) { 6638 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 6639 /*isError*/false); 6640 } 6641 if (LHSIsNull && !RHSIsNull) 6642 LHS = ImpCastExprToType(LHS.take(), RHSType, 6643 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 6644 else 6645 RHS = ImpCastExprToType(RHS.take(), LHSType, 6646 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 6647 return ResultTy; 6648 } 6649 if (LHSType->isObjCObjectPointerType() && 6650 RHSType->isObjCObjectPointerType()) { 6651 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 6652 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 6653 /*isError*/false); 6654 if (LHSIsNull && !RHSIsNull) 6655 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6656 else 6657 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6658 return ResultTy; 6659 } 6660 } 6661 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 6662 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 6663 unsigned DiagID = 0; 6664 bool isError = false; 6665 if ((LHSIsNull && LHSType->isIntegerType()) || 6666 (RHSIsNull && RHSType->isIntegerType())) { 6667 if (IsRelational && !getLangOptions().CPlusPlus) 6668 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 6669 } else if (IsRelational && !getLangOptions().CPlusPlus) 6670 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 6671 else if (getLangOptions().CPlusPlus) { 6672 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 6673 isError = true; 6674 } else 6675 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 6676 6677 if (DiagID) { 6678 Diag(Loc, DiagID) 6679 << LHSType << RHSType << LHS.get()->getSourceRange() 6680 << RHS.get()->getSourceRange(); 6681 if (isError) 6682 return QualType(); 6683 } 6684 6685 if (LHSType->isIntegerType()) 6686 LHS = ImpCastExprToType(LHS.take(), RHSType, 6687 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 6688 else 6689 RHS = ImpCastExprToType(RHS.take(), LHSType, 6690 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 6691 return ResultTy; 6692 } 6693 6694 // Handle block pointers. 6695 if (!IsRelational && RHSIsNull 6696 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 6697 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6698 return ResultTy; 6699 } 6700 if (!IsRelational && LHSIsNull 6701 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 6702 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 6703 return ResultTy; 6704 } 6705 6706 return InvalidOperands(Loc, LHS, RHS); 6707} 6708 6709 6710// Return a signed type that is of identical size and number of elements. 6711// For floating point vectors, return an integer type of identical size 6712// and number of elements. 6713QualType Sema::GetSignedVectorType(QualType V) { 6714 const VectorType *VTy = V->getAs<VectorType>(); 6715 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 6716 if (TypeSize == Context.getTypeSize(Context.CharTy)) 6717 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 6718 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 6719 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 6720 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 6721 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 6722 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 6723 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 6724 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 6725 "Unhandled vector element size in vector compare"); 6726 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 6727} 6728 6729/// CheckVectorCompareOperands - vector comparisons are a clang extension that 6730/// operates on extended vector types. Instead of producing an IntTy result, 6731/// like a scalar comparison, a vector comparison produces a vector of integer 6732/// types. 6733QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 6734 SourceLocation Loc, 6735 bool IsRelational) { 6736 // Check to make sure we're operating on vectors of the same type and width, 6737 // Allowing one side to be a scalar of element type. 6738 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 6739 if (vType.isNull()) 6740 return vType; 6741 6742 QualType LHSType = LHS.get()->getType(); 6743 6744 // If AltiVec, the comparison results in a numeric type, i.e. 6745 // bool for C++, int for C 6746 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 6747 return Context.getLogicalOperationType(); 6748 6749 // For non-floating point types, check for self-comparisons of the form 6750 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6751 // often indicate logic errors in the program. 6752 if (!LHSType->hasFloatingRepresentation()) { 6753 if (DeclRefExpr* DRL 6754 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 6755 if (DeclRefExpr* DRR 6756 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 6757 if (DRL->getDecl() == DRR->getDecl()) 6758 DiagRuntimeBehavior(Loc, 0, 6759 PDiag(diag::warn_comparison_always) 6760 << 0 // self- 6761 << 2 // "a constant" 6762 ); 6763 } 6764 6765 // Check for comparisons of floating point operands using != and ==. 6766 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 6767 assert (RHS.get()->getType()->hasFloatingRepresentation()); 6768 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 6769 } 6770 6771 // Return a signed type for the vector. 6772 return GetSignedVectorType(LHSType); 6773} 6774 6775QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 6776 SourceLocation Loc) { 6777 // Ensure that either both operands are of the same vector type, or 6778 // one operand is of a vector type and the other is of its element type. 6779 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 6780 if (vType.isNull() || vType->isFloatingType()) 6781 return InvalidOperands(Loc, LHS, RHS); 6782 6783 return GetSignedVectorType(LHS.get()->getType()); 6784} 6785 6786inline QualType Sema::CheckBitwiseOperands( 6787 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6788 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6789 6790 if (LHS.get()->getType()->isVectorType() || 6791 RHS.get()->getType()->isVectorType()) { 6792 if (LHS.get()->getType()->hasIntegerRepresentation() && 6793 RHS.get()->getType()->hasIntegerRepresentation()) 6794 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6795 6796 return InvalidOperands(Loc, LHS, RHS); 6797 } 6798 6799 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 6800 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 6801 IsCompAssign); 6802 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 6803 return QualType(); 6804 LHS = LHSResult.take(); 6805 RHS = RHSResult.take(); 6806 6807 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() && 6808 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType()) 6809 return compType; 6810 return InvalidOperands(Loc, LHS, RHS); 6811} 6812 6813inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 6814 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 6815 6816 // Check vector operands differently. 6817 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 6818 return CheckVectorLogicalOperands(LHS, RHS, Loc); 6819 6820 // Diagnose cases where the user write a logical and/or but probably meant a 6821 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 6822 // is a constant. 6823 if (LHS.get()->getType()->isIntegerType() && 6824 !LHS.get()->getType()->isBooleanType() && 6825 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 6826 // Don't warn in macros or template instantiations. 6827 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 6828 // If the RHS can be constant folded, and if it constant folds to something 6829 // that isn't 0 or 1 (which indicate a potential logical operation that 6830 // happened to fold to true/false) then warn. 6831 // Parens on the RHS are ignored. 6832 llvm::APSInt Result; 6833 if (RHS.get()->EvaluateAsInt(Result, Context)) 6834 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) || 6835 (Result != 0 && Result != 1)) { 6836 Diag(Loc, diag::warn_logical_instead_of_bitwise) 6837 << RHS.get()->getSourceRange() 6838 << (Opc == BO_LAnd ? "&&" : "||"); 6839 // Suggest replacing the logical operator with the bitwise version 6840 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 6841 << (Opc == BO_LAnd ? "&" : "|") 6842 << FixItHint::CreateReplacement(SourceRange( 6843 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 6844 getLangOptions())), 6845 Opc == BO_LAnd ? "&" : "|"); 6846 if (Opc == BO_LAnd) 6847 // Suggest replacing "Foo() && kNonZero" with "Foo()" 6848 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 6849 << FixItHint::CreateRemoval( 6850 SourceRange( 6851 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 6852 0, getSourceManager(), 6853 getLangOptions()), 6854 RHS.get()->getLocEnd())); 6855 } 6856 } 6857 6858 if (!Context.getLangOptions().CPlusPlus) { 6859 LHS = UsualUnaryConversions(LHS.take()); 6860 if (LHS.isInvalid()) 6861 return QualType(); 6862 6863 RHS = UsualUnaryConversions(RHS.take()); 6864 if (RHS.isInvalid()) 6865 return QualType(); 6866 6867 if (!LHS.get()->getType()->isScalarType() || 6868 !RHS.get()->getType()->isScalarType()) 6869 return InvalidOperands(Loc, LHS, RHS); 6870 6871 return Context.IntTy; 6872 } 6873 6874 // The following is safe because we only use this method for 6875 // non-overloadable operands. 6876 6877 // C++ [expr.log.and]p1 6878 // C++ [expr.log.or]p1 6879 // The operands are both contextually converted to type bool. 6880 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 6881 if (LHSRes.isInvalid()) 6882 return InvalidOperands(Loc, LHS, RHS); 6883 LHS = move(LHSRes); 6884 6885 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 6886 if (RHSRes.isInvalid()) 6887 return InvalidOperands(Loc, LHS, RHS); 6888 RHS = move(RHSRes); 6889 6890 // C++ [expr.log.and]p2 6891 // C++ [expr.log.or]p2 6892 // The result is a bool. 6893 return Context.BoolTy; 6894} 6895 6896/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 6897/// is a read-only property; return true if so. A readonly property expression 6898/// depends on various declarations and thus must be treated specially. 6899/// 6900static bool IsReadonlyProperty(Expr *E, Sema &S) { 6901 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 6902 if (!PropExpr) return false; 6903 if (PropExpr->isImplicitProperty()) return false; 6904 6905 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 6906 QualType BaseType = PropExpr->isSuperReceiver() ? 6907 PropExpr->getSuperReceiverType() : 6908 PropExpr->getBase()->getType(); 6909 6910 if (const ObjCObjectPointerType *OPT = 6911 BaseType->getAsObjCInterfacePointerType()) 6912 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 6913 if (S.isPropertyReadonly(PDecl, IFace)) 6914 return true; 6915 return false; 6916} 6917 6918static bool IsConstProperty(Expr *E, Sema &S) { 6919 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 6920 if (!PropExpr) return false; 6921 if (PropExpr->isImplicitProperty()) return false; 6922 6923 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 6924 QualType T = PDecl->getType().getNonReferenceType(); 6925 return T.isConstQualified(); 6926} 6927 6928static bool IsReadonlyMessage(Expr *E, Sema &S) { 6929 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 6930 if (!ME) return false; 6931 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 6932 ObjCMessageExpr *Base = 6933 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 6934 if (!Base) return false; 6935 return Base->getMethodDecl() != 0; 6936} 6937 6938/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 6939/// emit an error and return true. If so, return false. 6940static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 6941 SourceLocation OrigLoc = Loc; 6942 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 6943 &Loc); 6944 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 6945 IsLV = Expr::MLV_ReadonlyProperty; 6946 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S)) 6947 IsLV = Expr::MLV_Valid; 6948 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 6949 IsLV = Expr::MLV_InvalidMessageExpression; 6950 if (IsLV == Expr::MLV_Valid) 6951 return false; 6952 6953 unsigned Diag = 0; 6954 bool NeedType = false; 6955 switch (IsLV) { // C99 6.5.16p2 6956 case Expr::MLV_ConstQualified: 6957 Diag = diag::err_typecheck_assign_const; 6958 6959 // In ARC, use some specialized diagnostics for occasions where we 6960 // infer 'const'. These are always pseudo-strong variables. 6961 if (S.getLangOptions().ObjCAutoRefCount) { 6962 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 6963 if (declRef && isa<VarDecl>(declRef->getDecl())) { 6964 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 6965 6966 // Use the normal diagnostic if it's pseudo-__strong but the 6967 // user actually wrote 'const'. 6968 if (var->isARCPseudoStrong() && 6969 (!var->getTypeSourceInfo() || 6970 !var->getTypeSourceInfo()->getType().isConstQualified())) { 6971 // There are two pseudo-strong cases: 6972 // - self 6973 ObjCMethodDecl *method = S.getCurMethodDecl(); 6974 if (method && var == method->getSelfDecl()) 6975 Diag = method->isClassMethod() 6976 ? diag::err_typecheck_arc_assign_self_class_method 6977 : diag::err_typecheck_arc_assign_self; 6978 6979 // - fast enumeration variables 6980 else 6981 Diag = diag::err_typecheck_arr_assign_enumeration; 6982 6983 SourceRange Assign; 6984 if (Loc != OrigLoc) 6985 Assign = SourceRange(OrigLoc, OrigLoc); 6986 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 6987 // We need to preserve the AST regardless, so migration tool 6988 // can do its job. 6989 return false; 6990 } 6991 } 6992 } 6993 6994 break; 6995 case Expr::MLV_ArrayType: 6996 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 6997 NeedType = true; 6998 break; 6999 case Expr::MLV_NotObjectType: 7000 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7001 NeedType = true; 7002 break; 7003 case Expr::MLV_LValueCast: 7004 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7005 break; 7006 case Expr::MLV_Valid: 7007 llvm_unreachable("did not take early return for MLV_Valid"); 7008 case Expr::MLV_InvalidExpression: 7009 case Expr::MLV_MemberFunction: 7010 case Expr::MLV_ClassTemporary: 7011 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7012 break; 7013 case Expr::MLV_IncompleteType: 7014 case Expr::MLV_IncompleteVoidType: 7015 return S.RequireCompleteType(Loc, E->getType(), 7016 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 7017 << E->getSourceRange()); 7018 case Expr::MLV_DuplicateVectorComponents: 7019 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7020 break; 7021 case Expr::MLV_NotBlockQualified: 7022 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7023 break; 7024 case Expr::MLV_ReadonlyProperty: 7025 case Expr::MLV_NoSetterProperty: 7026 llvm_unreachable("readonly properties should be processed differently"); 7027 case Expr::MLV_InvalidMessageExpression: 7028 Diag = diag::error_readonly_message_assignment; 7029 break; 7030 case Expr::MLV_SubObjCPropertySetting: 7031 Diag = diag::error_no_subobject_property_setting; 7032 break; 7033 } 7034 7035 SourceRange Assign; 7036 if (Loc != OrigLoc) 7037 Assign = SourceRange(OrigLoc, OrigLoc); 7038 if (NeedType) 7039 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7040 else 7041 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7042 return true; 7043} 7044 7045 7046 7047// C99 6.5.16.1 7048QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 7049 SourceLocation Loc, 7050 QualType CompoundType) { 7051 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 7052 7053 // Verify that LHS is a modifiable lvalue, and emit error if not. 7054 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 7055 return QualType(); 7056 7057 QualType LHSType = LHSExpr->getType(); 7058 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 7059 CompoundType; 7060 AssignConvertType ConvTy; 7061 if (CompoundType.isNull()) { 7062 QualType LHSTy(LHSType); 7063 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7064 if (RHS.isInvalid()) 7065 return QualType(); 7066 // Special case of NSObject attributes on c-style pointer types. 7067 if (ConvTy == IncompatiblePointer && 7068 ((Context.isObjCNSObjectType(LHSType) && 7069 RHSType->isObjCObjectPointerType()) || 7070 (Context.isObjCNSObjectType(RHSType) && 7071 LHSType->isObjCObjectPointerType()))) 7072 ConvTy = Compatible; 7073 7074 if (ConvTy == Compatible && 7075 LHSType->isObjCObjectType()) 7076 Diag(Loc, diag::err_objc_object_assignment) 7077 << LHSType; 7078 7079 // If the RHS is a unary plus or minus, check to see if they = and + are 7080 // right next to each other. If so, the user may have typo'd "x =+ 4" 7081 // instead of "x += 4". 7082 Expr *RHSCheck = RHS.get(); 7083 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7084 RHSCheck = ICE->getSubExpr(); 7085 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 7086 if ((UO->getOpcode() == UO_Plus || 7087 UO->getOpcode() == UO_Minus) && 7088 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 7089 // Only if the two operators are exactly adjacent. 7090 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 7091 // And there is a space or other character before the subexpr of the 7092 // unary +/-. We don't want to warn on "x=-1". 7093 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 7094 UO->getSubExpr()->getLocStart().isFileID()) { 7095 Diag(Loc, diag::warn_not_compound_assign) 7096 << (UO->getOpcode() == UO_Plus ? "+" : "-") 7097 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 7098 } 7099 } 7100 7101 if (ConvTy == Compatible) { 7102 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) 7103 checkRetainCycles(LHSExpr, RHS.get()); 7104 else if (getLangOptions().ObjCAutoRefCount) 7105 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 7106 } 7107 } else { 7108 // Compound assignment "x += y" 7109 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 7110 } 7111 7112 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 7113 RHS.get(), AA_Assigning)) 7114 return QualType(); 7115 7116 CheckForNullPointerDereference(*this, LHSExpr); 7117 7118 // C99 6.5.16p3: The type of an assignment expression is the type of the 7119 // left operand unless the left operand has qualified type, in which case 7120 // it is the unqualified version of the type of the left operand. 7121 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 7122 // is converted to the type of the assignment expression (above). 7123 // C++ 5.17p1: the type of the assignment expression is that of its left 7124 // operand. 7125 return (getLangOptions().CPlusPlus 7126 ? LHSType : LHSType.getUnqualifiedType()); 7127} 7128 7129// C99 6.5.17 7130static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 7131 SourceLocation Loc) { 7132 S.DiagnoseUnusedExprResult(LHS.get()); 7133 7134 LHS = S.CheckPlaceholderExpr(LHS.take()); 7135 RHS = S.CheckPlaceholderExpr(RHS.take()); 7136 if (LHS.isInvalid() || RHS.isInvalid()) 7137 return QualType(); 7138 7139 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 7140 // operands, but not unary promotions. 7141 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 7142 7143 // So we treat the LHS as a ignored value, and in C++ we allow the 7144 // containing site to determine what should be done with the RHS. 7145 LHS = S.IgnoredValueConversions(LHS.take()); 7146 if (LHS.isInvalid()) 7147 return QualType(); 7148 7149 if (!S.getLangOptions().CPlusPlus) { 7150 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 7151 if (RHS.isInvalid()) 7152 return QualType(); 7153 if (!RHS.get()->getType()->isVoidType()) 7154 S.RequireCompleteType(Loc, RHS.get()->getType(), 7155 diag::err_incomplete_type); 7156 } 7157 7158 return RHS.get()->getType(); 7159} 7160 7161/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 7162/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 7163static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 7164 ExprValueKind &VK, 7165 SourceLocation OpLoc, 7166 bool IsInc, bool IsPrefix) { 7167 if (Op->isTypeDependent()) 7168 return S.Context.DependentTy; 7169 7170 QualType ResType = Op->getType(); 7171 // Atomic types can be used for increment / decrement where the non-atomic 7172 // versions can, so ignore the _Atomic() specifier for the purpose of 7173 // checking. 7174 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7175 ResType = ResAtomicType->getValueType(); 7176 7177 assert(!ResType.isNull() && "no type for increment/decrement expression"); 7178 7179 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) { 7180 // Decrement of bool is not allowed. 7181 if (!IsInc) { 7182 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 7183 return QualType(); 7184 } 7185 // Increment of bool sets it to true, but is deprecated. 7186 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 7187 } else if (ResType->isRealType()) { 7188 // OK! 7189 } else if (ResType->isAnyPointerType()) { 7190 // C99 6.5.2.4p2, 6.5.6p2 7191 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 7192 return QualType(); 7193 7194 // Diagnose bad cases where we step over interface counts. 7195 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op)) 7196 return QualType(); 7197 } else if (ResType->isAnyComplexType()) { 7198 // C99 does not support ++/-- on complex types, we allow as an extension. 7199 S.Diag(OpLoc, diag::ext_integer_increment_complex) 7200 << ResType << Op->getSourceRange(); 7201 } else if (ResType->isPlaceholderType()) { 7202 ExprResult PR = S.CheckPlaceholderExpr(Op); 7203 if (PR.isInvalid()) return QualType(); 7204 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 7205 IsInc, IsPrefix); 7206 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) { 7207 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 7208 } else { 7209 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 7210 << ResType << int(IsInc) << Op->getSourceRange(); 7211 return QualType(); 7212 } 7213 // At this point, we know we have a real, complex or pointer type. 7214 // Now make sure the operand is a modifiable lvalue. 7215 if (CheckForModifiableLvalue(Op, OpLoc, S)) 7216 return QualType(); 7217 // In C++, a prefix increment is the same type as the operand. Otherwise 7218 // (in C or with postfix), the increment is the unqualified type of the 7219 // operand. 7220 if (IsPrefix && S.getLangOptions().CPlusPlus) { 7221 VK = VK_LValue; 7222 return ResType; 7223 } else { 7224 VK = VK_RValue; 7225 return ResType.getUnqualifiedType(); 7226 } 7227} 7228 7229 7230/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 7231/// This routine allows us to typecheck complex/recursive expressions 7232/// where the declaration is needed for type checking. We only need to 7233/// handle cases when the expression references a function designator 7234/// or is an lvalue. Here are some examples: 7235/// - &(x) => x 7236/// - &*****f => f for f a function designator. 7237/// - &s.xx => s 7238/// - &s.zz[1].yy -> s, if zz is an array 7239/// - *(x + 1) -> x, if x is an array 7240/// - &"123"[2] -> 0 7241/// - & __real__ x -> x 7242static ValueDecl *getPrimaryDecl(Expr *E) { 7243 switch (E->getStmtClass()) { 7244 case Stmt::DeclRefExprClass: 7245 return cast<DeclRefExpr>(E)->getDecl(); 7246 case Stmt::MemberExprClass: 7247 // If this is an arrow operator, the address is an offset from 7248 // the base's value, so the object the base refers to is 7249 // irrelevant. 7250 if (cast<MemberExpr>(E)->isArrow()) 7251 return 0; 7252 // Otherwise, the expression refers to a part of the base 7253 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 7254 case Stmt::ArraySubscriptExprClass: { 7255 // FIXME: This code shouldn't be necessary! We should catch the implicit 7256 // promotion of register arrays earlier. 7257 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 7258 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 7259 if (ICE->getSubExpr()->getType()->isArrayType()) 7260 return getPrimaryDecl(ICE->getSubExpr()); 7261 } 7262 return 0; 7263 } 7264 case Stmt::UnaryOperatorClass: { 7265 UnaryOperator *UO = cast<UnaryOperator>(E); 7266 7267 switch(UO->getOpcode()) { 7268 case UO_Real: 7269 case UO_Imag: 7270 case UO_Extension: 7271 return getPrimaryDecl(UO->getSubExpr()); 7272 default: 7273 return 0; 7274 } 7275 } 7276 case Stmt::ParenExprClass: 7277 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 7278 case Stmt::ImplicitCastExprClass: 7279 // If the result of an implicit cast is an l-value, we care about 7280 // the sub-expression; otherwise, the result here doesn't matter. 7281 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 7282 default: 7283 return 0; 7284 } 7285} 7286 7287namespace { 7288 enum { 7289 AO_Bit_Field = 0, 7290 AO_Vector_Element = 1, 7291 AO_Property_Expansion = 2, 7292 AO_Register_Variable = 3, 7293 AO_No_Error = 4 7294 }; 7295} 7296/// \brief Diagnose invalid operand for address of operations. 7297/// 7298/// \param Type The type of operand which cannot have its address taken. 7299static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 7300 Expr *E, unsigned Type) { 7301 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 7302} 7303 7304/// CheckAddressOfOperand - The operand of & must be either a function 7305/// designator or an lvalue designating an object. If it is an lvalue, the 7306/// object cannot be declared with storage class register or be a bit field. 7307/// Note: The usual conversions are *not* applied to the operand of the & 7308/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 7309/// In C++, the operand might be an overloaded function name, in which case 7310/// we allow the '&' but retain the overloaded-function type. 7311static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 7312 SourceLocation OpLoc) { 7313 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 7314 if (PTy->getKind() == BuiltinType::Overload) { 7315 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 7316 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7317 << OrigOp.get()->getSourceRange(); 7318 return QualType(); 7319 } 7320 7321 return S.Context.OverloadTy; 7322 } 7323 7324 if (PTy->getKind() == BuiltinType::UnknownAny) 7325 return S.Context.UnknownAnyTy; 7326 7327 if (PTy->getKind() == BuiltinType::BoundMember) { 7328 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7329 << OrigOp.get()->getSourceRange(); 7330 return QualType(); 7331 } 7332 7333 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 7334 if (OrigOp.isInvalid()) return QualType(); 7335 } 7336 7337 if (OrigOp.get()->isTypeDependent()) 7338 return S.Context.DependentTy; 7339 7340 assert(!OrigOp.get()->getType()->isPlaceholderType()); 7341 7342 // Make sure to ignore parentheses in subsequent checks 7343 Expr *op = OrigOp.get()->IgnoreParens(); 7344 7345 if (S.getLangOptions().C99) { 7346 // Implement C99-only parts of addressof rules. 7347 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 7348 if (uOp->getOpcode() == UO_Deref) 7349 // Per C99 6.5.3.2, the address of a deref always returns a valid result 7350 // (assuming the deref expression is valid). 7351 return uOp->getSubExpr()->getType(); 7352 } 7353 // Technically, there should be a check for array subscript 7354 // expressions here, but the result of one is always an lvalue anyway. 7355 } 7356 ValueDecl *dcl = getPrimaryDecl(op); 7357 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 7358 unsigned AddressOfError = AO_No_Error; 7359 7360 if (lval == Expr::LV_ClassTemporary) { 7361 bool sfinae = S.isSFINAEContext(); 7362 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary 7363 : diag::ext_typecheck_addrof_class_temporary) 7364 << op->getType() << op->getSourceRange(); 7365 if (sfinae) 7366 return QualType(); 7367 } else if (isa<ObjCSelectorExpr>(op)) { 7368 return S.Context.getPointerType(op->getType()); 7369 } else if (lval == Expr::LV_MemberFunction) { 7370 // If it's an instance method, make a member pointer. 7371 // The expression must have exactly the form &A::foo. 7372 7373 // If the underlying expression isn't a decl ref, give up. 7374 if (!isa<DeclRefExpr>(op)) { 7375 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7376 << OrigOp.get()->getSourceRange(); 7377 return QualType(); 7378 } 7379 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 7380 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 7381 7382 // The id-expression was parenthesized. 7383 if (OrigOp.get() != DRE) { 7384 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 7385 << OrigOp.get()->getSourceRange(); 7386 7387 // The method was named without a qualifier. 7388 } else if (!DRE->getQualifier()) { 7389 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 7390 << op->getSourceRange(); 7391 } 7392 7393 return S.Context.getMemberPointerType(op->getType(), 7394 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 7395 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 7396 // C99 6.5.3.2p1 7397 // The operand must be either an l-value or a function designator 7398 if (!op->getType()->isFunctionType()) { 7399 // Use a special diagnostic for loads from property references. 7400 if (isa<PseudoObjectExpr>(op)) { 7401 AddressOfError = AO_Property_Expansion; 7402 } else { 7403 // FIXME: emit more specific diag... 7404 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7405 << op->getSourceRange(); 7406 return QualType(); 7407 } 7408 } 7409 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 7410 // The operand cannot be a bit-field 7411 AddressOfError = AO_Bit_Field; 7412 } else if (op->getObjectKind() == OK_VectorComponent) { 7413 // The operand cannot be an element of a vector 7414 AddressOfError = AO_Vector_Element; 7415 } else if (dcl) { // C99 6.5.3.2p1 7416 // We have an lvalue with a decl. Make sure the decl is not declared 7417 // with the register storage-class specifier. 7418 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 7419 // in C++ it is not error to take address of a register 7420 // variable (c++03 7.1.1P3) 7421 if (vd->getStorageClass() == SC_Register && 7422 !S.getLangOptions().CPlusPlus) { 7423 AddressOfError = AO_Register_Variable; 7424 } 7425 } else if (isa<FunctionTemplateDecl>(dcl)) { 7426 return S.Context.OverloadTy; 7427 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 7428 // Okay: we can take the address of a field. 7429 // Could be a pointer to member, though, if there is an explicit 7430 // scope qualifier for the class. 7431 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 7432 DeclContext *Ctx = dcl->getDeclContext(); 7433 if (Ctx && Ctx->isRecord()) { 7434 if (dcl->getType()->isReferenceType()) { 7435 S.Diag(OpLoc, 7436 diag::err_cannot_form_pointer_to_member_of_reference_type) 7437 << dcl->getDeclName() << dcl->getType(); 7438 return QualType(); 7439 } 7440 7441 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 7442 Ctx = Ctx->getParent(); 7443 return S.Context.getMemberPointerType(op->getType(), 7444 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 7445 } 7446 } 7447 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 7448 llvm_unreachable("Unknown/unexpected decl type"); 7449 } 7450 7451 if (AddressOfError != AO_No_Error) { 7452 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 7453 return QualType(); 7454 } 7455 7456 if (lval == Expr::LV_IncompleteVoidType) { 7457 // Taking the address of a void variable is technically illegal, but we 7458 // allow it in cases which are otherwise valid. 7459 // Example: "extern void x; void* y = &x;". 7460 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 7461 } 7462 7463 // If the operand has type "type", the result has type "pointer to type". 7464 if (op->getType()->isObjCObjectType()) 7465 return S.Context.getObjCObjectPointerType(op->getType()); 7466 return S.Context.getPointerType(op->getType()); 7467} 7468 7469/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 7470static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 7471 SourceLocation OpLoc) { 7472 if (Op->isTypeDependent()) 7473 return S.Context.DependentTy; 7474 7475 ExprResult ConvResult = S.UsualUnaryConversions(Op); 7476 if (ConvResult.isInvalid()) 7477 return QualType(); 7478 Op = ConvResult.take(); 7479 QualType OpTy = Op->getType(); 7480 QualType Result; 7481 7482 if (isa<CXXReinterpretCastExpr>(Op)) { 7483 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 7484 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 7485 Op->getSourceRange()); 7486 } 7487 7488 // Note that per both C89 and C99, indirection is always legal, even if OpTy 7489 // is an incomplete type or void. It would be possible to warn about 7490 // dereferencing a void pointer, but it's completely well-defined, and such a 7491 // warning is unlikely to catch any mistakes. 7492 if (const PointerType *PT = OpTy->getAs<PointerType>()) 7493 Result = PT->getPointeeType(); 7494 else if (const ObjCObjectPointerType *OPT = 7495 OpTy->getAs<ObjCObjectPointerType>()) 7496 Result = OPT->getPointeeType(); 7497 else { 7498 ExprResult PR = S.CheckPlaceholderExpr(Op); 7499 if (PR.isInvalid()) return QualType(); 7500 if (PR.take() != Op) 7501 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 7502 } 7503 7504 if (Result.isNull()) { 7505 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 7506 << OpTy << Op->getSourceRange(); 7507 return QualType(); 7508 } 7509 7510 // Dereferences are usually l-values... 7511 VK = VK_LValue; 7512 7513 // ...except that certain expressions are never l-values in C. 7514 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType()) 7515 VK = VK_RValue; 7516 7517 return Result; 7518} 7519 7520static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 7521 tok::TokenKind Kind) { 7522 BinaryOperatorKind Opc; 7523 switch (Kind) { 7524 default: llvm_unreachable("Unknown binop!"); 7525 case tok::periodstar: Opc = BO_PtrMemD; break; 7526 case tok::arrowstar: Opc = BO_PtrMemI; break; 7527 case tok::star: Opc = BO_Mul; break; 7528 case tok::slash: Opc = BO_Div; break; 7529 case tok::percent: Opc = BO_Rem; break; 7530 case tok::plus: Opc = BO_Add; break; 7531 case tok::minus: Opc = BO_Sub; break; 7532 case tok::lessless: Opc = BO_Shl; break; 7533 case tok::greatergreater: Opc = BO_Shr; break; 7534 case tok::lessequal: Opc = BO_LE; break; 7535 case tok::less: Opc = BO_LT; break; 7536 case tok::greaterequal: Opc = BO_GE; break; 7537 case tok::greater: Opc = BO_GT; break; 7538 case tok::exclaimequal: Opc = BO_NE; break; 7539 case tok::equalequal: Opc = BO_EQ; break; 7540 case tok::amp: Opc = BO_And; break; 7541 case tok::caret: Opc = BO_Xor; break; 7542 case tok::pipe: Opc = BO_Or; break; 7543 case tok::ampamp: Opc = BO_LAnd; break; 7544 case tok::pipepipe: Opc = BO_LOr; break; 7545 case tok::equal: Opc = BO_Assign; break; 7546 case tok::starequal: Opc = BO_MulAssign; break; 7547 case tok::slashequal: Opc = BO_DivAssign; break; 7548 case tok::percentequal: Opc = BO_RemAssign; break; 7549 case tok::plusequal: Opc = BO_AddAssign; break; 7550 case tok::minusequal: Opc = BO_SubAssign; break; 7551 case tok::lesslessequal: Opc = BO_ShlAssign; break; 7552 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 7553 case tok::ampequal: Opc = BO_AndAssign; break; 7554 case tok::caretequal: Opc = BO_XorAssign; break; 7555 case tok::pipeequal: Opc = BO_OrAssign; break; 7556 case tok::comma: Opc = BO_Comma; break; 7557 } 7558 return Opc; 7559} 7560 7561static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 7562 tok::TokenKind Kind) { 7563 UnaryOperatorKind Opc; 7564 switch (Kind) { 7565 default: llvm_unreachable("Unknown unary op!"); 7566 case tok::plusplus: Opc = UO_PreInc; break; 7567 case tok::minusminus: Opc = UO_PreDec; break; 7568 case tok::amp: Opc = UO_AddrOf; break; 7569 case tok::star: Opc = UO_Deref; break; 7570 case tok::plus: Opc = UO_Plus; break; 7571 case tok::minus: Opc = UO_Minus; break; 7572 case tok::tilde: Opc = UO_Not; break; 7573 case tok::exclaim: Opc = UO_LNot; break; 7574 case tok::kw___real: Opc = UO_Real; break; 7575 case tok::kw___imag: Opc = UO_Imag; break; 7576 case tok::kw___extension__: Opc = UO_Extension; break; 7577 } 7578 return Opc; 7579} 7580 7581/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 7582/// This warning is only emitted for builtin assignment operations. It is also 7583/// suppressed in the event of macro expansions. 7584static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 7585 SourceLocation OpLoc) { 7586 if (!S.ActiveTemplateInstantiations.empty()) 7587 return; 7588 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 7589 return; 7590 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 7591 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 7592 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 7593 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 7594 if (!LHSDeclRef || !RHSDeclRef || 7595 LHSDeclRef->getLocation().isMacroID() || 7596 RHSDeclRef->getLocation().isMacroID()) 7597 return; 7598 const ValueDecl *LHSDecl = 7599 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 7600 const ValueDecl *RHSDecl = 7601 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 7602 if (LHSDecl != RHSDecl) 7603 return; 7604 if (LHSDecl->getType().isVolatileQualified()) 7605 return; 7606 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 7607 if (RefTy->getPointeeType().isVolatileQualified()) 7608 return; 7609 7610 S.Diag(OpLoc, diag::warn_self_assignment) 7611 << LHSDeclRef->getType() 7612 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7613} 7614 7615/// CreateBuiltinBinOp - Creates a new built-in binary operation with 7616/// operator @p Opc at location @c TokLoc. This routine only supports 7617/// built-in operations; ActOnBinOp handles overloaded operators. 7618ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 7619 BinaryOperatorKind Opc, 7620 Expr *LHSExpr, Expr *RHSExpr) { 7621 if (getLangOptions().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) { 7622 // The syntax only allows initializer lists on the RHS of assignment, 7623 // so we don't need to worry about accepting invalid code for 7624 // non-assignment operators. 7625 // C++11 5.17p9: 7626 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 7627 // of x = {} is x = T(). 7628 InitializationKind Kind = 7629 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 7630 InitializedEntity Entity = 7631 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 7632 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1); 7633 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 7634 MultiExprArg(&RHSExpr, 1)); 7635 if (Init.isInvalid()) 7636 return Init; 7637 RHSExpr = Init.take(); 7638 } 7639 7640 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 7641 QualType ResultTy; // Result type of the binary operator. 7642 // The following two variables are used for compound assignment operators 7643 QualType CompLHSTy; // Type of LHS after promotions for computation 7644 QualType CompResultTy; // Type of computation result 7645 ExprValueKind VK = VK_RValue; 7646 ExprObjectKind OK = OK_Ordinary; 7647 7648 switch (Opc) { 7649 case BO_Assign: 7650 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 7651 if (getLangOptions().CPlusPlus && 7652 LHS.get()->getObjectKind() != OK_ObjCProperty) { 7653 VK = LHS.get()->getValueKind(); 7654 OK = LHS.get()->getObjectKind(); 7655 } 7656 if (!ResultTy.isNull()) 7657 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 7658 break; 7659 case BO_PtrMemD: 7660 case BO_PtrMemI: 7661 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 7662 Opc == BO_PtrMemI); 7663 break; 7664 case BO_Mul: 7665 case BO_Div: 7666 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 7667 Opc == BO_Div); 7668 break; 7669 case BO_Rem: 7670 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 7671 break; 7672 case BO_Add: 7673 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc); 7674 break; 7675 case BO_Sub: 7676 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 7677 break; 7678 case BO_Shl: 7679 case BO_Shr: 7680 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 7681 break; 7682 case BO_LE: 7683 case BO_LT: 7684 case BO_GE: 7685 case BO_GT: 7686 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 7687 break; 7688 case BO_EQ: 7689 case BO_NE: 7690 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 7691 break; 7692 case BO_And: 7693 case BO_Xor: 7694 case BO_Or: 7695 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 7696 break; 7697 case BO_LAnd: 7698 case BO_LOr: 7699 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 7700 break; 7701 case BO_MulAssign: 7702 case BO_DivAssign: 7703 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 7704 Opc == BO_DivAssign); 7705 CompLHSTy = CompResultTy; 7706 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7707 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7708 break; 7709 case BO_RemAssign: 7710 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 7711 CompLHSTy = CompResultTy; 7712 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7713 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7714 break; 7715 case BO_AddAssign: 7716 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy); 7717 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7718 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7719 break; 7720 case BO_SubAssign: 7721 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 7722 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7723 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7724 break; 7725 case BO_ShlAssign: 7726 case BO_ShrAssign: 7727 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 7728 CompLHSTy = CompResultTy; 7729 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7730 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7731 break; 7732 case BO_AndAssign: 7733 case BO_XorAssign: 7734 case BO_OrAssign: 7735 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 7736 CompLHSTy = CompResultTy; 7737 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 7738 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 7739 break; 7740 case BO_Comma: 7741 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 7742 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) { 7743 VK = RHS.get()->getValueKind(); 7744 OK = RHS.get()->getObjectKind(); 7745 } 7746 break; 7747 } 7748 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 7749 return ExprError(); 7750 7751 // Check for array bounds violations for both sides of the BinaryOperator 7752 CheckArrayAccess(LHS.get()); 7753 CheckArrayAccess(RHS.get()); 7754 7755 if (CompResultTy.isNull()) 7756 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 7757 ResultTy, VK, OK, OpLoc)); 7758 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() != 7759 OK_ObjCProperty) { 7760 VK = VK_LValue; 7761 OK = LHS.get()->getObjectKind(); 7762 } 7763 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 7764 ResultTy, VK, OK, CompLHSTy, 7765 CompResultTy, OpLoc)); 7766} 7767 7768/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 7769/// operators are mixed in a way that suggests that the programmer forgot that 7770/// comparison operators have higher precedence. The most typical example of 7771/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 7772static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 7773 SourceLocation OpLoc, Expr *LHSExpr, 7774 Expr *RHSExpr) { 7775 typedef BinaryOperator BinOp; 7776 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1), 7777 RHSopc = static_cast<BinOp::Opcode>(-1); 7778 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr)) 7779 LHSopc = BO->getOpcode(); 7780 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr)) 7781 RHSopc = BO->getOpcode(); 7782 7783 // Subs are not binary operators. 7784 if (LHSopc == -1 && RHSopc == -1) 7785 return; 7786 7787 // Bitwise operations are sometimes used as eager logical ops. 7788 // Don't diagnose this. 7789 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) && 7790 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc))) 7791 return; 7792 7793 bool isLeftComp = BinOp::isComparisonOp(LHSopc); 7794 bool isRightComp = BinOp::isComparisonOp(RHSopc); 7795 if (!isLeftComp && !isRightComp) return; 7796 7797 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 7798 OpLoc) 7799 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 7800 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc) 7801 : BinOp::getOpcodeStr(RHSopc); 7802 SourceRange ParensRange = isLeftComp ? 7803 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(), 7804 RHSExpr->getLocEnd()) 7805 : SourceRange(LHSExpr->getLocStart(), 7806 cast<BinOp>(RHSExpr)->getLHS()->getLocStart()); 7807 7808 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 7809 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr; 7810 SuggestParentheses(Self, OpLoc, 7811 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr, 7812 RHSExpr->getSourceRange()); 7813 SuggestParentheses(Self, OpLoc, 7814 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc), 7815 ParensRange); 7816} 7817 7818/// \brief It accepts a '&' expr that is inside a '|' one. 7819/// Emit a diagnostic together with a fixit hint that wraps the '&' expression 7820/// in parentheses. 7821static void 7822EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 7823 BinaryOperator *Bop) { 7824 assert(Bop->getOpcode() == BO_And); 7825 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 7826 << Bop->getSourceRange() << OpLoc; 7827 SuggestParentheses(Self, Bop->getOperatorLoc(), 7828 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence), 7829 Bop->getSourceRange()); 7830} 7831 7832/// \brief It accepts a '&&' expr that is inside a '||' one. 7833/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 7834/// in parentheses. 7835static void 7836EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 7837 BinaryOperator *Bop) { 7838 assert(Bop->getOpcode() == BO_LAnd); 7839 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 7840 << Bop->getSourceRange() << OpLoc; 7841 SuggestParentheses(Self, Bop->getOperatorLoc(), 7842 Self.PDiag(diag::note_logical_and_in_logical_or_silence), 7843 Bop->getSourceRange()); 7844} 7845 7846/// \brief Returns true if the given expression can be evaluated as a constant 7847/// 'true'. 7848static bool EvaluatesAsTrue(Sema &S, Expr *E) { 7849 bool Res; 7850 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 7851} 7852 7853/// \brief Returns true if the given expression can be evaluated as a constant 7854/// 'false'. 7855static bool EvaluatesAsFalse(Sema &S, Expr *E) { 7856 bool Res; 7857 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 7858} 7859 7860/// \brief Look for '&&' in the left hand of a '||' expr. 7861static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 7862 Expr *LHSExpr, Expr *RHSExpr) { 7863 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 7864 if (Bop->getOpcode() == BO_LAnd) { 7865 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 7866 if (EvaluatesAsFalse(S, RHSExpr)) 7867 return; 7868 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 7869 if (!EvaluatesAsTrue(S, Bop->getLHS())) 7870 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 7871 } else if (Bop->getOpcode() == BO_LOr) { 7872 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 7873 // If it's "a || b && 1 || c" we didn't warn earlier for 7874 // "a || b && 1", but warn now. 7875 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 7876 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 7877 } 7878 } 7879 } 7880} 7881 7882/// \brief Look for '&&' in the right hand of a '||' expr. 7883static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 7884 Expr *LHSExpr, Expr *RHSExpr) { 7885 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 7886 if (Bop->getOpcode() == BO_LAnd) { 7887 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 7888 if (EvaluatesAsFalse(S, LHSExpr)) 7889 return; 7890 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 7891 if (!EvaluatesAsTrue(S, Bop->getRHS())) 7892 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 7893 } 7894 } 7895} 7896 7897/// \brief Look for '&' in the left or right hand of a '|' expr. 7898static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 7899 Expr *OrArg) { 7900 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 7901 if (Bop->getOpcode() == BO_And) 7902 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 7903 } 7904} 7905 7906/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 7907/// precedence. 7908static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 7909 SourceLocation OpLoc, Expr *LHSExpr, 7910 Expr *RHSExpr){ 7911 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 7912 if (BinaryOperator::isBitwiseOp(Opc)) 7913 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 7914 7915 // Diagnose "arg1 & arg2 | arg3" 7916 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 7917 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 7918 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 7919 } 7920 7921 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 7922 // We don't warn for 'assert(a || b && "bad")' since this is safe. 7923 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 7924 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 7925 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 7926 } 7927} 7928 7929// Binary Operators. 'Tok' is the token for the operator. 7930ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 7931 tok::TokenKind Kind, 7932 Expr *LHSExpr, Expr *RHSExpr) { 7933 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 7934 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 7935 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 7936 7937 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 7938 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 7939 7940 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 7941} 7942 7943/// Build an overloaded binary operator expression in the given scope. 7944static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 7945 BinaryOperatorKind Opc, 7946 Expr *LHS, Expr *RHS) { 7947 // Find all of the overloaded operators visible from this 7948 // point. We perform both an operator-name lookup from the local 7949 // scope and an argument-dependent lookup based on the types of 7950 // the arguments. 7951 UnresolvedSet<16> Functions; 7952 OverloadedOperatorKind OverOp 7953 = BinaryOperator::getOverloadedOperator(Opc); 7954 if (Sc && OverOp != OO_None) 7955 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 7956 RHS->getType(), Functions); 7957 7958 // Build the (potentially-overloaded, potentially-dependent) 7959 // binary operation. 7960 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 7961} 7962 7963ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 7964 BinaryOperatorKind Opc, 7965 Expr *LHSExpr, Expr *RHSExpr) { 7966 // We want to end up calling one of checkPseudoObjectAssignment 7967 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 7968 // both expressions are overloadable or either is type-dependent), 7969 // or CreateBuiltinBinOp (in any other case). We also want to get 7970 // any placeholder types out of the way. 7971 7972 // Handle pseudo-objects in the LHS. 7973 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 7974 // Assignments with a pseudo-object l-value need special analysis. 7975 if (pty->getKind() == BuiltinType::PseudoObject && 7976 BinaryOperator::isAssignmentOp(Opc)) 7977 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 7978 7979 // Don't resolve overloads if the other type is overloadable. 7980 if (pty->getKind() == BuiltinType::Overload) { 7981 // We can't actually test that if we still have a placeholder, 7982 // though. Fortunately, none of the exceptions we see in that 7983 // code below are valid when the LHS is an overload set. Note 7984 // that an overload set can be dependently-typed, but it never 7985 // instantiates to having an overloadable type. 7986 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 7987 if (resolvedRHS.isInvalid()) return ExprError(); 7988 RHSExpr = resolvedRHS.take(); 7989 7990 if (RHSExpr->isTypeDependent() || 7991 RHSExpr->getType()->isOverloadableType()) 7992 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 7993 } 7994 7995 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 7996 if (LHS.isInvalid()) return ExprError(); 7997 LHSExpr = LHS.take(); 7998 } 7999 8000 // Handle pseudo-objects in the RHS. 8001 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 8002 // An overload in the RHS can potentially be resolved by the type 8003 // being assigned to. 8004 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 8005 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8006 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8007 8008 if (LHSExpr->getType()->isOverloadableType()) 8009 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8010 8011 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8012 } 8013 8014 // Don't resolve overloads if the other type is overloadable. 8015 if (pty->getKind() == BuiltinType::Overload && 8016 LHSExpr->getType()->isOverloadableType()) 8017 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8018 8019 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8020 if (!resolvedRHS.isUsable()) return ExprError(); 8021 RHSExpr = resolvedRHS.take(); 8022 } 8023 8024 if (getLangOptions().CPlusPlus) { 8025 // If either expression is type-dependent, always build an 8026 // overloaded op. 8027 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8028 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8029 8030 // Otherwise, build an overloaded op if either expression has an 8031 // overloadable type. 8032 if (LHSExpr->getType()->isOverloadableType() || 8033 RHSExpr->getType()->isOverloadableType()) 8034 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8035 } 8036 8037 // Build a built-in binary operation. 8038 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8039} 8040 8041ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 8042 UnaryOperatorKind Opc, 8043 Expr *InputExpr) { 8044 ExprResult Input = Owned(InputExpr); 8045 ExprValueKind VK = VK_RValue; 8046 ExprObjectKind OK = OK_Ordinary; 8047 QualType resultType; 8048 switch (Opc) { 8049 case UO_PreInc: 8050 case UO_PreDec: 8051 case UO_PostInc: 8052 case UO_PostDec: 8053 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 8054 Opc == UO_PreInc || 8055 Opc == UO_PostInc, 8056 Opc == UO_PreInc || 8057 Opc == UO_PreDec); 8058 break; 8059 case UO_AddrOf: 8060 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 8061 break; 8062 case UO_Deref: { 8063 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8064 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 8065 break; 8066 } 8067 case UO_Plus: 8068 case UO_Minus: 8069 Input = UsualUnaryConversions(Input.take()); 8070 if (Input.isInvalid()) return ExprError(); 8071 resultType = Input.get()->getType(); 8072 if (resultType->isDependentType()) 8073 break; 8074 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 8075 resultType->isVectorType()) 8076 break; 8077 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 8078 resultType->isEnumeralType()) 8079 break; 8080 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 8081 Opc == UO_Plus && 8082 resultType->isPointerType()) 8083 break; 8084 8085 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8086 << resultType << Input.get()->getSourceRange()); 8087 8088 case UO_Not: // bitwise complement 8089 Input = UsualUnaryConversions(Input.take()); 8090 if (Input.isInvalid()) return ExprError(); 8091 resultType = Input.get()->getType(); 8092 if (resultType->isDependentType()) 8093 break; 8094 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 8095 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 8096 // C99 does not support '~' for complex conjugation. 8097 Diag(OpLoc, diag::ext_integer_complement_complex) 8098 << resultType << Input.get()->getSourceRange(); 8099 else if (resultType->hasIntegerRepresentation()) 8100 break; 8101 else { 8102 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8103 << resultType << Input.get()->getSourceRange()); 8104 } 8105 break; 8106 8107 case UO_LNot: // logical negation 8108 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 8109 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8110 if (Input.isInvalid()) return ExprError(); 8111 resultType = Input.get()->getType(); 8112 8113 // Though we still have to promote half FP to float... 8114 if (resultType->isHalfType()) { 8115 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 8116 resultType = Context.FloatTy; 8117 } 8118 8119 if (resultType->isDependentType()) 8120 break; 8121 if (resultType->isScalarType()) { 8122 // C99 6.5.3.3p1: ok, fallthrough; 8123 if (Context.getLangOptions().CPlusPlus) { 8124 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 8125 // operand contextually converted to bool. 8126 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 8127 ScalarTypeToBooleanCastKind(resultType)); 8128 } 8129 } else if (resultType->isExtVectorType()) { 8130 // Vector logical not returns the signed variant of the operand type. 8131 resultType = GetSignedVectorType(resultType); 8132 break; 8133 } else { 8134 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8135 << resultType << Input.get()->getSourceRange()); 8136 } 8137 8138 // LNot always has type int. C99 6.5.3.3p5. 8139 // In C++, it's bool. C++ 5.3.1p8 8140 resultType = Context.getLogicalOperationType(); 8141 break; 8142 case UO_Real: 8143 case UO_Imag: 8144 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 8145 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 8146 // complex l-values to ordinary l-values and all other values to r-values. 8147 if (Input.isInvalid()) return ExprError(); 8148 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 8149 if (Input.get()->getValueKind() != VK_RValue && 8150 Input.get()->getObjectKind() == OK_Ordinary) 8151 VK = Input.get()->getValueKind(); 8152 } else if (!getLangOptions().CPlusPlus) { 8153 // In C, a volatile scalar is read by __imag. In C++, it is not. 8154 Input = DefaultLvalueConversion(Input.take()); 8155 } 8156 break; 8157 case UO_Extension: 8158 resultType = Input.get()->getType(); 8159 VK = Input.get()->getValueKind(); 8160 OK = Input.get()->getObjectKind(); 8161 break; 8162 } 8163 if (resultType.isNull() || Input.isInvalid()) 8164 return ExprError(); 8165 8166 // Check for array bounds violations in the operand of the UnaryOperator, 8167 // except for the '*' and '&' operators that have to be handled specially 8168 // by CheckArrayAccess (as there are special cases like &array[arraysize] 8169 // that are explicitly defined as valid by the standard). 8170 if (Opc != UO_AddrOf && Opc != UO_Deref) 8171 CheckArrayAccess(Input.get()); 8172 8173 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 8174 VK, OK, OpLoc)); 8175} 8176 8177/// \brief Determine whether the given expression is a qualified member 8178/// access expression, of a form that could be turned into a pointer to member 8179/// with the address-of operator. 8180static bool isQualifiedMemberAccess(Expr *E) { 8181 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8182 if (!DRE->getQualifier()) 8183 return false; 8184 8185 ValueDecl *VD = DRE->getDecl(); 8186 if (!VD->isCXXClassMember()) 8187 return false; 8188 8189 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 8190 return true; 8191 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 8192 return Method->isInstance(); 8193 8194 return false; 8195 } 8196 8197 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 8198 if (!ULE->getQualifier()) 8199 return false; 8200 8201 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 8202 DEnd = ULE->decls_end(); 8203 D != DEnd; ++D) { 8204 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 8205 if (Method->isInstance()) 8206 return true; 8207 } else { 8208 // Overload set does not contain methods. 8209 break; 8210 } 8211 } 8212 8213 return false; 8214 } 8215 8216 return false; 8217} 8218 8219ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 8220 UnaryOperatorKind Opc, Expr *Input) { 8221 // First things first: handle placeholders so that the 8222 // overloaded-operator check considers the right type. 8223 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 8224 // Increment and decrement of pseudo-object references. 8225 if (pty->getKind() == BuiltinType::PseudoObject && 8226 UnaryOperator::isIncrementDecrementOp(Opc)) 8227 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 8228 8229 // extension is always a builtin operator. 8230 if (Opc == UO_Extension) 8231 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8232 8233 // & gets special logic for several kinds of placeholder. 8234 // The builtin code knows what to do. 8235 if (Opc == UO_AddrOf && 8236 (pty->getKind() == BuiltinType::Overload || 8237 pty->getKind() == BuiltinType::UnknownAny || 8238 pty->getKind() == BuiltinType::BoundMember)) 8239 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8240 8241 // Anything else needs to be handled now. 8242 ExprResult Result = CheckPlaceholderExpr(Input); 8243 if (Result.isInvalid()) return ExprError(); 8244 Input = Result.take(); 8245 } 8246 8247 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() && 8248 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 8249 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 8250 // Find all of the overloaded operators visible from this 8251 // point. We perform both an operator-name lookup from the local 8252 // scope and an argument-dependent lookup based on the types of 8253 // the arguments. 8254 UnresolvedSet<16> Functions; 8255 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 8256 if (S && OverOp != OO_None) 8257 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 8258 Functions); 8259 8260 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 8261 } 8262 8263 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8264} 8265 8266// Unary Operators. 'Tok' is the token for the operator. 8267ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 8268 tok::TokenKind Op, Expr *Input) { 8269 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 8270} 8271 8272/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 8273ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 8274 LabelDecl *TheDecl) { 8275 TheDecl->setUsed(); 8276 // Create the AST node. The address of a label always has type 'void*'. 8277 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 8278 Context.getPointerType(Context.VoidTy))); 8279} 8280 8281/// Given the last statement in a statement-expression, check whether 8282/// the result is a producing expression (like a call to an 8283/// ns_returns_retained function) and, if so, rebuild it to hoist the 8284/// release out of the full-expression. Otherwise, return null. 8285/// Cannot fail. 8286static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 8287 // Should always be wrapped with one of these. 8288 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 8289 if (!cleanups) return 0; 8290 8291 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 8292 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 8293 return 0; 8294 8295 // Splice out the cast. This shouldn't modify any interesting 8296 // features of the statement. 8297 Expr *producer = cast->getSubExpr(); 8298 assert(producer->getType() == cast->getType()); 8299 assert(producer->getValueKind() == cast->getValueKind()); 8300 cleanups->setSubExpr(producer); 8301 return cleanups; 8302} 8303 8304ExprResult 8305Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 8306 SourceLocation RPLoc) { // "({..})" 8307 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 8308 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 8309 8310 bool isFileScope 8311 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 8312 if (isFileScope) 8313 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 8314 8315 // FIXME: there are a variety of strange constraints to enforce here, for 8316 // example, it is not possible to goto into a stmt expression apparently. 8317 // More semantic analysis is needed. 8318 8319 // If there are sub stmts in the compound stmt, take the type of the last one 8320 // as the type of the stmtexpr. 8321 QualType Ty = Context.VoidTy; 8322 bool StmtExprMayBindToTemp = false; 8323 if (!Compound->body_empty()) { 8324 Stmt *LastStmt = Compound->body_back(); 8325 LabelStmt *LastLabelStmt = 0; 8326 // If LastStmt is a label, skip down through into the body. 8327 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 8328 LastLabelStmt = Label; 8329 LastStmt = Label->getSubStmt(); 8330 } 8331 8332 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 8333 // Do function/array conversion on the last expression, but not 8334 // lvalue-to-rvalue. However, initialize an unqualified type. 8335 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 8336 if (LastExpr.isInvalid()) 8337 return ExprError(); 8338 Ty = LastExpr.get()->getType().getUnqualifiedType(); 8339 8340 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 8341 // In ARC, if the final expression ends in a consume, splice 8342 // the consume out and bind it later. In the alternate case 8343 // (when dealing with a retainable type), the result 8344 // initialization will create a produce. In both cases the 8345 // result will be +1, and we'll need to balance that out with 8346 // a bind. 8347 if (Expr *rebuiltLastStmt 8348 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 8349 LastExpr = rebuiltLastStmt; 8350 } else { 8351 LastExpr = PerformCopyInitialization( 8352 InitializedEntity::InitializeResult(LPLoc, 8353 Ty, 8354 false), 8355 SourceLocation(), 8356 LastExpr); 8357 } 8358 8359 if (LastExpr.isInvalid()) 8360 return ExprError(); 8361 if (LastExpr.get() != 0) { 8362 if (!LastLabelStmt) 8363 Compound->setLastStmt(LastExpr.take()); 8364 else 8365 LastLabelStmt->setSubStmt(LastExpr.take()); 8366 StmtExprMayBindToTemp = true; 8367 } 8368 } 8369 } 8370 } 8371 8372 // FIXME: Check that expression type is complete/non-abstract; statement 8373 // expressions are not lvalues. 8374 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 8375 if (StmtExprMayBindToTemp) 8376 return MaybeBindToTemporary(ResStmtExpr); 8377 return Owned(ResStmtExpr); 8378} 8379 8380ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 8381 TypeSourceInfo *TInfo, 8382 OffsetOfComponent *CompPtr, 8383 unsigned NumComponents, 8384 SourceLocation RParenLoc) { 8385 QualType ArgTy = TInfo->getType(); 8386 bool Dependent = ArgTy->isDependentType(); 8387 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 8388 8389 // We must have at least one component that refers to the type, and the first 8390 // one is known to be a field designator. Verify that the ArgTy represents 8391 // a struct/union/class. 8392 if (!Dependent && !ArgTy->isRecordType()) 8393 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 8394 << ArgTy << TypeRange); 8395 8396 // Type must be complete per C99 7.17p3 because a declaring a variable 8397 // with an incomplete type would be ill-formed. 8398 if (!Dependent 8399 && RequireCompleteType(BuiltinLoc, ArgTy, 8400 PDiag(diag::err_offsetof_incomplete_type) 8401 << TypeRange)) 8402 return ExprError(); 8403 8404 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 8405 // GCC extension, diagnose them. 8406 // FIXME: This diagnostic isn't actually visible because the location is in 8407 // a system header! 8408 if (NumComponents != 1) 8409 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 8410 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 8411 8412 bool DidWarnAboutNonPOD = false; 8413 QualType CurrentType = ArgTy; 8414 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 8415 SmallVector<OffsetOfNode, 4> Comps; 8416 SmallVector<Expr*, 4> Exprs; 8417 for (unsigned i = 0; i != NumComponents; ++i) { 8418 const OffsetOfComponent &OC = CompPtr[i]; 8419 if (OC.isBrackets) { 8420 // Offset of an array sub-field. TODO: Should we allow vector elements? 8421 if (!CurrentType->isDependentType()) { 8422 const ArrayType *AT = Context.getAsArrayType(CurrentType); 8423 if(!AT) 8424 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 8425 << CurrentType); 8426 CurrentType = AT->getElementType(); 8427 } else 8428 CurrentType = Context.DependentTy; 8429 8430 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 8431 if (IdxRval.isInvalid()) 8432 return ExprError(); 8433 Expr *Idx = IdxRval.take(); 8434 8435 // The expression must be an integral expression. 8436 // FIXME: An integral constant expression? 8437 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 8438 !Idx->getType()->isIntegerType()) 8439 return ExprError(Diag(Idx->getLocStart(), 8440 diag::err_typecheck_subscript_not_integer) 8441 << Idx->getSourceRange()); 8442 8443 // Record this array index. 8444 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 8445 Exprs.push_back(Idx); 8446 continue; 8447 } 8448 8449 // Offset of a field. 8450 if (CurrentType->isDependentType()) { 8451 // We have the offset of a field, but we can't look into the dependent 8452 // type. Just record the identifier of the field. 8453 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 8454 CurrentType = Context.DependentTy; 8455 continue; 8456 } 8457 8458 // We need to have a complete type to look into. 8459 if (RequireCompleteType(OC.LocStart, CurrentType, 8460 diag::err_offsetof_incomplete_type)) 8461 return ExprError(); 8462 8463 // Look for the designated field. 8464 const RecordType *RC = CurrentType->getAs<RecordType>(); 8465 if (!RC) 8466 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 8467 << CurrentType); 8468 RecordDecl *RD = RC->getDecl(); 8469 8470 // C++ [lib.support.types]p5: 8471 // The macro offsetof accepts a restricted set of type arguments in this 8472 // International Standard. type shall be a POD structure or a POD union 8473 // (clause 9). 8474 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 8475 if (!CRD->isPOD() && !DidWarnAboutNonPOD && 8476 DiagRuntimeBehavior(BuiltinLoc, 0, 8477 PDiag(diag::warn_offsetof_non_pod_type) 8478 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 8479 << CurrentType)) 8480 DidWarnAboutNonPOD = true; 8481 } 8482 8483 // Look for the field. 8484 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 8485 LookupQualifiedName(R, RD); 8486 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 8487 IndirectFieldDecl *IndirectMemberDecl = 0; 8488 if (!MemberDecl) { 8489 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 8490 MemberDecl = IndirectMemberDecl->getAnonField(); 8491 } 8492 8493 if (!MemberDecl) 8494 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 8495 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 8496 OC.LocEnd)); 8497 8498 // C99 7.17p3: 8499 // (If the specified member is a bit-field, the behavior is undefined.) 8500 // 8501 // We diagnose this as an error. 8502 if (MemberDecl->isBitField()) { 8503 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 8504 << MemberDecl->getDeclName() 8505 << SourceRange(BuiltinLoc, RParenLoc); 8506 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 8507 return ExprError(); 8508 } 8509 8510 RecordDecl *Parent = MemberDecl->getParent(); 8511 if (IndirectMemberDecl) 8512 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 8513 8514 // If the member was found in a base class, introduce OffsetOfNodes for 8515 // the base class indirections. 8516 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8517 /*DetectVirtual=*/false); 8518 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 8519 CXXBasePath &Path = Paths.front(); 8520 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 8521 B != BEnd; ++B) 8522 Comps.push_back(OffsetOfNode(B->Base)); 8523 } 8524 8525 if (IndirectMemberDecl) { 8526 for (IndirectFieldDecl::chain_iterator FI = 8527 IndirectMemberDecl->chain_begin(), 8528 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 8529 assert(isa<FieldDecl>(*FI)); 8530 Comps.push_back(OffsetOfNode(OC.LocStart, 8531 cast<FieldDecl>(*FI), OC.LocEnd)); 8532 } 8533 } else 8534 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 8535 8536 CurrentType = MemberDecl->getType().getNonReferenceType(); 8537 } 8538 8539 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 8540 TInfo, Comps.data(), Comps.size(), 8541 Exprs.data(), Exprs.size(), RParenLoc)); 8542} 8543 8544ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 8545 SourceLocation BuiltinLoc, 8546 SourceLocation TypeLoc, 8547 ParsedType ParsedArgTy, 8548 OffsetOfComponent *CompPtr, 8549 unsigned NumComponents, 8550 SourceLocation RParenLoc) { 8551 8552 TypeSourceInfo *ArgTInfo; 8553 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 8554 if (ArgTy.isNull()) 8555 return ExprError(); 8556 8557 if (!ArgTInfo) 8558 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 8559 8560 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 8561 RParenLoc); 8562} 8563 8564 8565ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 8566 Expr *CondExpr, 8567 Expr *LHSExpr, Expr *RHSExpr, 8568 SourceLocation RPLoc) { 8569 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 8570 8571 ExprValueKind VK = VK_RValue; 8572 ExprObjectKind OK = OK_Ordinary; 8573 QualType resType; 8574 bool ValueDependent = false; 8575 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 8576 resType = Context.DependentTy; 8577 ValueDependent = true; 8578 } else { 8579 // The conditional expression is required to be a constant expression. 8580 llvm::APSInt condEval(32); 8581 ExprResult CondICE = VerifyIntegerConstantExpression(CondExpr, &condEval, 8582 PDiag(diag::err_typecheck_choose_expr_requires_constant), false); 8583 if (CondICE.isInvalid()) 8584 return ExprError(); 8585 CondExpr = CondICE.take(); 8586 8587 // If the condition is > zero, then the AST type is the same as the LSHExpr. 8588 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 8589 8590 resType = ActiveExpr->getType(); 8591 ValueDependent = ActiveExpr->isValueDependent(); 8592 VK = ActiveExpr->getValueKind(); 8593 OK = ActiveExpr->getObjectKind(); 8594 } 8595 8596 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 8597 resType, VK, OK, RPLoc, 8598 resType->isDependentType(), 8599 ValueDependent)); 8600} 8601 8602//===----------------------------------------------------------------------===// 8603// Clang Extensions. 8604//===----------------------------------------------------------------------===// 8605 8606/// ActOnBlockStart - This callback is invoked when a block literal is started. 8607void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 8608 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 8609 PushBlockScope(CurScope, Block); 8610 CurContext->addDecl(Block); 8611 if (CurScope) 8612 PushDeclContext(CurScope, Block); 8613 else 8614 CurContext = Block; 8615 8616 getCurBlock()->HasImplicitReturnType = true; 8617 8618 // Enter a new evaluation context to insulate the block from any 8619 // cleanups from the enclosing full-expression. 8620 PushExpressionEvaluationContext(PotentiallyEvaluated); 8621} 8622 8623void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 8624 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 8625 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 8626 BlockScopeInfo *CurBlock = getCurBlock(); 8627 8628 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 8629 QualType T = Sig->getType(); 8630 8631 // GetTypeForDeclarator always produces a function type for a block 8632 // literal signature. Furthermore, it is always a FunctionProtoType 8633 // unless the function was written with a typedef. 8634 assert(T->isFunctionType() && 8635 "GetTypeForDeclarator made a non-function block signature"); 8636 8637 // Look for an explicit signature in that function type. 8638 FunctionProtoTypeLoc ExplicitSignature; 8639 8640 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 8641 if (isa<FunctionProtoTypeLoc>(tmp)) { 8642 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp); 8643 8644 // Check whether that explicit signature was synthesized by 8645 // GetTypeForDeclarator. If so, don't save that as part of the 8646 // written signature. 8647 if (ExplicitSignature.getLocalRangeBegin() == 8648 ExplicitSignature.getLocalRangeEnd()) { 8649 // This would be much cheaper if we stored TypeLocs instead of 8650 // TypeSourceInfos. 8651 TypeLoc Result = ExplicitSignature.getResultLoc(); 8652 unsigned Size = Result.getFullDataSize(); 8653 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 8654 Sig->getTypeLoc().initializeFullCopy(Result, Size); 8655 8656 ExplicitSignature = FunctionProtoTypeLoc(); 8657 } 8658 } 8659 8660 CurBlock->TheDecl->setSignatureAsWritten(Sig); 8661 CurBlock->FunctionType = T; 8662 8663 const FunctionType *Fn = T->getAs<FunctionType>(); 8664 QualType RetTy = Fn->getResultType(); 8665 bool isVariadic = 8666 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 8667 8668 CurBlock->TheDecl->setIsVariadic(isVariadic); 8669 8670 // Don't allow returning a objc interface by value. 8671 if (RetTy->isObjCObjectType()) { 8672 Diag(ParamInfo.getSourceRange().getBegin(), 8673 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 8674 return; 8675 } 8676 8677 // Context.DependentTy is used as a placeholder for a missing block 8678 // return type. TODO: what should we do with declarators like: 8679 // ^ * { ... } 8680 // If the answer is "apply template argument deduction".... 8681 if (RetTy != Context.DependentTy) { 8682 CurBlock->ReturnType = RetTy; 8683 CurBlock->TheDecl->setBlockMissingReturnType(false); 8684 CurBlock->HasImplicitReturnType = false; 8685 } 8686 8687 // Push block parameters from the declarator if we had them. 8688 SmallVector<ParmVarDecl*, 8> Params; 8689 if (ExplicitSignature) { 8690 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 8691 ParmVarDecl *Param = ExplicitSignature.getArg(I); 8692 if (Param->getIdentifier() == 0 && 8693 !Param->isImplicit() && 8694 !Param->isInvalidDecl() && 8695 !getLangOptions().CPlusPlus) 8696 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 8697 Params.push_back(Param); 8698 } 8699 8700 // Fake up parameter variables if we have a typedef, like 8701 // ^ fntype { ... } 8702 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 8703 for (FunctionProtoType::arg_type_iterator 8704 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 8705 ParmVarDecl *Param = 8706 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 8707 ParamInfo.getSourceRange().getBegin(), 8708 *I); 8709 Params.push_back(Param); 8710 } 8711 } 8712 8713 // Set the parameters on the block decl. 8714 if (!Params.empty()) { 8715 CurBlock->TheDecl->setParams(Params); 8716 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 8717 CurBlock->TheDecl->param_end(), 8718 /*CheckParameterNames=*/false); 8719 } 8720 8721 // Finally we can process decl attributes. 8722 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 8723 8724 // Put the parameter variables in scope. We can bail out immediately 8725 // if we don't have any. 8726 if (Params.empty()) 8727 return; 8728 8729 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 8730 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 8731 (*AI)->setOwningFunction(CurBlock->TheDecl); 8732 8733 // If this has an identifier, add it to the scope stack. 8734 if ((*AI)->getIdentifier()) { 8735 CheckShadow(CurBlock->TheScope, *AI); 8736 8737 PushOnScopeChains(*AI, CurBlock->TheScope); 8738 } 8739 } 8740} 8741 8742/// ActOnBlockError - If there is an error parsing a block, this callback 8743/// is invoked to pop the information about the block from the action impl. 8744void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 8745 // Leave the expression-evaluation context. 8746 DiscardCleanupsInEvaluationContext(); 8747 PopExpressionEvaluationContext(); 8748 8749 // Pop off CurBlock, handle nested blocks. 8750 PopDeclContext(); 8751 PopFunctionScopeInfo(); 8752} 8753 8754/// ActOnBlockStmtExpr - This is called when the body of a block statement 8755/// literal was successfully completed. ^(int x){...} 8756ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 8757 Stmt *Body, Scope *CurScope) { 8758 // If blocks are disabled, emit an error. 8759 if (!LangOpts.Blocks) 8760 Diag(CaretLoc, diag::err_blocks_disable); 8761 8762 // Leave the expression-evaluation context. 8763 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 8764 PopExpressionEvaluationContext(); 8765 8766 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 8767 8768 PopDeclContext(); 8769 8770 QualType RetTy = Context.VoidTy; 8771 if (!BSI->ReturnType.isNull()) 8772 RetTy = BSI->ReturnType; 8773 8774 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 8775 QualType BlockTy; 8776 8777 // Set the captured variables on the block. 8778 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 8779 SmallVector<BlockDecl::Capture, 4> Captures; 8780 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 8781 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 8782 if (Cap.isThisCapture()) 8783 continue; 8784 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 8785 Cap.isNested(), Cap.getCopyExpr()); 8786 Captures.push_back(NewCap); 8787 } 8788 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 8789 BSI->CXXThisCaptureIndex != 0); 8790 8791 // If the user wrote a function type in some form, try to use that. 8792 if (!BSI->FunctionType.isNull()) { 8793 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 8794 8795 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 8796 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 8797 8798 // Turn protoless block types into nullary block types. 8799 if (isa<FunctionNoProtoType>(FTy)) { 8800 FunctionProtoType::ExtProtoInfo EPI; 8801 EPI.ExtInfo = Ext; 8802 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 8803 8804 // Otherwise, if we don't need to change anything about the function type, 8805 // preserve its sugar structure. 8806 } else if (FTy->getResultType() == RetTy && 8807 (!NoReturn || FTy->getNoReturnAttr())) { 8808 BlockTy = BSI->FunctionType; 8809 8810 // Otherwise, make the minimal modifications to the function type. 8811 } else { 8812 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 8813 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8814 EPI.TypeQuals = 0; // FIXME: silently? 8815 EPI.ExtInfo = Ext; 8816 BlockTy = Context.getFunctionType(RetTy, 8817 FPT->arg_type_begin(), 8818 FPT->getNumArgs(), 8819 EPI); 8820 } 8821 8822 // If we don't have a function type, just build one from nothing. 8823 } else { 8824 FunctionProtoType::ExtProtoInfo EPI; 8825 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 8826 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 8827 } 8828 8829 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 8830 BSI->TheDecl->param_end()); 8831 BlockTy = Context.getBlockPointerType(BlockTy); 8832 8833 // If needed, diagnose invalid gotos and switches in the block. 8834 if (getCurFunction()->NeedsScopeChecking() && 8835 !hasAnyUnrecoverableErrorsInThisFunction()) 8836 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 8837 8838 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 8839 8840 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(), 8841 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) { 8842 const VarDecl *variable = ci->getVariable(); 8843 QualType T = variable->getType(); 8844 QualType::DestructionKind destructKind = T.isDestructedType(); 8845 if (destructKind != QualType::DK_none) 8846 getCurFunction()->setHasBranchProtectedScope(); 8847 } 8848 8849 computeNRVO(Body, getCurBlock()); 8850 8851 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 8852 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 8853 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 8854 8855 // If the block isn't obviously global, i.e. it captures anything at 8856 // all, mark this full-expression as needing a cleanup. 8857 if (Result->getBlockDecl()->hasCaptures()) { 8858 ExprCleanupObjects.push_back(Result->getBlockDecl()); 8859 ExprNeedsCleanups = true; 8860 } 8861 8862 return Owned(Result); 8863} 8864 8865ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 8866 Expr *E, ParsedType Ty, 8867 SourceLocation RPLoc) { 8868 TypeSourceInfo *TInfo; 8869 GetTypeFromParser(Ty, &TInfo); 8870 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 8871} 8872 8873ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 8874 Expr *E, TypeSourceInfo *TInfo, 8875 SourceLocation RPLoc) { 8876 Expr *OrigExpr = E; 8877 8878 // Get the va_list type 8879 QualType VaListType = Context.getBuiltinVaListType(); 8880 if (VaListType->isArrayType()) { 8881 // Deal with implicit array decay; for example, on x86-64, 8882 // va_list is an array, but it's supposed to decay to 8883 // a pointer for va_arg. 8884 VaListType = Context.getArrayDecayedType(VaListType); 8885 // Make sure the input expression also decays appropriately. 8886 ExprResult Result = UsualUnaryConversions(E); 8887 if (Result.isInvalid()) 8888 return ExprError(); 8889 E = Result.take(); 8890 } else { 8891 // Otherwise, the va_list argument must be an l-value because 8892 // it is modified by va_arg. 8893 if (!E->isTypeDependent() && 8894 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 8895 return ExprError(); 8896 } 8897 8898 if (!E->isTypeDependent() && 8899 !Context.hasSameType(VaListType, E->getType())) { 8900 return ExprError(Diag(E->getLocStart(), 8901 diag::err_first_argument_to_va_arg_not_of_type_va_list) 8902 << OrigExpr->getType() << E->getSourceRange()); 8903 } 8904 8905 if (!TInfo->getType()->isDependentType()) { 8906 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 8907 PDiag(diag::err_second_parameter_to_va_arg_incomplete) 8908 << TInfo->getTypeLoc().getSourceRange())) 8909 return ExprError(); 8910 8911 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 8912 TInfo->getType(), 8913 PDiag(diag::err_second_parameter_to_va_arg_abstract) 8914 << TInfo->getTypeLoc().getSourceRange())) 8915 return ExprError(); 8916 8917 if (!TInfo->getType().isPODType(Context)) { 8918 Diag(TInfo->getTypeLoc().getBeginLoc(), 8919 TInfo->getType()->isObjCLifetimeType() 8920 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 8921 : diag::warn_second_parameter_to_va_arg_not_pod) 8922 << TInfo->getType() 8923 << TInfo->getTypeLoc().getSourceRange(); 8924 } 8925 8926 // Check for va_arg where arguments of the given type will be promoted 8927 // (i.e. this va_arg is guaranteed to have undefined behavior). 8928 QualType PromoteType; 8929 if (TInfo->getType()->isPromotableIntegerType()) { 8930 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 8931 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 8932 PromoteType = QualType(); 8933 } 8934 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 8935 PromoteType = Context.DoubleTy; 8936 if (!PromoteType.isNull()) 8937 Diag(TInfo->getTypeLoc().getBeginLoc(), 8938 diag::warn_second_parameter_to_va_arg_never_compatible) 8939 << TInfo->getType() 8940 << PromoteType 8941 << TInfo->getTypeLoc().getSourceRange(); 8942 } 8943 8944 QualType T = TInfo->getType().getNonLValueExprType(Context); 8945 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 8946} 8947 8948ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 8949 // The type of __null will be int or long, depending on the size of 8950 // pointers on the target. 8951 QualType Ty; 8952 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 8953 if (pw == Context.getTargetInfo().getIntWidth()) 8954 Ty = Context.IntTy; 8955 else if (pw == Context.getTargetInfo().getLongWidth()) 8956 Ty = Context.LongTy; 8957 else if (pw == Context.getTargetInfo().getLongLongWidth()) 8958 Ty = Context.LongLongTy; 8959 else { 8960 llvm_unreachable("I don't know size of pointer!"); 8961 } 8962 8963 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 8964} 8965 8966static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 8967 Expr *SrcExpr, FixItHint &Hint) { 8968 if (!SemaRef.getLangOptions().ObjC1) 8969 return; 8970 8971 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 8972 if (!PT) 8973 return; 8974 8975 // Check if the destination is of type 'id'. 8976 if (!PT->isObjCIdType()) { 8977 // Check if the destination is the 'NSString' interface. 8978 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 8979 if (!ID || !ID->getIdentifier()->isStr("NSString")) 8980 return; 8981 } 8982 8983 // Ignore any parens, implicit casts (should only be 8984 // array-to-pointer decays), and not-so-opaque values. The last is 8985 // important for making this trigger for property assignments. 8986 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 8987 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 8988 if (OV->getSourceExpr()) 8989 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 8990 8991 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 8992 if (!SL || !SL->isAscii()) 8993 return; 8994 8995 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 8996} 8997 8998bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 8999 SourceLocation Loc, 9000 QualType DstType, QualType SrcType, 9001 Expr *SrcExpr, AssignmentAction Action, 9002 bool *Complained) { 9003 if (Complained) 9004 *Complained = false; 9005 9006 // Decode the result (notice that AST's are still created for extensions). 9007 bool CheckInferredResultType = false; 9008 bool isInvalid = false; 9009 unsigned DiagKind = 0; 9010 FixItHint Hint; 9011 ConversionFixItGenerator ConvHints; 9012 bool MayHaveConvFixit = false; 9013 bool MayHaveFunctionDiff = false; 9014 9015 switch (ConvTy) { 9016 case Compatible: return false; 9017 case PointerToInt: 9018 DiagKind = diag::ext_typecheck_convert_pointer_int; 9019 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9020 MayHaveConvFixit = true; 9021 break; 9022 case IntToPointer: 9023 DiagKind = diag::ext_typecheck_convert_int_pointer; 9024 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9025 MayHaveConvFixit = true; 9026 break; 9027 case IncompatiblePointer: 9028 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 9029 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 9030 CheckInferredResultType = DstType->isObjCObjectPointerType() && 9031 SrcType->isObjCObjectPointerType(); 9032 if (Hint.isNull() && !CheckInferredResultType) { 9033 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9034 } 9035 MayHaveConvFixit = true; 9036 break; 9037 case IncompatiblePointerSign: 9038 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 9039 break; 9040 case FunctionVoidPointer: 9041 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 9042 break; 9043 case IncompatiblePointerDiscardsQualifiers: { 9044 // Perform array-to-pointer decay if necessary. 9045 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 9046 9047 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 9048 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 9049 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 9050 DiagKind = diag::err_typecheck_incompatible_address_space; 9051 break; 9052 9053 9054 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 9055 DiagKind = diag::err_typecheck_incompatible_ownership; 9056 break; 9057 } 9058 9059 llvm_unreachable("unknown error case for discarding qualifiers!"); 9060 // fallthrough 9061 } 9062 case CompatiblePointerDiscardsQualifiers: 9063 // If the qualifiers lost were because we were applying the 9064 // (deprecated) C++ conversion from a string literal to a char* 9065 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 9066 // Ideally, this check would be performed in 9067 // checkPointerTypesForAssignment. However, that would require a 9068 // bit of refactoring (so that the second argument is an 9069 // expression, rather than a type), which should be done as part 9070 // of a larger effort to fix checkPointerTypesForAssignment for 9071 // C++ semantics. 9072 if (getLangOptions().CPlusPlus && 9073 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 9074 return false; 9075 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 9076 break; 9077 case IncompatibleNestedPointerQualifiers: 9078 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 9079 break; 9080 case IntToBlockPointer: 9081 DiagKind = diag::err_int_to_block_pointer; 9082 break; 9083 case IncompatibleBlockPointer: 9084 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 9085 break; 9086 case IncompatibleObjCQualifiedId: 9087 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 9088 // it can give a more specific diagnostic. 9089 DiagKind = diag::warn_incompatible_qualified_id; 9090 break; 9091 case IncompatibleVectors: 9092 DiagKind = diag::warn_incompatible_vectors; 9093 break; 9094 case IncompatibleObjCWeakRef: 9095 DiagKind = diag::err_arc_weak_unavailable_assign; 9096 break; 9097 case Incompatible: 9098 DiagKind = diag::err_typecheck_convert_incompatible; 9099 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9100 MayHaveConvFixit = true; 9101 isInvalid = true; 9102 MayHaveFunctionDiff = true; 9103 break; 9104 } 9105 9106 QualType FirstType, SecondType; 9107 switch (Action) { 9108 case AA_Assigning: 9109 case AA_Initializing: 9110 // The destination type comes first. 9111 FirstType = DstType; 9112 SecondType = SrcType; 9113 break; 9114 9115 case AA_Returning: 9116 case AA_Passing: 9117 case AA_Converting: 9118 case AA_Sending: 9119 case AA_Casting: 9120 // The source type comes first. 9121 FirstType = SrcType; 9122 SecondType = DstType; 9123 break; 9124 } 9125 9126 PartialDiagnostic FDiag = PDiag(DiagKind); 9127 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 9128 9129 // If we can fix the conversion, suggest the FixIts. 9130 assert(ConvHints.isNull() || Hint.isNull()); 9131 if (!ConvHints.isNull()) { 9132 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 9133 HE = ConvHints.Hints.end(); HI != HE; ++HI) 9134 FDiag << *HI; 9135 } else { 9136 FDiag << Hint; 9137 } 9138 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 9139 9140 if (MayHaveFunctionDiff) 9141 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 9142 9143 Diag(Loc, FDiag); 9144 9145 if (SecondType == Context.OverloadTy) 9146 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 9147 FirstType); 9148 9149 if (CheckInferredResultType) 9150 EmitRelatedResultTypeNote(SrcExpr); 9151 9152 if (Complained) 9153 *Complained = true; 9154 return isInvalid; 9155} 9156 9157ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9158 llvm::APSInt *Result) { 9159 return VerifyIntegerConstantExpression(E, Result, 9160 PDiag(diag::err_expr_not_ice) << LangOpts.CPlusPlus); 9161} 9162 9163ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 9164 PartialDiagnostic NotIceDiag, 9165 bool AllowFold, 9166 PartialDiagnostic FoldDiag) { 9167 SourceLocation DiagLoc = E->getSourceRange().getBegin(); 9168 9169 if (getLangOptions().CPlusPlus0x) { 9170 // C++11 [expr.const]p5: 9171 // If an expression of literal class type is used in a context where an 9172 // integral constant expression is required, then that class type shall 9173 // have a single non-explicit conversion function to an integral or 9174 // unscoped enumeration type 9175 ExprResult Converted; 9176 if (NotIceDiag.getDiagID()) { 9177 Converted = ConvertToIntegralOrEnumerationType( 9178 DiagLoc, E, 9179 PDiag(diag::err_ice_not_integral), 9180 PDiag(diag::err_ice_incomplete_type), 9181 PDiag(diag::err_ice_explicit_conversion), 9182 PDiag(diag::note_ice_conversion_here), 9183 PDiag(diag::err_ice_ambiguous_conversion), 9184 PDiag(diag::note_ice_conversion_here), 9185 PDiag(0), 9186 /*AllowScopedEnumerations*/ false); 9187 } else { 9188 // The caller wants to silently enquire whether this is an ICE. Don't 9189 // produce any diagnostics if it isn't. 9190 Converted = ConvertToIntegralOrEnumerationType( 9191 DiagLoc, E, PDiag(), PDiag(), PDiag(), PDiag(), 9192 PDiag(), PDiag(), PDiag(), false); 9193 } 9194 if (Converted.isInvalid()) 9195 return Converted; 9196 E = Converted.take(); 9197 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 9198 return ExprError(); 9199 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 9200 // An ICE must be of integral or unscoped enumeration type. 9201 if (NotIceDiag.getDiagID()) 9202 Diag(DiagLoc, NotIceDiag) << E->getSourceRange(); 9203 return ExprError(); 9204 } 9205 9206 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 9207 // in the non-ICE case. 9208 if (!getLangOptions().CPlusPlus0x && E->isIntegerConstantExpr(Context)) { 9209 if (Result) 9210 *Result = E->EvaluateKnownConstInt(Context); 9211 return Owned(E); 9212 } 9213 9214 Expr::EvalResult EvalResult; 9215 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 9216 EvalResult.Diag = &Notes; 9217 9218 // Try to evaluate the expression, and produce diagnostics explaining why it's 9219 // not a constant expression as a side-effect. 9220 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 9221 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 9222 9223 // In C++11, we can rely on diagnostics being produced for any expression 9224 // which is not a constant expression. If no diagnostics were produced, then 9225 // this is a constant expression. 9226 if (Folded && getLangOptions().CPlusPlus0x && Notes.empty()) { 9227 if (Result) 9228 *Result = EvalResult.Val.getInt(); 9229 return Owned(E); 9230 } 9231 9232 // If our only note is the usual "invalid subexpression" note, just point 9233 // the caret at its location rather than producing an essentially 9234 // redundant note. 9235 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9236 diag::note_invalid_subexpr_in_const_expr) { 9237 DiagLoc = Notes[0].first; 9238 Notes.clear(); 9239 } 9240 9241 if (!Folded || !AllowFold) { 9242 if (NotIceDiag.getDiagID()) { 9243 Diag(DiagLoc, NotIceDiag) << E->getSourceRange(); 9244 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9245 Diag(Notes[I].first, Notes[I].second); 9246 } 9247 9248 return ExprError(); 9249 } 9250 9251 if (FoldDiag.getDiagID()) 9252 Diag(DiagLoc, FoldDiag) << E->getSourceRange(); 9253 else 9254 Diag(DiagLoc, diag::ext_expr_not_ice) 9255 << E->getSourceRange() << LangOpts.CPlusPlus; 9256 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9257 Diag(Notes[I].first, Notes[I].second); 9258 9259 if (Result) 9260 *Result = EvalResult.Val.getInt(); 9261 return Owned(E); 9262} 9263 9264namespace { 9265 // Handle the case where we conclude a expression which we speculatively 9266 // considered to be unevaluated is actually evaluated. 9267 class TransformToPE : public TreeTransform<TransformToPE> { 9268 typedef TreeTransform<TransformToPE> BaseTransform; 9269 9270 public: 9271 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 9272 9273 // Make sure we redo semantic analysis 9274 bool AlwaysRebuild() { return true; } 9275 9276 // Make sure we handle LabelStmts correctly. 9277 // FIXME: This does the right thing, but maybe we need a more general 9278 // fix to TreeTransform? 9279 StmtResult TransformLabelStmt(LabelStmt *S) { 9280 S->getDecl()->setStmt(0); 9281 return BaseTransform::TransformLabelStmt(S); 9282 } 9283 9284 // We need to special-case DeclRefExprs referring to FieldDecls which 9285 // are not part of a member pointer formation; normal TreeTransforming 9286 // doesn't catch this case because of the way we represent them in the AST. 9287 // FIXME: This is a bit ugly; is it really the best way to handle this 9288 // case? 9289 // 9290 // Error on DeclRefExprs referring to FieldDecls. 9291 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 9292 if (isa<FieldDecl>(E->getDecl()) && 9293 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated) 9294 return SemaRef.Diag(E->getLocation(), 9295 diag::err_invalid_non_static_member_use) 9296 << E->getDecl() << E->getSourceRange(); 9297 9298 return BaseTransform::TransformDeclRefExpr(E); 9299 } 9300 9301 // Exception: filter out member pointer formation 9302 ExprResult TransformUnaryOperator(UnaryOperator *E) { 9303 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 9304 return E; 9305 9306 return BaseTransform::TransformUnaryOperator(E); 9307 } 9308 9309 ExprResult TransformLambdaExpr(LambdaExpr *E) { 9310 // Lambdas never need to be transformed. 9311 return E; 9312 } 9313 }; 9314} 9315 9316ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) { 9317 assert(ExprEvalContexts.back().Context == Unevaluated && 9318 "Should only transform unevaluated expressions"); 9319 ExprEvalContexts.back().Context = 9320 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 9321 if (ExprEvalContexts.back().Context == Unevaluated) 9322 return E; 9323 return TransformToPE(*this).TransformExpr(E); 9324} 9325 9326void 9327Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 9328 Decl *LambdaContextDecl, 9329 bool IsDecltype) { 9330 ExprEvalContexts.push_back( 9331 ExpressionEvaluationContextRecord(NewContext, 9332 ExprCleanupObjects.size(), 9333 ExprNeedsCleanups, 9334 LambdaContextDecl, 9335 IsDecltype)); 9336 ExprNeedsCleanups = false; 9337 if (!MaybeODRUseExprs.empty()) 9338 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 9339} 9340 9341void Sema::PopExpressionEvaluationContext() { 9342 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 9343 9344 if (!Rec.Lambdas.empty()) { 9345 if (Rec.Context == Unevaluated) { 9346 // C++11 [expr.prim.lambda]p2: 9347 // A lambda-expression shall not appear in an unevaluated operand 9348 // (Clause 5). 9349 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 9350 Diag(Rec.Lambdas[I]->getLocStart(), 9351 diag::err_lambda_unevaluated_operand); 9352 } else { 9353 // Mark the capture expressions odr-used. This was deferred 9354 // during lambda expression creation. 9355 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 9356 LambdaExpr *Lambda = Rec.Lambdas[I]; 9357 for (LambdaExpr::capture_init_iterator 9358 C = Lambda->capture_init_begin(), 9359 CEnd = Lambda->capture_init_end(); 9360 C != CEnd; ++C) { 9361 MarkDeclarationsReferencedInExpr(*C); 9362 } 9363 } 9364 } 9365 } 9366 9367 // When are coming out of an unevaluated context, clear out any 9368 // temporaries that we may have created as part of the evaluation of 9369 // the expression in that context: they aren't relevant because they 9370 // will never be constructed. 9371 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) { 9372 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 9373 ExprCleanupObjects.end()); 9374 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 9375 CleanupVarDeclMarking(); 9376 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 9377 // Otherwise, merge the contexts together. 9378 } else { 9379 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 9380 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 9381 Rec.SavedMaybeODRUseExprs.end()); 9382 } 9383 9384 // Pop the current expression evaluation context off the stack. 9385 ExprEvalContexts.pop_back(); 9386} 9387 9388void Sema::DiscardCleanupsInEvaluationContext() { 9389 ExprCleanupObjects.erase( 9390 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 9391 ExprCleanupObjects.end()); 9392 ExprNeedsCleanups = false; 9393 MaybeODRUseExprs.clear(); 9394} 9395 9396ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 9397 if (!E->getType()->isVariablyModifiedType()) 9398 return E; 9399 return TranformToPotentiallyEvaluated(E); 9400} 9401 9402static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 9403 // Do not mark anything as "used" within a dependent context; wait for 9404 // an instantiation. 9405 if (SemaRef.CurContext->isDependentContext()) 9406 return false; 9407 9408 switch (SemaRef.ExprEvalContexts.back().Context) { 9409 case Sema::Unevaluated: 9410 // We are in an expression that is not potentially evaluated; do nothing. 9411 // (Depending on how you read the standard, we actually do need to do 9412 // something here for null pointer constants, but the standard's 9413 // definition of a null pointer constant is completely crazy.) 9414 return false; 9415 9416 case Sema::ConstantEvaluated: 9417 case Sema::PotentiallyEvaluated: 9418 // We are in a potentially evaluated expression (or a constant-expression 9419 // in C++03); we need to do implicit template instantiation, implicitly 9420 // define class members, and mark most declarations as used. 9421 return true; 9422 9423 case Sema::PotentiallyEvaluatedIfUsed: 9424 // Referenced declarations will only be used if the construct in the 9425 // containing expression is used. 9426 return false; 9427 } 9428 llvm_unreachable("Invalid context"); 9429} 9430 9431/// \brief Mark a function referenced, and check whether it is odr-used 9432/// (C++ [basic.def.odr]p2, C99 6.9p3) 9433void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 9434 assert(Func && "No function?"); 9435 9436 Func->setReferenced(); 9437 9438 // Don't mark this function as used multiple times, unless it's a constexpr 9439 // function which we need to instantiate. 9440 if (Func->isUsed(false) && 9441 !(Func->isConstexpr() && !Func->getBody() && 9442 Func->isImplicitlyInstantiable())) 9443 return; 9444 9445 if (!IsPotentiallyEvaluatedContext(*this)) 9446 return; 9447 9448 // Note that this declaration has been used. 9449 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 9450 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 9451 if (Constructor->isDefaultConstructor()) { 9452 if (Constructor->isTrivial()) 9453 return; 9454 if (!Constructor->isUsed(false)) 9455 DefineImplicitDefaultConstructor(Loc, Constructor); 9456 } else if (Constructor->isCopyConstructor()) { 9457 if (!Constructor->isUsed(false)) 9458 DefineImplicitCopyConstructor(Loc, Constructor); 9459 } else if (Constructor->isMoveConstructor()) { 9460 if (!Constructor->isUsed(false)) 9461 DefineImplicitMoveConstructor(Loc, Constructor); 9462 } 9463 } 9464 9465 MarkVTableUsed(Loc, Constructor->getParent()); 9466 } else if (CXXDestructorDecl *Destructor = 9467 dyn_cast<CXXDestructorDecl>(Func)) { 9468 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 9469 !Destructor->isUsed(false)) 9470 DefineImplicitDestructor(Loc, Destructor); 9471 if (Destructor->isVirtual()) 9472 MarkVTableUsed(Loc, Destructor->getParent()); 9473 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 9474 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 9475 MethodDecl->isOverloadedOperator() && 9476 MethodDecl->getOverloadedOperator() == OO_Equal) { 9477 if (!MethodDecl->isUsed(false)) { 9478 if (MethodDecl->isCopyAssignmentOperator()) 9479 DefineImplicitCopyAssignment(Loc, MethodDecl); 9480 else 9481 DefineImplicitMoveAssignment(Loc, MethodDecl); 9482 } 9483 } else if (isa<CXXConversionDecl>(MethodDecl) && 9484 MethodDecl->getParent()->isLambda()) { 9485 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 9486 if (Conversion->isLambdaToBlockPointerConversion()) 9487 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 9488 else 9489 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 9490 } else if (MethodDecl->isVirtual()) 9491 MarkVTableUsed(Loc, MethodDecl->getParent()); 9492 } 9493 9494 // Recursive functions should be marked when used from another function. 9495 // FIXME: Is this really right? 9496 if (CurContext == Func) return; 9497 9498 // Implicit instantiation of function templates and member functions of 9499 // class templates. 9500 if (Func->isImplicitlyInstantiable()) { 9501 bool AlreadyInstantiated = false; 9502 SourceLocation PointOfInstantiation = Loc; 9503 if (FunctionTemplateSpecializationInfo *SpecInfo 9504 = Func->getTemplateSpecializationInfo()) { 9505 if (SpecInfo->getPointOfInstantiation().isInvalid()) 9506 SpecInfo->setPointOfInstantiation(Loc); 9507 else if (SpecInfo->getTemplateSpecializationKind() 9508 == TSK_ImplicitInstantiation) { 9509 AlreadyInstantiated = true; 9510 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 9511 } 9512 } else if (MemberSpecializationInfo *MSInfo 9513 = Func->getMemberSpecializationInfo()) { 9514 if (MSInfo->getPointOfInstantiation().isInvalid()) 9515 MSInfo->setPointOfInstantiation(Loc); 9516 else if (MSInfo->getTemplateSpecializationKind() 9517 == TSK_ImplicitInstantiation) { 9518 AlreadyInstantiated = true; 9519 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 9520 } 9521 } 9522 9523 if (!AlreadyInstantiated || Func->isConstexpr()) { 9524 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 9525 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass()) 9526 PendingLocalImplicitInstantiations.push_back( 9527 std::make_pair(Func, PointOfInstantiation)); 9528 else if (Func->isConstexpr()) 9529 // Do not defer instantiations of constexpr functions, to avoid the 9530 // expression evaluator needing to call back into Sema if it sees a 9531 // call to such a function. 9532 InstantiateFunctionDefinition(PointOfInstantiation, Func); 9533 else { 9534 PendingInstantiations.push_back(std::make_pair(Func, 9535 PointOfInstantiation)); 9536 // Notify the consumer that a function was implicitly instantiated. 9537 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 9538 } 9539 } 9540 } else { 9541 // Walk redefinitions, as some of them may be instantiable. 9542 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 9543 e(Func->redecls_end()); i != e; ++i) { 9544 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 9545 MarkFunctionReferenced(Loc, *i); 9546 } 9547 } 9548 9549 // Keep track of used but undefined functions. 9550 if (!Func->isPure() && !Func->hasBody() && 9551 Func->getLinkage() != ExternalLinkage) { 9552 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()]; 9553 if (old.isInvalid()) old = Loc; 9554 } 9555 9556 Func->setUsed(true); 9557} 9558 9559static void 9560diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 9561 VarDecl *var, DeclContext *DC) { 9562 DeclContext *VarDC = var->getDeclContext(); 9563 9564 // If the parameter still belongs to the translation unit, then 9565 // we're actually just using one parameter in the declaration of 9566 // the next. 9567 if (isa<ParmVarDecl>(var) && 9568 isa<TranslationUnitDecl>(VarDC)) 9569 return; 9570 9571 // For C code, don't diagnose about capture if we're not actually in code 9572 // right now; it's impossible to write a non-constant expression outside of 9573 // function context, so we'll get other (more useful) diagnostics later. 9574 // 9575 // For C++, things get a bit more nasty... it would be nice to suppress this 9576 // diagnostic for certain cases like using a local variable in an array bound 9577 // for a member of a local class, but the correct predicate is not obvious. 9578 if (!S.getLangOptions().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 9579 return; 9580 9581 if (isa<CXXMethodDecl>(VarDC) && 9582 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 9583 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 9584 << var->getIdentifier(); 9585 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 9586 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 9587 << var->getIdentifier() << fn->getDeclName(); 9588 } else if (isa<BlockDecl>(VarDC)) { 9589 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 9590 << var->getIdentifier(); 9591 } else { 9592 // FIXME: Is there any other context where a local variable can be 9593 // declared? 9594 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 9595 << var->getIdentifier(); 9596 } 9597 9598 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 9599 << var->getIdentifier(); 9600 9601 // FIXME: Add additional diagnostic info about class etc. which prevents 9602 // capture. 9603} 9604 9605/// \brief Capture the given variable in the given lambda expression. 9606static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 9607 VarDecl *Var, QualType FieldType, 9608 QualType DeclRefType, 9609 SourceLocation Loc) { 9610 CXXRecordDecl *Lambda = LSI->Lambda; 9611 9612 // Build the non-static data member. 9613 FieldDecl *Field 9614 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 9615 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 9616 0, false, false); 9617 Field->setImplicit(true); 9618 Field->setAccess(AS_private); 9619 Lambda->addDecl(Field); 9620 9621 // C++11 [expr.prim.lambda]p21: 9622 // When the lambda-expression is evaluated, the entities that 9623 // are captured by copy are used to direct-initialize each 9624 // corresponding non-static data member of the resulting closure 9625 // object. (For array members, the array elements are 9626 // direct-initialized in increasing subscript order.) These 9627 // initializations are performed in the (unspecified) order in 9628 // which the non-static data members are declared. 9629 9630 // Introduce a new evaluation context for the initialization, so 9631 // that temporaries introduced as part of the capture are retained 9632 // to be re-"exported" from the lambda expression itself. 9633 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 9634 9635 // C++ [expr.prim.labda]p12: 9636 // An entity captured by a lambda-expression is odr-used (3.2) in 9637 // the scope containing the lambda-expression. 9638 Expr *Ref = new (S.Context) DeclRefExpr(Var, DeclRefType, VK_LValue, Loc); 9639 Var->setReferenced(true); 9640 Var->setUsed(true); 9641 9642 // When the field has array type, create index variables for each 9643 // dimension of the array. We use these index variables to subscript 9644 // the source array, and other clients (e.g., CodeGen) will perform 9645 // the necessary iteration with these index variables. 9646 SmallVector<VarDecl *, 4> IndexVariables; 9647 QualType BaseType = FieldType; 9648 QualType SizeType = S.Context.getSizeType(); 9649 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 9650 while (const ConstantArrayType *Array 9651 = S.Context.getAsConstantArrayType(BaseType)) { 9652 // Create the iteration variable for this array index. 9653 IdentifierInfo *IterationVarName = 0; 9654 { 9655 SmallString<8> Str; 9656 llvm::raw_svector_ostream OS(Str); 9657 OS << "__i" << IndexVariables.size(); 9658 IterationVarName = &S.Context.Idents.get(OS.str()); 9659 } 9660 VarDecl *IterationVar 9661 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9662 IterationVarName, SizeType, 9663 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9664 SC_None, SC_None); 9665 IndexVariables.push_back(IterationVar); 9666 LSI->ArrayIndexVars.push_back(IterationVar); 9667 9668 // Create a reference to the iteration variable. 9669 ExprResult IterationVarRef 9670 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 9671 assert(!IterationVarRef.isInvalid() && 9672 "Reference to invented variable cannot fail!"); 9673 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 9674 assert(!IterationVarRef.isInvalid() && 9675 "Conversion of invented variable cannot fail!"); 9676 9677 // Subscript the array with this iteration variable. 9678 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 9679 Ref, Loc, IterationVarRef.take(), Loc); 9680 if (Subscript.isInvalid()) { 9681 S.CleanupVarDeclMarking(); 9682 S.DiscardCleanupsInEvaluationContext(); 9683 S.PopExpressionEvaluationContext(); 9684 return ExprError(); 9685 } 9686 9687 Ref = Subscript.take(); 9688 BaseType = Array->getElementType(); 9689 } 9690 9691 // Construct the entity that we will be initializing. For an array, this 9692 // will be first element in the array, which may require several levels 9693 // of array-subscript entities. 9694 SmallVector<InitializedEntity, 4> Entities; 9695 Entities.reserve(1 + IndexVariables.size()); 9696 Entities.push_back( 9697 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 9698 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 9699 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 9700 0, 9701 Entities.back())); 9702 9703 InitializationKind InitKind 9704 = InitializationKind::CreateDirect(Loc, Loc, Loc); 9705 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1); 9706 ExprResult Result(true); 9707 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1)) 9708 Result = Init.Perform(S, Entities.back(), InitKind, 9709 MultiExprArg(S, &Ref, 1)); 9710 9711 // If this initialization requires any cleanups (e.g., due to a 9712 // default argument to a copy constructor), note that for the 9713 // lambda. 9714 if (S.ExprNeedsCleanups) 9715 LSI->ExprNeedsCleanups = true; 9716 9717 // Exit the expression evaluation context used for the capture. 9718 S.CleanupVarDeclMarking(); 9719 S.DiscardCleanupsInEvaluationContext(); 9720 S.PopExpressionEvaluationContext(); 9721 return Result; 9722} 9723 9724bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 9725 TryCaptureKind Kind, SourceLocation EllipsisLoc, 9726 bool BuildAndDiagnose, 9727 QualType &CaptureType, 9728 QualType &DeclRefType) { 9729 bool Nested = false; 9730 9731 DeclContext *DC = CurContext; 9732 if (Var->getDeclContext() == DC) return true; 9733 if (!Var->hasLocalStorage()) return true; 9734 9735 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 9736 9737 // Walk up the stack to determine whether we can capture the variable, 9738 // performing the "simple" checks that don't depend on type. We stop when 9739 // we've either hit the declared scope of the variable or find an existing 9740 // capture of that variable. 9741 CaptureType = Var->getType(); 9742 DeclRefType = CaptureType.getNonReferenceType(); 9743 bool Explicit = (Kind != TryCapture_Implicit); 9744 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 9745 do { 9746 // Only block literals and lambda expressions can capture; other 9747 // scopes don't work. 9748 DeclContext *ParentDC; 9749 if (isa<BlockDecl>(DC)) 9750 ParentDC = DC->getParent(); 9751 else if (isa<CXXMethodDecl>(DC) && 9752 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 9753 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 9754 ParentDC = DC->getParent()->getParent(); 9755 else { 9756 if (BuildAndDiagnose) 9757 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 9758 return true; 9759 } 9760 9761 CapturingScopeInfo *CSI = 9762 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 9763 9764 // Check whether we've already captured it. 9765 if (CSI->CaptureMap.count(Var)) { 9766 // If we found a capture, any subcaptures are nested. 9767 Nested = true; 9768 9769 // Retrieve the capture type for this variable. 9770 CaptureType = CSI->getCapture(Var).getCaptureType(); 9771 9772 // Compute the type of an expression that refers to this variable. 9773 DeclRefType = CaptureType.getNonReferenceType(); 9774 9775 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 9776 if (Cap.isCopyCapture() && 9777 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 9778 DeclRefType.addConst(); 9779 break; 9780 } 9781 9782 bool IsBlock = isa<BlockScopeInfo>(CSI); 9783 bool IsLambda = !IsBlock; 9784 9785 // Lambdas are not allowed to capture unnamed variables 9786 // (e.g. anonymous unions). 9787 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 9788 // assuming that's the intent. 9789 if (IsLambda && !Var->getDeclName()) { 9790 if (BuildAndDiagnose) { 9791 Diag(Loc, diag::err_lambda_capture_anonymous_var); 9792 Diag(Var->getLocation(), diag::note_declared_at); 9793 } 9794 return true; 9795 } 9796 9797 // Prohibit variably-modified types; they're difficult to deal with. 9798 if (Var->getType()->isVariablyModifiedType()) { 9799 if (BuildAndDiagnose) { 9800 if (IsBlock) 9801 Diag(Loc, diag::err_ref_vm_type); 9802 else 9803 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 9804 Diag(Var->getLocation(), diag::note_previous_decl) 9805 << Var->getDeclName(); 9806 } 9807 return true; 9808 } 9809 9810 // Lambdas are not allowed to capture __block variables; they don't 9811 // support the expected semantics. 9812 if (IsLambda && HasBlocksAttr) { 9813 if (BuildAndDiagnose) { 9814 Diag(Loc, diag::err_lambda_capture_block) 9815 << Var->getDeclName(); 9816 Diag(Var->getLocation(), diag::note_previous_decl) 9817 << Var->getDeclName(); 9818 } 9819 return true; 9820 } 9821 9822 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 9823 // No capture-default 9824 if (BuildAndDiagnose) { 9825 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 9826 Diag(Var->getLocation(), diag::note_previous_decl) 9827 << Var->getDeclName(); 9828 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 9829 diag::note_lambda_decl); 9830 } 9831 return true; 9832 } 9833 9834 FunctionScopesIndex--; 9835 DC = ParentDC; 9836 Explicit = false; 9837 } while (!Var->getDeclContext()->Equals(DC)); 9838 9839 // Walk back down the scope stack, computing the type of the capture at 9840 // each step, checking type-specific requirements, and adding captures if 9841 // requested. 9842 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 9843 ++I) { 9844 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 9845 9846 // Compute the type of the capture and of a reference to the capture within 9847 // this scope. 9848 if (isa<BlockScopeInfo>(CSI)) { 9849 Expr *CopyExpr = 0; 9850 bool ByRef = false; 9851 9852 // Blocks are not allowed to capture arrays. 9853 if (CaptureType->isArrayType()) { 9854 if (BuildAndDiagnose) { 9855 Diag(Loc, diag::err_ref_array_type); 9856 Diag(Var->getLocation(), diag::note_previous_decl) 9857 << Var->getDeclName(); 9858 } 9859 return true; 9860 } 9861 9862 if (HasBlocksAttr || CaptureType->isReferenceType()) { 9863 // Block capture by reference does not change the capture or 9864 // declaration reference types. 9865 ByRef = true; 9866 } else { 9867 // Block capture by copy introduces 'const'. 9868 CaptureType = CaptureType.getNonReferenceType().withConst(); 9869 DeclRefType = CaptureType; 9870 9871 if (getLangOptions().CPlusPlus && BuildAndDiagnose) { 9872 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 9873 // The capture logic needs the destructor, so make sure we mark it. 9874 // Usually this is unnecessary because most local variables have 9875 // their destructors marked at declaration time, but parameters are 9876 // an exception because it's technically only the call site that 9877 // actually requires the destructor. 9878 if (isa<ParmVarDecl>(Var)) 9879 FinalizeVarWithDestructor(Var, Record); 9880 9881 // According to the blocks spec, the capture of a variable from 9882 // the stack requires a const copy constructor. This is not true 9883 // of the copy/move done to move a __block variable to the heap. 9884 Expr *DeclRef = new (Context) DeclRefExpr(Var, 9885 DeclRefType.withConst(), 9886 VK_LValue, Loc); 9887 ExprResult Result 9888 = PerformCopyInitialization( 9889 InitializedEntity::InitializeBlock(Var->getLocation(), 9890 CaptureType, false), 9891 Loc, Owned(DeclRef)); 9892 9893 // Build a full-expression copy expression if initialization 9894 // succeeded and used a non-trivial constructor. Recover from 9895 // errors by pretending that the copy isn't necessary. 9896 if (!Result.isInvalid() && 9897 !cast<CXXConstructExpr>(Result.get())->getConstructor() 9898 ->isTrivial()) { 9899 Result = MaybeCreateExprWithCleanups(Result); 9900 CopyExpr = Result.take(); 9901 } 9902 } 9903 } 9904 } 9905 9906 // Actually capture the variable. 9907 if (BuildAndDiagnose) 9908 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 9909 SourceLocation(), CaptureType, CopyExpr); 9910 Nested = true; 9911 continue; 9912 } 9913 9914 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 9915 9916 // Determine whether we are capturing by reference or by value. 9917 bool ByRef = false; 9918 if (I == N - 1 && Kind != TryCapture_Implicit) { 9919 ByRef = (Kind == TryCapture_ExplicitByRef); 9920 } else { 9921 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 9922 } 9923 9924 // Compute the type of the field that will capture this variable. 9925 if (ByRef) { 9926 // C++11 [expr.prim.lambda]p15: 9927 // An entity is captured by reference if it is implicitly or 9928 // explicitly captured but not captured by copy. It is 9929 // unspecified whether additional unnamed non-static data 9930 // members are declared in the closure type for entities 9931 // captured by reference. 9932 // 9933 // FIXME: It is not clear whether we want to build an lvalue reference 9934 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 9935 // to do the former, while EDG does the latter. Core issue 1249 will 9936 // clarify, but for now we follow GCC because it's a more permissive and 9937 // easily defensible position. 9938 CaptureType = Context.getLValueReferenceType(DeclRefType); 9939 } else { 9940 // C++11 [expr.prim.lambda]p14: 9941 // For each entity captured by copy, an unnamed non-static 9942 // data member is declared in the closure type. The 9943 // declaration order of these members is unspecified. The type 9944 // of such a data member is the type of the corresponding 9945 // captured entity if the entity is not a reference to an 9946 // object, or the referenced type otherwise. [Note: If the 9947 // captured entity is a reference to a function, the 9948 // corresponding data member is also a reference to a 9949 // function. - end note ] 9950 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 9951 if (!RefType->getPointeeType()->isFunctionType()) 9952 CaptureType = RefType->getPointeeType(); 9953 } 9954 } 9955 9956 // Capture this variable in the lambda. 9957 Expr *CopyExpr = 0; 9958 if (BuildAndDiagnose) { 9959 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 9960 DeclRefType, Loc); 9961 if (!Result.isInvalid()) 9962 CopyExpr = Result.take(); 9963 } 9964 9965 // Compute the type of a reference to this captured variable. 9966 if (ByRef) 9967 DeclRefType = CaptureType.getNonReferenceType(); 9968 else { 9969 // C++ [expr.prim.lambda]p5: 9970 // The closure type for a lambda-expression has a public inline 9971 // function call operator [...]. This function call operator is 9972 // declared const (9.3.1) if and only if the lambda-expression’s 9973 // parameter-declaration-clause is not followed by mutable. 9974 DeclRefType = CaptureType.getNonReferenceType(); 9975 if (!LSI->Mutable && !CaptureType->isReferenceType()) 9976 DeclRefType.addConst(); 9977 } 9978 9979 // Add the capture. 9980 if (BuildAndDiagnose) 9981 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 9982 EllipsisLoc, CaptureType, CopyExpr); 9983 Nested = true; 9984 } 9985 9986 return false; 9987} 9988 9989bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 9990 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 9991 QualType CaptureType; 9992 QualType DeclRefType; 9993 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 9994 /*BuildAndDiagnose=*/true, CaptureType, 9995 DeclRefType); 9996} 9997 9998QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 9999 QualType CaptureType; 10000 QualType DeclRefType; 10001 10002 // Determine whether we can capture this variable. 10003 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 10004 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 10005 return QualType(); 10006 10007 return DeclRefType; 10008} 10009 10010static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 10011 SourceLocation Loc) { 10012 // Keep track of used but undefined variables. 10013 // FIXME: We shouldn't suppress this warning for static data members. 10014 if (Var->hasDefinition() == VarDecl::DeclarationOnly && 10015 Var->getLinkage() != ExternalLinkage && 10016 !(Var->isStaticDataMember() && Var->hasInit())) { 10017 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()]; 10018 if (old.isInvalid()) old = Loc; 10019 } 10020 10021 SemaRef.tryCaptureVariable(Var, Loc); 10022 10023 Var->setUsed(true); 10024} 10025 10026void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 10027 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 10028 // an object that satisfies the requirements for appearing in a 10029 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 10030 // is immediately applied." This function handles the lvalue-to-rvalue 10031 // conversion part. 10032 MaybeODRUseExprs.erase(E->IgnoreParens()); 10033} 10034 10035ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 10036 if (!Res.isUsable()) 10037 return Res; 10038 10039 // If a constant-expression is a reference to a variable where we delay 10040 // deciding whether it is an odr-use, just assume we will apply the 10041 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 10042 // (a non-type template argument), we have special handling anyway. 10043 UpdateMarkingForLValueToRValue(Res.get()); 10044 return Res; 10045} 10046 10047void Sema::CleanupVarDeclMarking() { 10048 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 10049 e = MaybeODRUseExprs.end(); 10050 i != e; ++i) { 10051 VarDecl *Var; 10052 SourceLocation Loc; 10053 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(*i)) { 10054 Var = BDRE->getDecl(); 10055 Loc = BDRE->getLocation(); 10056 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 10057 Var = cast<VarDecl>(DRE->getDecl()); 10058 Loc = DRE->getLocation(); 10059 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 10060 Var = cast<VarDecl>(ME->getMemberDecl()); 10061 Loc = ME->getMemberLoc(); 10062 } else { 10063 llvm_unreachable("Unexpcted expression"); 10064 } 10065 10066 MarkVarDeclODRUsed(*this, Var, Loc); 10067 } 10068 10069 MaybeODRUseExprs.clear(); 10070} 10071 10072// Mark a VarDecl referenced, and perform the necessary handling to compute 10073// odr-uses. 10074static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 10075 VarDecl *Var, Expr *E) { 10076 Var->setReferenced(); 10077 10078 if (!IsPotentiallyEvaluatedContext(SemaRef)) 10079 return; 10080 10081 // Implicit instantiation of static data members of class templates. 10082 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 10083 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 10084 assert(MSInfo && "Missing member specialization information?"); 10085 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 10086 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 10087 (!AlreadyInstantiated || Var->isUsableInConstantExpressions())) { 10088 if (!AlreadyInstantiated) { 10089 // This is a modification of an existing AST node. Notify listeners. 10090 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 10091 L->StaticDataMemberInstantiated(Var); 10092 MSInfo->setPointOfInstantiation(Loc); 10093 } 10094 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10095 if (Var->isUsableInConstantExpressions()) 10096 // Do not defer instantiations of variables which could be used in a 10097 // constant expression. 10098 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 10099 else 10100 SemaRef.PendingInstantiations.push_back( 10101 std::make_pair(Var, PointOfInstantiation)); 10102 } 10103 } 10104 10105 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 10106 // an object that satisfies the requirements for appearing in a 10107 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 10108 // is immediately applied." We check the first part here, and 10109 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 10110 // Note that we use the C++11 definition everywhere because nothing in 10111 // C++03 depends on whether we get the C++03 version correct. This does not 10112 // apply to references, since they are not objects. 10113 const VarDecl *DefVD; 10114 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() && 10115 Var->isUsableInConstantExpressions() && 10116 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) 10117 SemaRef.MaybeODRUseExprs.insert(E); 10118 else 10119 MarkVarDeclODRUsed(SemaRef, Var, Loc); 10120} 10121 10122/// \brief Mark a variable referenced, and check whether it is odr-used 10123/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 10124/// used directly for normal expressions referring to VarDecl. 10125void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 10126 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 10127} 10128 10129static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 10130 Decl *D, Expr *E) { 10131 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 10132 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 10133 return; 10134 } 10135 10136 SemaRef.MarkAnyDeclReferenced(Loc, D); 10137} 10138 10139/// \brief Perform reference-marking and odr-use handling for a 10140/// BlockDeclRefExpr. 10141void Sema::MarkBlockDeclRefReferenced(BlockDeclRefExpr *E) { 10142 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E); 10143} 10144 10145/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 10146void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 10147 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E); 10148} 10149 10150/// \brief Perform reference-marking and odr-use handling for a MemberExpr. 10151void Sema::MarkMemberReferenced(MemberExpr *E) { 10152 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E); 10153} 10154 10155/// \brief Perform marking for a reference to an arbitrary declaration. It 10156/// marks the declaration referenced, and performs odr-use checking for functions 10157/// and variables. This method should not be used when building an normal 10158/// expression which refers to a variable. 10159void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) { 10160 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 10161 MarkVariableReferenced(Loc, VD); 10162 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 10163 MarkFunctionReferenced(Loc, FD); 10164 else 10165 D->setReferenced(); 10166} 10167 10168namespace { 10169 // Mark all of the declarations referenced 10170 // FIXME: Not fully implemented yet! We need to have a better understanding 10171 // of when we're entering 10172 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 10173 Sema &S; 10174 SourceLocation Loc; 10175 10176 public: 10177 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 10178 10179 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 10180 10181 bool TraverseTemplateArgument(const TemplateArgument &Arg); 10182 bool TraverseRecordType(RecordType *T); 10183 }; 10184} 10185 10186bool MarkReferencedDecls::TraverseTemplateArgument( 10187 const TemplateArgument &Arg) { 10188 if (Arg.getKind() == TemplateArgument::Declaration) { 10189 S.MarkAnyDeclReferenced(Loc, Arg.getAsDecl()); 10190 } 10191 10192 return Inherited::TraverseTemplateArgument(Arg); 10193} 10194 10195bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 10196 if (ClassTemplateSpecializationDecl *Spec 10197 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 10198 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 10199 return TraverseTemplateArguments(Args.data(), Args.size()); 10200 } 10201 10202 return true; 10203} 10204 10205void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 10206 MarkReferencedDecls Marker(*this, Loc); 10207 Marker.TraverseType(Context.getCanonicalType(T)); 10208} 10209 10210namespace { 10211 /// \brief Helper class that marks all of the declarations referenced by 10212 /// potentially-evaluated subexpressions as "referenced". 10213 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 10214 Sema &S; 10215 bool SkipLocalVariables; 10216 10217 public: 10218 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 10219 10220 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 10221 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 10222 10223 void VisitDeclRefExpr(DeclRefExpr *E) { 10224 // If we were asked not to visit local variables, don't. 10225 if (SkipLocalVariables) { 10226 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 10227 if (VD->hasLocalStorage()) 10228 return; 10229 } 10230 10231 S.MarkDeclRefReferenced(E); 10232 } 10233 10234 void VisitMemberExpr(MemberExpr *E) { 10235 S.MarkMemberReferenced(E); 10236 Inherited::VisitMemberExpr(E); 10237 } 10238 10239 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 10240 S.MarkFunctionReferenced(E->getLocStart(), 10241 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 10242 Visit(E->getSubExpr()); 10243 } 10244 10245 void VisitCXXNewExpr(CXXNewExpr *E) { 10246 if (E->getOperatorNew()) 10247 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 10248 if (E->getOperatorDelete()) 10249 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 10250 Inherited::VisitCXXNewExpr(E); 10251 } 10252 10253 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 10254 if (E->getOperatorDelete()) 10255 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 10256 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 10257 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 10258 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 10259 S.MarkFunctionReferenced(E->getLocStart(), 10260 S.LookupDestructor(Record)); 10261 } 10262 10263 Inherited::VisitCXXDeleteExpr(E); 10264 } 10265 10266 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10267 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 10268 Inherited::VisitCXXConstructExpr(E); 10269 } 10270 10271 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { 10272 // If we were asked not to visit local variables, don't. 10273 if (SkipLocalVariables && E->getDecl()->hasLocalStorage()) 10274 return; 10275 10276 S.MarkBlockDeclRefReferenced(E); 10277 } 10278 10279 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 10280 Visit(E->getExpr()); 10281 } 10282 10283 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10284 Inherited::VisitImplicitCastExpr(E); 10285 10286 if (E->getCastKind() == CK_LValueToRValue) 10287 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 10288 } 10289 }; 10290} 10291 10292/// \brief Mark any declarations that appear within this expression or any 10293/// potentially-evaluated subexpressions as "referenced". 10294/// 10295/// \param SkipLocalVariables If true, don't mark local variables as 10296/// 'referenced'. 10297void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 10298 bool SkipLocalVariables) { 10299 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 10300} 10301 10302/// \brief Emit a diagnostic that describes an effect on the run-time behavior 10303/// of the program being compiled. 10304/// 10305/// This routine emits the given diagnostic when the code currently being 10306/// type-checked is "potentially evaluated", meaning that there is a 10307/// possibility that the code will actually be executable. Code in sizeof() 10308/// expressions, code used only during overload resolution, etc., are not 10309/// potentially evaluated. This routine will suppress such diagnostics or, 10310/// in the absolutely nutty case of potentially potentially evaluated 10311/// expressions (C++ typeid), queue the diagnostic to potentially emit it 10312/// later. 10313/// 10314/// This routine should be used for all diagnostics that describe the run-time 10315/// behavior of a program, such as passing a non-POD value through an ellipsis. 10316/// Failure to do so will likely result in spurious diagnostics or failures 10317/// during overload resolution or within sizeof/alignof/typeof/typeid. 10318bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 10319 const PartialDiagnostic &PD) { 10320 switch (ExprEvalContexts.back().Context) { 10321 case Unevaluated: 10322 // The argument will never be evaluated, so don't complain. 10323 break; 10324 10325 case ConstantEvaluated: 10326 // Relevant diagnostics should be produced by constant evaluation. 10327 break; 10328 10329 case PotentiallyEvaluated: 10330 case PotentiallyEvaluatedIfUsed: 10331 if (Statement && getCurFunctionOrMethodDecl()) { 10332 FunctionScopes.back()->PossiblyUnreachableDiags. 10333 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 10334 } 10335 else 10336 Diag(Loc, PD); 10337 10338 return true; 10339 } 10340 10341 return false; 10342} 10343 10344bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 10345 CallExpr *CE, FunctionDecl *FD) { 10346 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 10347 return false; 10348 10349 // If we're inside a decltype's expression, don't check for a valid return 10350 // type or construct temporaries until we know whether this is the last call. 10351 if (ExprEvalContexts.back().IsDecltype) { 10352 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 10353 return false; 10354 } 10355 10356 PartialDiagnostic Note = 10357 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here) 10358 << FD->getDeclName() : PDiag(); 10359 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation(); 10360 10361 if (RequireCompleteType(Loc, ReturnType, 10362 FD ? 10363 PDiag(diag::err_call_function_incomplete_return) 10364 << CE->getSourceRange() << FD->getDeclName() : 10365 PDiag(diag::err_call_incomplete_return) 10366 << CE->getSourceRange(), 10367 std::make_pair(NoteLoc, Note))) 10368 return true; 10369 10370 return false; 10371} 10372 10373// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 10374// will prevent this condition from triggering, which is what we want. 10375void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 10376 SourceLocation Loc; 10377 10378 unsigned diagnostic = diag::warn_condition_is_assignment; 10379 bool IsOrAssign = false; 10380 10381 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 10382 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 10383 return; 10384 10385 IsOrAssign = Op->getOpcode() == BO_OrAssign; 10386 10387 // Greylist some idioms by putting them into a warning subcategory. 10388 if (ObjCMessageExpr *ME 10389 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 10390 Selector Sel = ME->getSelector(); 10391 10392 // self = [<foo> init...] 10393 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 10394 diagnostic = diag::warn_condition_is_idiomatic_assignment; 10395 10396 // <foo> = [<bar> nextObject] 10397 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 10398 diagnostic = diag::warn_condition_is_idiomatic_assignment; 10399 } 10400 10401 Loc = Op->getOperatorLoc(); 10402 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 10403 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 10404 return; 10405 10406 IsOrAssign = Op->getOperator() == OO_PipeEqual; 10407 Loc = Op->getOperatorLoc(); 10408 } else { 10409 // Not an assignment. 10410 return; 10411 } 10412 10413 Diag(Loc, diagnostic) << E->getSourceRange(); 10414 10415 SourceLocation Open = E->getSourceRange().getBegin(); 10416 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 10417 Diag(Loc, diag::note_condition_assign_silence) 10418 << FixItHint::CreateInsertion(Open, "(") 10419 << FixItHint::CreateInsertion(Close, ")"); 10420 10421 if (IsOrAssign) 10422 Diag(Loc, diag::note_condition_or_assign_to_comparison) 10423 << FixItHint::CreateReplacement(Loc, "!="); 10424 else 10425 Diag(Loc, diag::note_condition_assign_to_comparison) 10426 << FixItHint::CreateReplacement(Loc, "=="); 10427} 10428 10429/// \brief Redundant parentheses over an equality comparison can indicate 10430/// that the user intended an assignment used as condition. 10431void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 10432 // Don't warn if the parens came from a macro. 10433 SourceLocation parenLoc = ParenE->getLocStart(); 10434 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 10435 return; 10436 // Don't warn for dependent expressions. 10437 if (ParenE->isTypeDependent()) 10438 return; 10439 10440 Expr *E = ParenE->IgnoreParens(); 10441 10442 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 10443 if (opE->getOpcode() == BO_EQ && 10444 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 10445 == Expr::MLV_Valid) { 10446 SourceLocation Loc = opE->getOperatorLoc(); 10447 10448 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 10449 Diag(Loc, diag::note_equality_comparison_silence) 10450 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin()) 10451 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd()); 10452 Diag(Loc, diag::note_equality_comparison_to_assign) 10453 << FixItHint::CreateReplacement(Loc, "="); 10454 } 10455} 10456 10457ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 10458 DiagnoseAssignmentAsCondition(E); 10459 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 10460 DiagnoseEqualityWithExtraParens(parenE); 10461 10462 ExprResult result = CheckPlaceholderExpr(E); 10463 if (result.isInvalid()) return ExprError(); 10464 E = result.take(); 10465 10466 if (!E->isTypeDependent()) { 10467 if (getLangOptions().CPlusPlus) 10468 return CheckCXXBooleanCondition(E); // C++ 6.4p4 10469 10470 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 10471 if (ERes.isInvalid()) 10472 return ExprError(); 10473 E = ERes.take(); 10474 10475 QualType T = E->getType(); 10476 if (!T->isScalarType()) { // C99 6.8.4.1p1 10477 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 10478 << T << E->getSourceRange(); 10479 return ExprError(); 10480 } 10481 } 10482 10483 return Owned(E); 10484} 10485 10486ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 10487 Expr *SubExpr) { 10488 if (!SubExpr) 10489 return ExprError(); 10490 10491 return CheckBooleanCondition(SubExpr, Loc); 10492} 10493 10494namespace { 10495 /// A visitor for rebuilding a call to an __unknown_any expression 10496 /// to have an appropriate type. 10497 struct RebuildUnknownAnyFunction 10498 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 10499 10500 Sema &S; 10501 10502 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 10503 10504 ExprResult VisitStmt(Stmt *S) { 10505 llvm_unreachable("unexpected statement!"); 10506 } 10507 10508 ExprResult VisitExpr(Expr *E) { 10509 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 10510 << E->getSourceRange(); 10511 return ExprError(); 10512 } 10513 10514 /// Rebuild an expression which simply semantically wraps another 10515 /// expression which it shares the type and value kind of. 10516 template <class T> ExprResult rebuildSugarExpr(T *E) { 10517 ExprResult SubResult = Visit(E->getSubExpr()); 10518 if (SubResult.isInvalid()) return ExprError(); 10519 10520 Expr *SubExpr = SubResult.take(); 10521 E->setSubExpr(SubExpr); 10522 E->setType(SubExpr->getType()); 10523 E->setValueKind(SubExpr->getValueKind()); 10524 assert(E->getObjectKind() == OK_Ordinary); 10525 return E; 10526 } 10527 10528 ExprResult VisitParenExpr(ParenExpr *E) { 10529 return rebuildSugarExpr(E); 10530 } 10531 10532 ExprResult VisitUnaryExtension(UnaryOperator *E) { 10533 return rebuildSugarExpr(E); 10534 } 10535 10536 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 10537 ExprResult SubResult = Visit(E->getSubExpr()); 10538 if (SubResult.isInvalid()) return ExprError(); 10539 10540 Expr *SubExpr = SubResult.take(); 10541 E->setSubExpr(SubExpr); 10542 E->setType(S.Context.getPointerType(SubExpr->getType())); 10543 assert(E->getValueKind() == VK_RValue); 10544 assert(E->getObjectKind() == OK_Ordinary); 10545 return E; 10546 } 10547 10548 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 10549 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 10550 10551 E->setType(VD->getType()); 10552 10553 assert(E->getValueKind() == VK_RValue); 10554 if (S.getLangOptions().CPlusPlus && 10555 !(isa<CXXMethodDecl>(VD) && 10556 cast<CXXMethodDecl>(VD)->isInstance())) 10557 E->setValueKind(VK_LValue); 10558 10559 return E; 10560 } 10561 10562 ExprResult VisitMemberExpr(MemberExpr *E) { 10563 return resolveDecl(E, E->getMemberDecl()); 10564 } 10565 10566 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 10567 return resolveDecl(E, E->getDecl()); 10568 } 10569 }; 10570} 10571 10572/// Given a function expression of unknown-any type, try to rebuild it 10573/// to have a function type. 10574static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 10575 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 10576 if (Result.isInvalid()) return ExprError(); 10577 return S.DefaultFunctionArrayConversion(Result.take()); 10578} 10579 10580namespace { 10581 /// A visitor for rebuilding an expression of type __unknown_anytype 10582 /// into one which resolves the type directly on the referring 10583 /// expression. Strict preservation of the original source 10584 /// structure is not a goal. 10585 struct RebuildUnknownAnyExpr 10586 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 10587 10588 Sema &S; 10589 10590 /// The current destination type. 10591 QualType DestType; 10592 10593 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 10594 : S(S), DestType(CastType) {} 10595 10596 ExprResult VisitStmt(Stmt *S) { 10597 llvm_unreachable("unexpected statement!"); 10598 } 10599 10600 ExprResult VisitExpr(Expr *E) { 10601 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 10602 << E->getSourceRange(); 10603 return ExprError(); 10604 } 10605 10606 ExprResult VisitCallExpr(CallExpr *E); 10607 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 10608 10609 /// Rebuild an expression which simply semantically wraps another 10610 /// expression which it shares the type and value kind of. 10611 template <class T> ExprResult rebuildSugarExpr(T *E) { 10612 ExprResult SubResult = Visit(E->getSubExpr()); 10613 if (SubResult.isInvalid()) return ExprError(); 10614 Expr *SubExpr = SubResult.take(); 10615 E->setSubExpr(SubExpr); 10616 E->setType(SubExpr->getType()); 10617 E->setValueKind(SubExpr->getValueKind()); 10618 assert(E->getObjectKind() == OK_Ordinary); 10619 return E; 10620 } 10621 10622 ExprResult VisitParenExpr(ParenExpr *E) { 10623 return rebuildSugarExpr(E); 10624 } 10625 10626 ExprResult VisitUnaryExtension(UnaryOperator *E) { 10627 return rebuildSugarExpr(E); 10628 } 10629 10630 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 10631 const PointerType *Ptr = DestType->getAs<PointerType>(); 10632 if (!Ptr) { 10633 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 10634 << E->getSourceRange(); 10635 return ExprError(); 10636 } 10637 assert(E->getValueKind() == VK_RValue); 10638 assert(E->getObjectKind() == OK_Ordinary); 10639 E->setType(DestType); 10640 10641 // Build the sub-expression as if it were an object of the pointee type. 10642 DestType = Ptr->getPointeeType(); 10643 ExprResult SubResult = Visit(E->getSubExpr()); 10644 if (SubResult.isInvalid()) return ExprError(); 10645 E->setSubExpr(SubResult.take()); 10646 return E; 10647 } 10648 10649 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 10650 10651 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 10652 10653 ExprResult VisitMemberExpr(MemberExpr *E) { 10654 return resolveDecl(E, E->getMemberDecl()); 10655 } 10656 10657 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 10658 return resolveDecl(E, E->getDecl()); 10659 } 10660 }; 10661} 10662 10663/// Rebuilds a call expression which yielded __unknown_anytype. 10664ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 10665 Expr *CalleeExpr = E->getCallee(); 10666 10667 enum FnKind { 10668 FK_MemberFunction, 10669 FK_FunctionPointer, 10670 FK_BlockPointer 10671 }; 10672 10673 FnKind Kind; 10674 QualType CalleeType = CalleeExpr->getType(); 10675 if (CalleeType == S.Context.BoundMemberTy) { 10676 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 10677 Kind = FK_MemberFunction; 10678 CalleeType = Expr::findBoundMemberType(CalleeExpr); 10679 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 10680 CalleeType = Ptr->getPointeeType(); 10681 Kind = FK_FunctionPointer; 10682 } else { 10683 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 10684 Kind = FK_BlockPointer; 10685 } 10686 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 10687 10688 // Verify that this is a legal result type of a function. 10689 if (DestType->isArrayType() || DestType->isFunctionType()) { 10690 unsigned diagID = diag::err_func_returning_array_function; 10691 if (Kind == FK_BlockPointer) 10692 diagID = diag::err_block_returning_array_function; 10693 10694 S.Diag(E->getExprLoc(), diagID) 10695 << DestType->isFunctionType() << DestType; 10696 return ExprError(); 10697 } 10698 10699 // Otherwise, go ahead and set DestType as the call's result. 10700 E->setType(DestType.getNonLValueExprType(S.Context)); 10701 E->setValueKind(Expr::getValueKindForType(DestType)); 10702 assert(E->getObjectKind() == OK_Ordinary); 10703 10704 // Rebuild the function type, replacing the result type with DestType. 10705 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 10706 DestType = S.Context.getFunctionType(DestType, 10707 Proto->arg_type_begin(), 10708 Proto->getNumArgs(), 10709 Proto->getExtProtoInfo()); 10710 else 10711 DestType = S.Context.getFunctionNoProtoType(DestType, 10712 FnType->getExtInfo()); 10713 10714 // Rebuild the appropriate pointer-to-function type. 10715 switch (Kind) { 10716 case FK_MemberFunction: 10717 // Nothing to do. 10718 break; 10719 10720 case FK_FunctionPointer: 10721 DestType = S.Context.getPointerType(DestType); 10722 break; 10723 10724 case FK_BlockPointer: 10725 DestType = S.Context.getBlockPointerType(DestType); 10726 break; 10727 } 10728 10729 // Finally, we can recurse. 10730 ExprResult CalleeResult = Visit(CalleeExpr); 10731 if (!CalleeResult.isUsable()) return ExprError(); 10732 E->setCallee(CalleeResult.take()); 10733 10734 // Bind a temporary if necessary. 10735 return S.MaybeBindToTemporary(E); 10736} 10737 10738ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 10739 // Verify that this is a legal result type of a call. 10740 if (DestType->isArrayType() || DestType->isFunctionType()) { 10741 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 10742 << DestType->isFunctionType() << DestType; 10743 return ExprError(); 10744 } 10745 10746 // Rewrite the method result type if available. 10747 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 10748 assert(Method->getResultType() == S.Context.UnknownAnyTy); 10749 Method->setResultType(DestType); 10750 } 10751 10752 // Change the type of the message. 10753 E->setType(DestType.getNonReferenceType()); 10754 E->setValueKind(Expr::getValueKindForType(DestType)); 10755 10756 return S.MaybeBindToTemporary(E); 10757} 10758 10759ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 10760 // The only case we should ever see here is a function-to-pointer decay. 10761 assert(E->getCastKind() == CK_FunctionToPointerDecay); 10762 assert(E->getValueKind() == VK_RValue); 10763 assert(E->getObjectKind() == OK_Ordinary); 10764 10765 E->setType(DestType); 10766 10767 // Rebuild the sub-expression as the pointee (function) type. 10768 DestType = DestType->castAs<PointerType>()->getPointeeType(); 10769 10770 ExprResult Result = Visit(E->getSubExpr()); 10771 if (!Result.isUsable()) return ExprError(); 10772 10773 E->setSubExpr(Result.take()); 10774 return S.Owned(E); 10775} 10776 10777ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 10778 ExprValueKind ValueKind = VK_LValue; 10779 QualType Type = DestType; 10780 10781 // We know how to make this work for certain kinds of decls: 10782 10783 // - functions 10784 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 10785 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 10786 DestType = Ptr->getPointeeType(); 10787 ExprResult Result = resolveDecl(E, VD); 10788 if (Result.isInvalid()) return ExprError(); 10789 return S.ImpCastExprToType(Result.take(), Type, 10790 CK_FunctionToPointerDecay, VK_RValue); 10791 } 10792 10793 if (!Type->isFunctionType()) { 10794 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 10795 << VD << E->getSourceRange(); 10796 return ExprError(); 10797 } 10798 10799 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 10800 if (MD->isInstance()) { 10801 ValueKind = VK_RValue; 10802 Type = S.Context.BoundMemberTy; 10803 } 10804 10805 // Function references aren't l-values in C. 10806 if (!S.getLangOptions().CPlusPlus) 10807 ValueKind = VK_RValue; 10808 10809 // - variables 10810 } else if (isa<VarDecl>(VD)) { 10811 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 10812 Type = RefTy->getPointeeType(); 10813 } else if (Type->isFunctionType()) { 10814 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 10815 << VD << E->getSourceRange(); 10816 return ExprError(); 10817 } 10818 10819 // - nothing else 10820 } else { 10821 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 10822 << VD << E->getSourceRange(); 10823 return ExprError(); 10824 } 10825 10826 VD->setType(DestType); 10827 E->setType(Type); 10828 E->setValueKind(ValueKind); 10829 return S.Owned(E); 10830} 10831 10832/// Check a cast of an unknown-any type. We intentionally only 10833/// trigger this for C-style casts. 10834ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 10835 Expr *CastExpr, CastKind &CastKind, 10836 ExprValueKind &VK, CXXCastPath &Path) { 10837 // Rewrite the casted expression from scratch. 10838 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 10839 if (!result.isUsable()) return ExprError(); 10840 10841 CastExpr = result.take(); 10842 VK = CastExpr->getValueKind(); 10843 CastKind = CK_NoOp; 10844 10845 return CastExpr; 10846} 10847 10848ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 10849 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 10850} 10851 10852static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 10853 Expr *orig = E; 10854 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 10855 while (true) { 10856 E = E->IgnoreParenImpCasts(); 10857 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 10858 E = call->getCallee(); 10859 diagID = diag::err_uncasted_call_of_unknown_any; 10860 } else { 10861 break; 10862 } 10863 } 10864 10865 SourceLocation loc; 10866 NamedDecl *d; 10867 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 10868 loc = ref->getLocation(); 10869 d = ref->getDecl(); 10870 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 10871 loc = mem->getMemberLoc(); 10872 d = mem->getMemberDecl(); 10873 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 10874 diagID = diag::err_uncasted_call_of_unknown_any; 10875 loc = msg->getSelectorStartLoc(); 10876 d = msg->getMethodDecl(); 10877 if (!d) { 10878 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 10879 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 10880 << orig->getSourceRange(); 10881 return ExprError(); 10882 } 10883 } else { 10884 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 10885 << E->getSourceRange(); 10886 return ExprError(); 10887 } 10888 10889 S.Diag(loc, diagID) << d << orig->getSourceRange(); 10890 10891 // Never recoverable. 10892 return ExprError(); 10893} 10894 10895/// Check for operands with placeholder types and complain if found. 10896/// Returns true if there was an error and no recovery was possible. 10897ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 10898 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 10899 if (!placeholderType) return Owned(E); 10900 10901 switch (placeholderType->getKind()) { 10902 10903 // Overloaded expressions. 10904 case BuiltinType::Overload: { 10905 // Try to resolve a single function template specialization. 10906 // This is obligatory. 10907 ExprResult result = Owned(E); 10908 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 10909 return result; 10910 10911 // If that failed, try to recover with a call. 10912 } else { 10913 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 10914 /*complain*/ true); 10915 return result; 10916 } 10917 } 10918 10919 // Bound member functions. 10920 case BuiltinType::BoundMember: { 10921 ExprResult result = Owned(E); 10922 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 10923 /*complain*/ true); 10924 return result; 10925 } 10926 10927 // ARC unbridged casts. 10928 case BuiltinType::ARCUnbridgedCast: { 10929 Expr *realCast = stripARCUnbridgedCast(E); 10930 diagnoseARCUnbridgedCast(realCast); 10931 return Owned(realCast); 10932 } 10933 10934 // Expressions of unknown type. 10935 case BuiltinType::UnknownAny: 10936 return diagnoseUnknownAnyExpr(*this, E); 10937 10938 // Pseudo-objects. 10939 case BuiltinType::PseudoObject: 10940 return checkPseudoObjectRValue(E); 10941 10942 // Everything else should be impossible. 10943#define BUILTIN_TYPE(Id, SingletonId) \ 10944 case BuiltinType::Id: 10945#define PLACEHOLDER_TYPE(Id, SingletonId) 10946#include "clang/AST/BuiltinTypes.def" 10947 break; 10948 } 10949 10950 llvm_unreachable("invalid placeholder type!"); 10951} 10952 10953bool Sema::CheckCaseExpression(Expr *E) { 10954 if (E->isTypeDependent()) 10955 return true; 10956 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 10957 return E->getType()->isIntegralOrEnumerationType(); 10958 return false; 10959} 10960